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
dotnet__aspnetcore
src/Shared/BrowserTesting/src/BrowserKind.cs
{ "start": 209, "end": 287 }
public enum ____ { Chromium = 1, Firefox = 2, Webkit = 4 }
BrowserKind
csharp
louthy__language-ext
LanguageExt.Core/Class Instances/Eq/EqEither.cs
{ "start": 1446, "end": 2104 }
public struct ____<L, R> : Eq<Either<L, R>> { /// <summary> /// Equality test /// </summary> [Pure] public static bool Equals(Either<L, R> x, Either<L, R> y) => EqEither<EqDefault<L>, EqDefault<R>, L, R>.Equals(x, y); /// <summary> /// Get hash code of the value /// </summary> /// <param name="x">Value to get the hash code of</param> /// <returns>The hash code of x</returns> [Pure] public static int GetHashCode(Either<L, R> x) => HashableEither<HashableDefault<L>, HashableDefault<R>, L, R>.GetHashCode(x); } }
EqEither
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Managers/IOpenIdScopeManager.cs
{ "start": 185, "end": 551 }
interface ____ not meant to be implemented by custom managers, /// that should inherit from the generic OpenIdScopeManager class. /// It is primarily intended to be used by services that cannot easily /// depend on the generic scope manager. The actual scope entity type is /// automatically determined at runtime based on the OpenIddict core options. /// </summary>
is
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.ZeroCore.OpenIddict/OpenIddict/Scopes/AbpOpenIddictScopeStore.cs
{ "start": 372, "end": 14239 }
public class ____ : AbpOpenIddictStoreBase<IOpenIddictScopeRepository>, IOpenIddictScopeStore<OpenIddictScopeModel> { public AbpOpenIddictScopeStore( IOpenIddictScopeRepository repository, IUnitOfWorkManager unitOfWorkManager, IGuidGenerator guidGenerator, IOpenIddictDbConcurrencyExceptionHandler concurrencyExceptionHandler) : base(repository, unitOfWorkManager, guidGenerator, concurrencyExceptionHandler) { } public virtual async ValueTask<long> CountAsync(CancellationToken cancellationToken) { return await Repository.GetCountAsync(string.Empty, cancellationToken); } public virtual ValueTask<long> CountAsync<TResult>( Func<IQueryable<OpenIddictScopeModel>, IQueryable<TResult>> query, CancellationToken cancellationToken) { throw new NotSupportedException(); } public virtual async ValueTask CreateAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); await Repository.InsertAsync(scope.ToEntity()); scope = (await Repository.FindByIdAsync(scope.Id, cancellationToken: cancellationToken)).ToModel(); } public virtual async ValueTask DeleteAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); try { await Repository.DeleteAsync(scope.Id); } catch (AbpDbConcurrencyException e) { Logger.LogError(e, e.Message); await ConcurrencyExceptionHandler.HandleAsync(e); throw new OpenIddictExceptions.ConcurrencyException(e.Message, e.InnerException); } } public virtual async ValueTask<OpenIddictScopeModel> FindByIdAsync(string identifier, CancellationToken cancellationToken) { Check.NotNullOrEmpty(identifier, nameof(identifier)); return (await Repository.FindByIdAsync(Guid.Parse(identifier), cancellationToken)) .ToModel(); } public virtual async ValueTask<OpenIddictScopeModel> FindByNameAsync(string name, CancellationToken cancellationToken) { Check.NotNullOrEmpty(name, nameof(name)); return (await Repository.FindByNameAsync(name, cancellationToken)).ToModel(); } public virtual async IAsyncEnumerable<OpenIddictScopeModel> FindByNamesAsync(ImmutableArray<string> names, [EnumeratorCancellation] CancellationToken cancellationToken) { Check.NotNull(names, nameof(names)); foreach (var name in names) { Check.NotNullOrEmpty(name, nameof(name)); } var scopes = await Repository.FindByNamesAsync(names.ToArray(), cancellationToken); foreach (var scope in scopes) { yield return scope.ToModel(); } } public virtual async IAsyncEnumerable<OpenIddictScopeModel> FindByResourceAsync(string resource, [EnumeratorCancellation] CancellationToken cancellationToken) { Check.NotNullOrEmpty(resource, nameof(resource)); var scopes = await Repository.FindByResourceAsync(resource, cancellationToken); foreach (var scope in scopes) { var resources = await GetResourcesAsync(scope.ToModel(), cancellationToken); if (resources.Contains(resource, StringComparer.Ordinal)) { yield return scope.ToModel(); } } } public virtual ValueTask<TResult> GetAsync<TState, TResult>( Func<IQueryable<OpenIddictScopeModel>, TState, IQueryable<TResult>> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException(); } public virtual ValueTask<string> GetDescriptionAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); return new ValueTask<string>(scope.Description); } public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync( OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (string.IsNullOrEmpty(scope.Descriptions)) { return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary .Create<CultureInfo, string>()); } using (var document = JsonDocument.Parse(scope.Descriptions)) { var builder = ImmutableDictionary.CreateBuilder<CultureInfo, string>(); foreach (var property in document.RootElement.EnumerateObject()) { var value = property.Value.GetString(); if (string.IsNullOrEmpty(value)) { continue; } builder[CultureInfo.GetCultureInfo(property.Name)] = value; } return new ValueTask<ImmutableDictionary<CultureInfo, string>>(builder.ToImmutable()); } } public virtual ValueTask<string> GetDisplayNameAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); return new ValueTask<string>(scope.DisplayName); } public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync( OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (string.IsNullOrEmpty(scope.DisplayNames)) { return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary .Create<CultureInfo, string>()); } using (var document = JsonDocument.Parse(scope.DisplayNames)) { var builder = ImmutableDictionary.CreateBuilder<CultureInfo, string>(); foreach (var property in document.RootElement.EnumerateObject()) { var value = property.Value.GetString(); if (string.IsNullOrEmpty(value)) { continue; } builder[CultureInfo.GetCultureInfo(property.Name)] = value; } return new ValueTask<ImmutableDictionary<CultureInfo, string>>(builder.ToImmutable()); } } public virtual ValueTask<string> GetIdAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); return new ValueTask<string>(scope.Id.ToString()); } public virtual ValueTask<string> GetNameAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); return new ValueTask<string>(scope.Name); } public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync( OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (string.IsNullOrEmpty(scope.Properties)) { return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary .Create<string, JsonElement>()); } using (var document = JsonDocument.Parse(scope.Properties)) { var builder = ImmutableDictionary.CreateBuilder<string, JsonElement>(); foreach (var property in document.RootElement.EnumerateObject()) { builder[property.Name] = property.Value.Clone(); } return new ValueTask<ImmutableDictionary<string, JsonElement>>(builder.ToImmutable()); } } public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (string.IsNullOrEmpty(scope.Resources)) { return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); } using (var document = JsonDocument.Parse(scope.Resources)) { var builder = ImmutableArray.CreateBuilder<string>(document.RootElement.GetArrayLength()); foreach (var element in document.RootElement.EnumerateArray()) { var value = element.GetString(); if (string.IsNullOrEmpty(value)) { continue; } builder.Add(value); } return new ValueTask<ImmutableArray<string>>(builder.ToImmutable()); } } public virtual ValueTask<OpenIddictScopeModel> InstantiateAsync(CancellationToken cancellationToken) { return new ValueTask<OpenIddictScopeModel>(new OpenIddictScopeModel { Id = GuidGenerator.Create() }); } public virtual async IAsyncEnumerable<OpenIddictScopeModel> ListAsync(int? count, int? offset, [EnumeratorCancellation] CancellationToken cancellationToken) { var scopes = await Repository.ListAsync(count, offset, cancellationToken); foreach (var scope in scopes) { yield return scope.ToModel(); } } public IAsyncEnumerable<TResult> ListAsync<TState, TResult>( Func<IQueryable<OpenIddictScopeModel>, TState, IQueryable<TResult>> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException(); } public virtual ValueTask SetDescriptionAsync(OpenIddictScopeModel scope, string description, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); scope.Description = description; return default; } public virtual ValueTask SetDescriptionsAsync(OpenIddictScopeModel scope, ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (descriptions is null || descriptions.IsEmpty) { scope.Descriptions = null; return default; } scope.Descriptions = WriteStream(writer => { writer.WriteStartObject(); foreach (var description in descriptions) { writer.WritePropertyName(description.Key.Name); writer.WriteStringValue(description.Value); } writer.WriteEndObject(); }); return default; } public virtual ValueTask SetDisplayNameAsync(OpenIddictScopeModel scope, string name, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); scope.DisplayName = name; return default; } public virtual ValueTask SetDisplayNamesAsync(OpenIddictScopeModel scope, ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (names is null || names.IsEmpty) { scope.DisplayNames = null; return default; } scope.DisplayNames = WriteStream(writer => { writer.WriteStartObject(); foreach (var name in names) { writer.WritePropertyName(name.Key.Name); writer.WriteStringValue(name.Value); } writer.WriteEndObject(); }); return default; } public virtual ValueTask SetNameAsync(OpenIddictScopeModel scope, string name, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); scope.Name = name; return default; } public virtual ValueTask SetPropertiesAsync(OpenIddictScopeModel scope, ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (properties is null || properties.IsEmpty) { scope.Properties = null; return default; } scope.Properties = WriteStream(writer => { writer.WriteStartObject(); foreach (var property in properties) { writer.WritePropertyName(property.Key); property.Value.WriteTo(writer); } writer.WriteEndObject(); }); return default; } public virtual ValueTask SetResourcesAsync(OpenIddictScopeModel scope, ImmutableArray<string> resources, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); if (resources.IsDefaultOrEmpty) { scope.Resources = null; return default; } scope.Resources = WriteStream(writer => { writer.WriteStartArray(); foreach (var resource in resources) { writer.WriteStringValue(resource); } writer.WriteEndArray(); }); return default; } public virtual async ValueTask UpdateAsync(OpenIddictScopeModel scope, CancellationToken cancellationToken) { Check.NotNull(scope, nameof(scope)); var entity = await Repository.GetAsync(scope.Id); try { await Repository.UpdateAsync(scope.ToEntity(entity)); } catch (AbpDbConcurrencyException e) { Logger.LogError(e, e.Message); await ConcurrencyExceptionHandler.HandleAsync(e); throw new OpenIddictExceptions.ConcurrencyException(e.Message, e.InnerException); } scope = (await Repository.FindByIdAsync(entity.Id, cancellationToken)).ToModel(); } }
AbpOpenIddictScopeStore
csharp
dotnet__maui
src/Controls/tests/ManualTests/Performance/CollectionViewPool/Models/Enums.cs
{ "start": 2066, "end": 2121 }
public enum ____ { Farenheit, Celsius }
TemperatureUnit
csharp
dotnet__efcore
test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs
{ "start": 30346, "end": 30877 }
private class ____<T>( Func<T, Expression> literalExpressionFunc) : RelationalTypeMapping("storeType", typeof(SimpleTestType)) { private readonly Func<T, Expression> _literalExpressionFunc = literalExpressionFunc; public override Expression GenerateCodeLiteral(object value) => _literalExpressionFunc((T)value); protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => throw new NotSupportedException(); }
SimpleTestTypeMapping
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue9686.cs
{ "start": 1578, "end": 2389 }
public class ____ : List<_9686Item>, INotifyPropertyChanged { string _groupName; public string GroupName { get => _groupName; set => SetField(ref _groupName, value); } public _9686Group(string groupName, ObservableCollection<_9686Item> items) : base(items) { GroupName = groupName; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } }
_9686Group
csharp
dotnet__machinelearning
src/Microsoft.ML.StandardTrainers/Standard/PoissonRegression/PoissonRegression.cs
{ "start": 3164, "end": 4053 }
public sealed class ____ : LbfgsTrainerBase<LbfgsPoissonRegressionTrainer.Options, RegressionPredictionTransformer<PoissonRegressionModelParameters>, PoissonRegressionModelParameters> { internal const string LoadNameValue = "PoissonRegression"; internal const string UserNameValue = "Poisson Regression"; internal const string ShortName = "PR"; internal const string Summary = "Poisson Regression assumes the unknown function, denoted Y has a Poisson distribution."; /// <summary> /// Options for the <see cref="LbfgsPoissonRegressionTrainer"/> as used in /// [LbfgsPoissonRegression(Options)](xref:Microsoft.ML.StandardTrainersCatalog.LbfgsPoissonRegression(Microsoft.ML.RegressionCatalog.RegressionTrainers,Microsoft.ML.Trainers.LbfgsPoissonRegressionTrainer.Options)). /// </summary>
LbfgsPoissonRegressionTrainer
csharp
dotnet__orleans
src/Orleans.Serialization/Invocation/Response.cs
{ "start": 4758, "end": 5978 }
public sealed class ____<TResult> : Response { [Id(0)] private TResult? _result; public TResult? TypedResult { get => _result; set => _result = value; } public override Exception? Exception { get => null; set => throw new InvalidOperationException($"Cannot set {nameof(Exception)} property for type {nameof(Response<TResult>)}"); } public override object? Result { get => _result; set => _result = (TResult?)value; } public override Type GetSimpleResultType() => typeof(TResult); public override T GetResult<T>() { if (typeof(TResult).IsValueType && typeof(T).IsValueType && typeof(T) == typeof(TResult)) return Unsafe.As<TResult, T>(ref _result!); return (T)(object)_result!; } public override void Dispose() { _result = default; ResponsePool.Return(this); } public override string ToString() => _result?.ToString() ?? "[null]"; } /// <summary> /// Supports raw serialization of <see cref="Response{TResult}"/> values. /// </summary>
Response
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Tests/Helpers/DummyTracker.cs
{ "start": 231, "end": 674 }
internal class ____ : IResourceMonitor { public const double CpuPercentage = 50.0; public const double MemoryPercentage = 10.0; public const ulong MemoryUsed = 100; public const ulong MemoryTotal = 1000; public const uint CpuUnits = 1; public ResourceUtilization GetUtilization(TimeSpan aggregationPeriod) => new(CpuPercentage, MemoryUsed, new SystemResources(CpuUnits, CpuUnits, MemoryTotal, MemoryTotal)); }
DummyTracker
csharp
dotnet__aspnetcore
src/Components/Components/test/PersistentState/PersistentComponentStateTest.cs
{ "start": 369, "end": 10468 }
public class ____ { [Fact] public void InitializeExistingState_SetupsState() { // Arrange var applicationState = new PersistentComponentState(new Dictionary<string, byte[]>(), [], []); var existingState = new Dictionary<string, byte[]> { ["MyState"] = JsonSerializer.SerializeToUtf8Bytes(new byte[] { 1, 2, 3, 4 }) }; // Act applicationState.InitializeExistingState(existingState, RestoreContext.InitialValue); // Assert Assert.True(applicationState.TryTakeFromJson<byte[]>("MyState", out var existing)); Assert.Equal(new byte[] { 1, 2, 3, 4 }, existing); } [Fact] public void InitializeExistingState_ThrowsIfAlreadyInitialized() { // Arrange var applicationState = new PersistentComponentState(new Dictionary<string, byte[]>(), [], []); var existingState = new Dictionary<string, byte[]> { ["MyState"] = new byte[] { 1, 2, 3, 4 } }; applicationState.InitializeExistingState(existingState, RestoreContext.InitialValue); // Act & Assert Assert.Throws<InvalidOperationException>(() => applicationState.InitializeExistingState(existingState, null)); } [Fact] public void RegisterOnPersisting_ThrowsIfCalledDuringOnPersisting() { // Arrange var currentState = new Dictionary<string, byte[]>(); var applicationState = new PersistentComponentState(currentState, [], []) { PersistingState = true }; // Act & Assert Assert.Throws<InvalidOperationException>(() => applicationState.RegisterOnPersisting(() => Task.CompletedTask)); } [Fact] public void TryRetrieveState_ReturnsStateWhenItExists() { // Arrange var applicationState = new PersistentComponentState(new Dictionary<string, byte[]>(), [], []); var existingState = new Dictionary<string, byte[]> { ["MyState"] = JsonSerializer.SerializeToUtf8Bytes(new byte[] { 1, 2, 3, 4 }) }; // Act applicationState.InitializeExistingState(existingState, RestoreContext.InitialValue); // Assert Assert.True(applicationState.TryTakeFromJson<byte[]>("MyState", out var existing)); Assert.Equal(new byte[] { 1, 2, 3, 4 }, existing); Assert.False(applicationState.TryTakeFromJson<byte[]>("MyState", out var gone)); } [Fact] public void PersistState_SavesDataToTheStoreAsync() { // Arrange var currentState = new Dictionary<string, byte[]>(); var applicationState = new PersistentComponentState(currentState, [], []) { PersistingState = true }; var myState = new byte[] { 1, 2, 3, 4 }; // Act applicationState.PersistAsJson("MyState", myState); // Assert Assert.True(currentState.TryGetValue("MyState", out var stored)); Assert.Equal(myState, JsonSerializer.Deserialize<byte[]>(stored)); } [Fact] public void PersistState_ThrowsForDuplicateKeys() { // Arrange var currentState = new Dictionary<string, byte[]>(); var applicationState = new PersistentComponentState(currentState, [], []) { PersistingState = true }; var myState = new byte[] { 1, 2, 3, 4 }; applicationState.PersistAsJson("MyState", myState); // Act & Assert Assert.Throws<ArgumentException>(() => applicationState.PersistAsJson("MyState", myState)); } [Fact] public void PersistAsJson_SerializesTheDataToJsonAsync() { // Arrange var currentState = new Dictionary<string, byte[]>(); var applicationState = new PersistentComponentState(currentState, [], []) { PersistingState = true }; var myState = new byte[] { 1, 2, 3, 4 }; // Act applicationState.PersistAsJson("MyState", myState); // Assert Assert.True(currentState.TryGetValue("MyState", out var stored)); Assert.Equal(myState, JsonSerializer.Deserialize<byte[]>(stored)); } [Fact] public void PersistAsJson_NullValueAsync() { // Arrange var currentState = new Dictionary<string, byte[]>(); var applicationState = new PersistentComponentState(currentState, [], []) { PersistingState = true }; // Act applicationState.PersistAsJson<byte[]>("MyState", null); // Assert Assert.True(currentState.TryGetValue("MyState", out var stored)); Assert.Null(JsonSerializer.Deserialize<byte[]>(stored)); } [Fact] public void TryRetrieveFromJson_DeserializesTheDataFromJson() { // Arrange var myState = new byte[] { 1, 2, 3, 4 }; var serialized = JsonSerializer.SerializeToUtf8Bytes(myState); var existingState = new Dictionary<string, byte[]>() { ["MyState"] = serialized }; var applicationState = new PersistentComponentState(new Dictionary<string, byte[]>(), [], []); applicationState.InitializeExistingState(existingState, RestoreContext.InitialValue); // Act Assert.True(applicationState.TryTakeFromJson<byte[]>("MyState", out var stored)); // Assert Assert.Equal(myState, stored); Assert.False(applicationState.TryTakeFromJson<byte[]>("MyState", out _)); } [Fact] public void TryRetrieveFromJson_NullValue() { // Arrange var serialized = JsonSerializer.SerializeToUtf8Bytes<byte[]>(null); var existingState = new Dictionary<string, byte[]>() { ["MyState"] = serialized }; var applicationState = new PersistentComponentState(new Dictionary<string, byte[]>(), [], []); applicationState.InitializeExistingState(existingState, RestoreContext.InitialValue); // Act Assert.True(applicationState.TryTakeFromJson<byte[]>("MyState", out var stored)); // Assert Assert.Null(stored); Assert.False(applicationState.TryTakeFromJson<byte[]>("MyState", out _)); } [Fact] public void RegisterOnRestoring_InvokesCallbackWhenShouldRestoreMatches() { // Arrange var currentState = new Dictionary<string, byte[]>(); var callbacks = new List<RestoreComponentStateRegistration>(); var applicationState = new PersistentComponentState(currentState, [], callbacks); applicationState.InitializeExistingState(new Dictionary<string, byte[]>(), RestoreContext.InitialValue); var callbackInvoked = false; var options = new RestoreOptions { RestoreBehavior = RestoreBehavior.Default, AllowUpdates = false }; // Act var subscription = applicationState.RegisterOnRestoring(() => { callbackInvoked = true; }, options); // Assert Assert.True(callbackInvoked); } [Fact] public void RegisterOnRestoring_DoesNotInvokeCallbackWhenShouldRestoreDoesNotMatch() { // Arrange var currentState = new Dictionary<string, byte[]>(); var callbacks = new List<RestoreComponentStateRegistration>(); var applicationState = new PersistentComponentState(currentState, [], callbacks); applicationState.InitializeExistingState(new Dictionary<string, byte[]>(), RestoreContext.InitialValue); var callbackInvoked = false; var options = new RestoreOptions { RestoreBehavior = RestoreBehavior.SkipInitialValue, AllowUpdates = false }; // Act var subscription = applicationState.RegisterOnRestoring(() => { callbackInvoked = true; }, options); // Assert Assert.False(callbackInvoked); } [Fact] public void RegisterOnRestoring_ReturnsDefaultSubscriptionWhenNotAllowingUpdates() { // Arrange var currentState = new Dictionary<string, byte[]>(); var callbacks = new List<RestoreComponentStateRegistration>(); var applicationState = new PersistentComponentState(currentState, [], callbacks); applicationState.InitializeExistingState(new Dictionary<string, byte[]>(), RestoreContext.InitialValue); var options = new RestoreOptions { RestoreBehavior = RestoreBehavior.Default, AllowUpdates = false }; // Act var subscription = applicationState.RegisterOnRestoring(() => { }, options); // Assert Assert.Equal(default, subscription); Assert.Empty(callbacks); } [Fact] public void RegisterOnRestoring_ReturnsRestoringSubscriptionWhenAllowsUpdates() { // Arrange var currentState = new Dictionary<string, byte[]>(); var callbacks = new List<RestoreComponentStateRegistration>(); var applicationState = new PersistentComponentState(currentState, [], callbacks); applicationState.InitializeExistingState(new Dictionary<string, byte[]>(), RestoreContext.InitialValue); var options = new RestoreOptions { RestoreBehavior = RestoreBehavior.Default, AllowUpdates = true }; // Act var subscription = applicationState.RegisterOnRestoring(() => { }, options); // Assert Assert.NotEqual(default, subscription); Assert.Single(callbacks); } [Fact] public void RegisterOnRestoring_SubscriptionCanBeDisposed() { // Arrange var currentState = new Dictionary<string, byte[]>(); var callbacks = new List<RestoreComponentStateRegistration>(); var applicationState = new PersistentComponentState(currentState, [], callbacks); applicationState.InitializeExistingState(new Dictionary<string, byte[]>(), RestoreContext.InitialValue); var options = new RestoreOptions { RestoreBehavior = RestoreBehavior.Default, AllowUpdates = true }; var subscription = applicationState.RegisterOnRestoring(() => { }, options); Assert.Single(callbacks); // Act subscription.Dispose(); // Assert Assert.Empty(callbacks); } }
PersistentComponentStateTest
csharp
dotnet__aspnetcore
src/Servers/Kestrel/Core/test/Http2/Http2FrameWriterTests.cs
{ "start": 3308, "end": 3805 }
public static class ____ { public static async Task<byte[]> ReadForLengthAsync(this PipeReader pipeReader, int length) { while (true) { var result = await pipeReader.ReadAsync(); var buffer = result.Buffer; if (!buffer.IsEmpty && buffer.Length >= length) { return buffer.Slice(0, length).ToArray(); } pipeReader.AdvanceTo(buffer.Start, buffer.End); } } }
PipeReaderExtensions
csharp
reactiveui__ReactiveUI
src/ReactiveUI/Bindings/ISetMethodBindingConverter.cs
{ "start": 587, "end": 1932 }
class ____ /// PerformSet for this particular Type. If the method isn't supported at /// all, return a non-positive integer. When multiple implementations /// return a positive value, the host will use the one which returns /// the highest value. When in doubt, return '2' or '0'. /// </summary> /// <param name="fromType">The from type to convert from.</param> /// <param name="toType">The target type to convert to.</param> /// <returns>A positive integer if PerformSet is supported, /// zero or a negative value otherwise.</returns> #if NET6_0_OR_GREATER [RequiresDynamicCode("GetAffinityForObjects uses methods that require dynamic code generation")] [RequiresUnreferencedCode("GetAffinityForObjects uses methods that may require unreferenced code")] #endif int GetAffinityForObjects(Type? fromType, Type? toType); /// <summary> /// Convert a given object to the specified type. /// </summary> /// <param name="toTarget">The target object we are setting to.</param> /// <param name="newValue">The value to set on the new object.</param> /// <param name="arguments">The arguments required. Used for indexer based values.</param> /// <returns>The value that was set.</returns> object? PerformSet(object? toTarget, object? newValue, object?[]? arguments); }
supports
csharp
jellyfin__jellyfin
MediaBrowser.Model/Dto/MetadataEditorInfo.cs
{ "start": 227, "end": 291 }
class ____ metadata editor information. /// </summary>
representing
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/AreaAttribute.cs
{ "start": 411, "end": 793 }
public class ____ : RouteValueAttribute { /// <summary> /// Initializes a new <see cref="AreaAttribute"/> instance. /// </summary> /// <param name="areaName">The area containing the controller or action.</param> public AreaAttribute(string areaName) : base("area", areaName) { ArgumentException.ThrowIfNullOrEmpty(areaName); } }
AreaAttribute
csharp
xunit__xunit
src/xunit.v3.assert.tests/Asserts/AsyncCollectionAssertsTests.cs
{ "start": 24848, "end": 26449 }
public sealed class ____(int value) : IEnumerable<string> { public int Value { get; } = value; public IEnumerator<string> GetEnumerator() => Enumerable.Repeat("", Value).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } [Fact] public void WithThrow_PrintsPointerWhereThrowOccurs_RecordsInnerException() { static void validateError( Action action, string expectedType, string actualType) { var ex = Record.Exception(action); var padding = Math.Max(expectedType.Length, actualType.Length); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Exception thrown during comparison" + Environment.NewLine + " " + new string(' ', padding) + " ↓ (pos 0)" + Environment.NewLine + "Expected: " + expectedType.PadRight(padding) + "[1, 2]" + Environment.NewLine + "Actual: " + actualType.PadRight(padding) + "[1, 3]" + Environment.NewLine + " " + new string(' ', padding) + " ↑ (pos 0)", ex.Message ); Assert.IsType<DivideByZeroException>(ex.InnerException); } #pragma warning disable IDE0300 // Simplify collection initialization validateError(() => Assert.Equal(new[] { 1, 2 }, new[] { 1, 3 }.ToAsyncEnumerable(), new ThrowingComparer()), "int[] ", "<generated> "); #pragma warning restore IDE0300 // Simplify collection initialization validateError(() => Assert.Equal(new[] { 1, 2 }.ToAsyncEnumerable(), new[] { 1, 3 }.ToAsyncEnumerable(), new ThrowingComparer()), "", ""); }
EnumerableItem
csharp
louthy__language-ext
LanguageExt.Tests/Divisible.cs
{ "start": 114, "end": 327 }
public class ____ { [Fact] public void OptionalNumericDivide() { var x = Some(20); var y = Some(10); var z = divide<TInt, int>(x, y); Assert.True(z == 2); } }
Divisible
csharp
microsoft__garnet
libs/server/Objects/SortedSetGeo/GeoSearchOptions.cs
{ "start": 263, "end": 719 }
public enum ____ : byte { /// <summary> /// Meters /// </summary> M = 0, /// <summary> /// Kilometers /// </summary> KM, /// <summary> /// Miles /// </summary> MI, /// <summary> /// Foot /// </summary> FT } /// <summary> /// The direction in which to sequence elements. /// </summary>
GeoDistanceUnitType
csharp
JoshClose__CsvHelper
src/CsvHelper/Configuration/Attributes/DetectColumnCountChangesAttribute.cs
{ "start": 681, "end": 1583 }
public class ____ : Attribute, IClassMapper { /// <summary> /// A value indicating whether changes in the column /// count should be detected. If <see langword="true"/>, a <see cref="BadDataException"/> /// will be thrown if a different column count is detected. /// </summary> public bool DetectColumnCountChanges { get; private set; } /// <summary> /// A value indicating whether changes in the column /// count should be detected. If <see langword="true"/>, a <see cref="BadDataException"/> /// will be thrown if a different column count is detected. /// </summary> public DetectColumnCountChangesAttribute(bool detectColumnCountChanges = true) { DetectColumnCountChanges = detectColumnCountChanges; } /// <inheritdoc /> public void ApplyTo(CsvConfiguration configuration) { configuration.DetectColumnCountChanges = DetectColumnCountChanges; } }
DetectColumnCountChangesAttribute
csharp
grandnode__grandnode2
src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs
{ "start": 363, "end": 4249 }
public class ____ : IShippingMethodService { #region Ctor /// <summary> /// Ctor /// </summary> public ShippingMethodService( IRepository<ShippingMethod> shippingMethodRepository, IMediator mediator, ICacheBase cacheBase) { _shippingMethodRepository = shippingMethodRepository; _mediator = mediator; _cacheBase = cacheBase; } #endregion #region Fields private readonly IRepository<ShippingMethod> _shippingMethodRepository; private readonly IMediator _mediator; private readonly ICacheBase _cacheBase; #endregion #region Shipping methods /// <summary> /// Deletes a shipping method /// </summary> /// <param name="shippingMethod">The shipping method</param> public virtual async Task DeleteShippingMethod(ShippingMethod shippingMethod) { ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.DeleteAsync(shippingMethod); //clear cache await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY); //event notification await _mediator.EntityDeleted(shippingMethod); } /// <summary> /// Gets a shipping method /// </summary> /// <param name="shippingMethodId">The shipping method identifier</param> /// <returns>Shipping method</returns> public virtual Task<ShippingMethod> GetShippingMethodById(string shippingMethodId) { var key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId); return _cacheBase.GetAsync(key, () => _shippingMethodRepository.GetByIdAsync(shippingMethodId)); } /// <summary> /// Gets all shipping methods /// </summary> /// <param name="filterByCountryId">The country ident to filter by</param> /// <param name="customer"></param> /// <returns>Shipping methods</returns> public virtual async Task<IList<ShippingMethod>> GetAllShippingMethods(string filterByCountryId = "", Customer customer = null) { var shippingMethods = await _cacheBase.GetAsync(CacheKey.SHIPPINGMETHOD_ALL, async () => { var query = from sm in _shippingMethodRepository.Table orderby sm.DisplayOrder select sm; return await Task.FromResult(query.ToList()); }); if (!string.IsNullOrEmpty(filterByCountryId)) shippingMethods = shippingMethods.Where(x => !x.CountryRestrictionExists(filterByCountryId)).ToList(); if (customer != null) shippingMethods = shippingMethods .Where(x => !x.CustomerGroupRestrictionExists(customer.Groups)).ToList(); return shippingMethods; } /// <summary> /// Inserts a shipping method /// </summary> /// <param name="shippingMethod">Shipping method</param> public virtual async Task InsertShippingMethod(ShippingMethod shippingMethod) { ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.InsertAsync(shippingMethod); //clear cache await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY); //event notification await _mediator.EntityInserted(shippingMethod); } /// <summary> /// Updates the shipping method /// </summary> /// <param name="shippingMethod">Shipping method</param> public virtual async Task UpdateShippingMethod(ShippingMethod shippingMethod) { ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.UpdateAsync(shippingMethod); //clear cache await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY); //event notification await _mediator.EntityUpdated(shippingMethod); } #endregion }
ShippingMethodService
csharp
dotnet__orleans
src/Orleans.Serialization/ISerializableSerializer/DotNetSerializableCodec.cs
{ "start": 558, "end": 9758 }
public class ____ : IGeneralizedCodec { public static readonly Type CodecType = typeof(DotNetSerializableCodec); private static readonly Type SerializableType = typeof(ISerializable); private readonly SerializationCallbacksFactory _serializationCallbacks; private readonly Func<Type, Action<object, SerializationInfo, StreamingContext>> _createConstructorDelegate; private readonly ConcurrentDictionary<Type, Action<object, SerializationInfo, StreamingContext>> _constructors = new(); #pragma warning disable SYSLIB0050 // Type or member is obsolete private readonly IFormatterConverter _formatterConverter; #pragma warning restore SYSLIB0050 // Type or member is obsolete private readonly StreamingContext _streamingContext; private readonly SerializationEntryCodec _entrySerializer; private readonly TypeConverter _typeConverter; private readonly ValueTypeSerializerFactory _valueTypeSerializerFactory; /// <summary> /// Initializes a new instance of the <see cref="DotNetSerializableCodec"/> class. /// </summary> /// <param name="typeResolver">The type resolver.</param> public DotNetSerializableCodec(TypeConverter typeResolver) { #pragma warning disable SYSLIB0050 // Type or member is obsolete _streamingContext = new StreamingContext(StreamingContextStates.All); #pragma warning restore SYSLIB0050 // Type or member is obsolete _typeConverter = typeResolver; _entrySerializer = new SerializationEntryCodec(); _serializationCallbacks = new SerializationCallbacksFactory(); #pragma warning disable SYSLIB0050 // Type or member is obsolete _formatterConverter = new FormatterConverter(); #pragma warning restore SYSLIB0050 // Type or member is obsolete var constructorFactory = new SerializationConstructorFactory(); _createConstructorDelegate = constructorFactory.GetSerializationConstructorDelegate; _valueTypeSerializerFactory = new ValueTypeSerializerFactory( _entrySerializer, constructorFactory, _serializationCallbacks, _formatterConverter, _streamingContext); } /// <inheritdoc /> [SecurityCritical] public void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, object value) where TBufferWriter : IBufferWriter<byte> { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } var type = value.GetType(); writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecType, WireType.TagDelimited); if (type.IsValueType) { var serializer = _valueTypeSerializerFactory.GetSerializer(type); serializer.WriteValue(ref writer, value); } else { WriteObject(ref writer, type, value); } writer.WriteEndObject(); } /// <inheritdoc /> [SecurityCritical] public object ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.IsReference) { return ReferenceCodec.ReadReference(ref reader, field.FieldType); } field.EnsureWireTypeTagDelimited(); var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); Type type; var header = reader.ReadFieldHeader(); if (header.FieldIdDelta == 1) { // This is an exception type, so deserialize it as an exception. var typeName = StringCodec.ReadValue(ref reader, header); if (!_typeConverter.TryParse(typeName, out type)) { return ReadFallbackException(ref reader, typeName, placeholderReferenceId); } } else { type = TypeSerializerCodec.ReadValue(ref reader, header); if (type.IsValueType) { var serializer = _valueTypeSerializerFactory.GetSerializer(type); return serializer.ReadValue(ref reader, type); } } return ReadObject(ref reader, type, placeholderReferenceId); } private object ReadFallbackException<TInput>(ref Reader<TInput> reader, string typeName, uint placeholderReferenceId) { // Deserialize into a fallback type for unknown exceptions. This means that missing fields will not be represented. var result = (UnavailableExceptionFallbackException)ReadObject(ref reader, typeof(UnavailableExceptionFallbackException), placeholderReferenceId); result.ExceptionType = typeName; return result; } private object ReadObject<TInput>(ref Reader<TInput> reader, Type type, uint placeholderReferenceId) { var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type); #pragma warning disable SYSLIB0050 // Type or member is obsolete var info = new SerializationInfo(type, _formatterConverter); #pragma warning restore SYSLIB0050 // Type or member is obsolete var result = RuntimeHelpers.GetUninitializedObject(type); ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); callbacks.OnDeserializing?.Invoke(result, _streamingContext); uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; if (fieldId == 1) { var entry = _entrySerializer.ReadValue(ref reader, header); if (entry.ObjectType is { } entryType) { info.AddValue(entry.Name, entry.Value, entryType); } else { info.AddValue(entry.Name, entry.Value); } } else { reader.ConsumeUnknownField(header); } } var constructor = _constructors.GetOrAdd(info.ObjectType, _createConstructorDelegate); constructor(result, info, _streamingContext); callbacks.OnDeserialized?.Invoke(result, _streamingContext); if (result is IDeserializationCallback callback) { callback.OnDeserialization(_streamingContext.Context); } return result; } private void WriteObject<TBufferWriter>(ref Writer<TBufferWriter> writer, Type type, object value) where TBufferWriter : IBufferWriter<byte> { var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type); #pragma warning disable SYSLIB0050 // Type or member is obsolete var info = new SerializationInfo(type, _formatterConverter); #pragma warning restore SYSLIB0050 // Type or member is obsolete // Serialize the type name according to the value populated in the SerializationInfo. if (value is Exception) { // For exceptions, the type is serialized as a string to facilitate safe deserialization. var typeName = _typeConverter.Format(info.ObjectType); StringCodec.WriteField(ref writer, 1, typeName); } else { TypeSerializerCodec.WriteField(ref writer, 0, info.ObjectType); } callbacks.OnSerializing?.Invoke(value, _streamingContext); #pragma warning disable SYSLIB0050 // Type or member is obsolete ((ISerializable)value).GetObjectData(info, _streamingContext); #pragma warning restore SYSLIB0050 // Type or member is obsolete var first = true; foreach (var field in info) { var surrogate = new SerializationEntrySurrogate { Name = field.Name, Value = field.Value, ObjectType = field.ObjectType }; _entrySerializer.WriteField(ref writer, first ? 1 : (uint)0, typeof(SerializationEntrySurrogate), surrogate); if (first) { first = false; } } callbacks.OnSerialized?.Invoke(value, _streamingContext); } /// <inheritdoc /> [SecurityCritical] public bool IsSupportedType(Type type) => type == CodecType || typeof(Exception).IsAssignableFrom(type) || SerializableType.IsAssignableFrom(type) && SerializationConstructorFactory.HasSerializationConstructor(type); } }
DotNetSerializableCodec
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 2701887, "end": 2705115 }
public partial class ____ : global::System.IEquatable<OnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4>, IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4 { public OnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity severity, global::System.String? old, global::System.String? @new) { this.__typename = __typename; Severity = severity; Old = old; New = @new; } /// <summary> /// The name of the current Object type at runtime. /// </summary> public global::System.String __typename { get; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity Severity { get; } public global::System.String? Old { get; } public global::System.String? New { get; } public virtual global::System.Boolean Equals(OnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (__typename.Equals(other.__typename)) && Severity.Equals(other.Severity) && ((Old is null && other.Old is null) || Old != null && Old.Equals(other.Old)) && ((New is null && other.New is null) || New != null && New.Equals(other.New)); } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((OnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; hash ^= 397 * __typename.GetHashCode(); hash ^= 397 * Severity.GetHashCode(); if (Old != null) { hash ^= 397 * Old.GetHashCode(); } if (New != null) { hash ^= 397 * New.GetHashCode(); } return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
OnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DescriptionChanged_4
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Runtime/Caching/ICacheManager.cs
{ "start": 320, "end": 392 }
public interface ____ : ICacheManager<ICache> { }
ICacheManager
csharp
louthy__language-ext
LanguageExt.Core/Effects/IO/Prelude/IO.Prelude.cs
{ "start": 293, "end": 26352 }
partial class ____ { /// <summary> /// Access the cancellation-token from the IO environment /// </summary> /// <returns>CancellationToken</returns> public static readonly IO<CancellationToken> cancelToken = IO.lift(e => e.Token); /// <summary> /// Request a cancellation of the IO expression /// </summary> public static readonly IO<Unit> cancel = IO.lift<Unit>( e => { e.Source.Cancel(); throw new TaskCanceledException(); }); /// <summary> /// Always yields a `Unit` value /// </summary> public static readonly IO<Unit> unitIO = IO.pure<Unit>(default); /// <summary> /// Yields the IO environment /// </summary> public static readonly IO<EnvIO> envIO = IO.lift<EnvIO>(e => e); /// <summary> /// Tail call /// </summary> /// <param name="tailIO"></param> /// <typeparam name="A"></typeparam> /// <returns></returns> public static IO<A> tail<A>(IO<A> tailIO) => new IOTail<A>(tailIO); /// <summary> /// Tail call /// </summary> /// <param name="ma"></param> /// <typeparam name="A"></typeparam> /// <returns></returns> public static K<M, A> tailIO<M, A>(K<M, A> ma) where M : MonadUnliftIO<M> => ma.MapIO(tail); /// <summary> /// Make this IO computation run on the `SynchronizationContext` that was captured at the start /// of the IO chain (i.e. the one embedded within the `EnvIO` environment that is passed through /// all IO computations) /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static K<M, A> postIO<M, A>(K<M, A> ma) where M : MonadUnliftIO<M> => M.PostIO(ma); /// <summary> /// Queue this IO operation to run on the thread-pool. /// </summary> /// <param name="timeout">Maximum time that the forked IO operation can run for. `None` for no timeout.</param> /// <returns>Returns a `ForkIO` data-structure that contains two IO effects that can be used to either cancel /// the forked IO operation or to await the result of it. /// </returns> [Pure] [MethodImpl(Opt.Default)] public static K<M, ForkIO<A>> fork<M, A>(K<M, A> ma, Option<TimeSpan> timeout = default) where M : MonadUnliftIO<M>, Monad<M> => M.ForkIOMaybe(ma, timeout); /// <summary> /// Queue this IO operation to run on the thread-pool. /// </summary> /// <param name="timeout">Maximum time that the forked IO operation can run for. `None` for no timeout.</param> /// <returns>Returns a `ForkIO` data-structure that contains two IO effects that can be used to either cancel /// the forked IO operation or to await the result of it. /// </returns> [Pure] [MethodImpl(Opt.Default)] public static K<M, A> awaitIO<M, A>(K<M, ForkIO<A>> ma) where M : MonadUnliftIO<M> => M.Await(ma); /// <summary> /// Yield the thread for the specified duration or until cancelled. /// </summary> /// <param name="duration">Amount of time to yield for</param> /// <returns>Unit</returns> [Pure] [MethodImpl(Opt.Default)] public static IO<Unit> yieldFor(Duration duration) => IO.yieldFor(duration); /// <summary> /// Yield the thread for the specified duration or until cancelled. /// </summary> /// <param name="timeSpan">Amount of time to yield for</param> /// <returns>Unit</returns> [Pure] [MethodImpl(Opt.Default)] public static IO<Unit> yieldFor(TimeSpan timeSpan) => IO.yieldFor(timeSpan); /// <summary> /// Awaits all operations /// </summary> /// <param name="ms">Operations to await</param> /// <returns>Sequence of results</returns> public static K<M, Seq<A>> awaitAll<M, A>(params K<M, A>[] ms) where M : MonadUnliftIO<M> => awaitAll(ms.ToSeqUnsafe()); /// <summary> /// Awaits all forks /// </summary> /// <param name="forks">Forks to await</param> /// <returns>Sequence of results</returns> public static K<M, Seq<A>> awaitAll<M, A>(params K<M, ForkIO<A>>[] forks) where M : MonadUnliftIO<M> => awaitAll(forks.ToSeqUnsafe()); /// <summary> /// Awaits all /// </summary> /// <param name="forks">IO operations to await</param> /// <returns>Sequence of results</returns> public static IO<Seq<A>> awaitAll<A>(params ForkIO<A>[] forks) => awaitAll(forks.ToSeqUnsafe()); /// <summary> /// Awaits all operations /// </summary> /// <param name="ms">Operations to await</param> /// <returns>Sequence of results</returns> public static K<M, Seq<A>> awaitAll<M, A>(Seq<K<M, A>> ms) where M : MonadUnliftIO<M> => ms.Traverse(f => f.ToIO()) .Bind(awaitAll); /// <summary> /// Awaits all operations /// </summary> /// <param name="ms">Operations to await</param> /// <returns>Sequence of results</returns> public static IO<Seq<A>> awaitAll<A>(Seq<IO<A>> ms) => IO.liftAsync(async eio => { var result = await Task.WhenAll(ms.Map(io => io.RunAsync(eio).AsTask())); return result.ToSeqUnsafe(); }); /// <summary> /// Awaits all forks /// </summary> /// <param name="forks">Forks to await</param> /// <returns>Sequence of results</returns> public static K<M, Seq<A>> awaitAll<M, A>(Seq<K<M, ForkIO<A>>> forks) where M : MonadUnliftIO<M> => forks.TraverseM(f => f.Await()); /// <summary> /// Awaits all /// </summary> /// <param name="forks">IO operations to await</param> /// <returns>Sequence of results</returns> public static IO<Seq<A>> awaitAll<A>(Seq<IO<ForkIO<A>>> forks) => IO.liftAsync(async eio => { var forks1 = forks.Map(mf => mf.Run(eio)); var result = await Task.WhenAll(forks1.Map(f => f.Await.RunAsync(eio).AsTask())); return result.ToSeqUnsafe(); }); /// <summary> /// Awaits all /// </summary> /// <param name="forks">IO operations to await</param> /// <returns>Sequence of results</returns> public static IO<Seq<A>> awaitAll<A>(Seq<ForkIO<A>> forks) => IO.liftAsync(async eio => { var result = await Task.WhenAll(forks.Map(f => f.Await.RunAsync(eio).AsTask())); return result.ToSeqUnsafe(); }); /// <summary> /// Awaits for any operation to complete /// </summary> /// <param name="ms">Operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static K<M, A> awaitAny<M, A>(params K<M, A>[] ms) where M : MonadUnliftIO<M> => awaitAny(ms.ToSeqUnsafe()); /// <summary> /// Awaits for any IO to complete /// </summary> /// <param name="ms">IO operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(params IO<A>[] ms) => awaitAny(ms.ToSeqUnsafe()); /// <summary> /// Awaits for any IO to complete /// </summary> /// <param name="ms">IO operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(params K<IO, A>[] ms) => awaitAny(ms.ToSeqUnsafe()); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static K<M, A> awaitAny<M, A>(params K<M, ForkIO<A>>[] forks) where M : MonadUnliftIO<M> => awaitAny(forks.ToSeqUnsafe()); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(params IO<ForkIO<A>>[] forks) => awaitAny(forks.ToSeqUnsafe()); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(params ForkIO<A>[] forks) => awaitAny(forks.ToSeqUnsafe()); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static K<M, A> awaitAny<M, A>(Seq<K<M, ForkIO<A>>> forks) where M : MonadUnliftIO<M> => forks.Traverse(f => f.ToIO()) .Bind(awaitAny); /// <summary> /// Awaits for operations to complete /// </summary> /// <param name="ms">Operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static K<M, A> awaitAny<M, A>(Seq<K<M, A>> forks) where M : MonadUnliftIO<M> => forks.Traverse(f => f.ToIO()) .Bind(awaitAny); /// <summary> /// Awaits for any IO to complete /// </summary> /// <param name="ms">IO operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(Seq<K<IO, A>> ms) => awaitAny(ms.Map(m => m.As())); /// <summary> /// Awaits for any IO to complete /// </summary> /// <param name="ms">IO operations to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(Seq<IO<A>> ms) => IO.liftAsync(async eio => await await Task.WhenAny(ms.Map(io => io.RunAsync(eio).AsTask()))); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(Seq<ForkIO<A>> forks) => IO.liftAsync(async eio => await await Task.WhenAny(forks.Map(f => f.Await.RunAsync(eio).AsTask()))); /// <summary> /// Awaits for any forks to complete /// </summary> /// <param name="forks">Forks to await</param> /// <returns> /// If we get one success, then we'll return straight away and cancel the others. /// If we get any errors, we'll collect them in the hope that at least one works. /// If we have collected as many errors as we have forks, then we'll return them all. /// </returns> public static IO<A> awaitAny<A>(Seq<IO<ForkIO<A>>> forks) => IO.liftAsync(async eio => { var forks1 = forks.Map(mf => mf.Run(eio)); var result = await await Task.WhenAny(forks1.Map(f => f.Await.RunAsync(eio).AsTask())); return result; }); /// <summary> /// Timeout operation if it takes too long /// </summary> [Pure] [MethodImpl(Opt.Default)] public static K<M, A> timeout<M, A>(TimeSpan timeout, K<M, A> ma) where M : MonadUnliftIO<M> => ma.TimeoutIO(timeout); /// <summary> /// Timeout operation if it takes too long /// </summary> [Pure] [MethodImpl(Opt.Default)] public static IO<A> timeout<A>(TimeSpan timeout, K<IO, A> ma) => ma.As().Timeout(timeout); /// <summary> /// Keeps repeating the computation /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeat<M, A>(K<M, A> ma) where M : MonadUnliftIO<M> => ma.RepeatIO(); /// <summary> /// Keeps repeating the computation /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeat<A>(IO<A> ma) => ma.Repeat(); /// <summary> /// Keeps repeating the computation, until the scheduler expires /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeat<M, A>(Schedule schedule, K<M, A> ma) where M : MonadUnliftIO<M> => ma.RepeatIO(schedule); /// <summary> /// Keeps repeating the computation until the scheduler expires /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeat<A>(Schedule schedule, K<IO, A> ma) => ma.As().Repeat(schedule); /// <summary> /// Keeps repeating the computation until the predicate returns false /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeatWhile<M, A>(K<M, A> ma, Func<A, bool> predicate) where M : MonadUnliftIO<M> => ma.RepeatWhileIO(predicate); /// <summary> /// Keeps repeating the computation until the predicate returns false /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeatWhile<A>(IO<A> ma, Func<A, bool> predicate) => ma.As().RepeatWhile(predicate); /// <summary> /// Keeps repeating the computation until the scheduler expires, or the predicate returns false /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeatWhile<M, A>( Schedule schedule, K<M, A> ma, Func<A, bool> predicate) where M : MonadUnliftIO<M> => ma.RepeatWhileIO(schedule, predicate); /// <summary> /// Keeps repeating the computation until the scheduler expires, or the predicate returns false /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeatWhile<A>( Schedule schedule, K<IO, A> ma, Func<A, bool> predicate) => ma.As().RepeatWhile(schedule, predicate); /// <summary> /// Keeps repeating the computation until the predicate returns true /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeatUntil<M, A>( K<M, A> ma, Func<A, bool> predicate) where M : MonadUnliftIO<M> => ma.RepeatUntilIO(predicate); /// <summary> /// Keeps repeating the computation until the predicate returns true /// </summary> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeatUntil<A>( K<IO, A> ma, Func<A, bool> predicate) => ma.As().RepeatUntil(predicate); /// <summary> /// Keeps repeating the computation until the scheduler expires, or the predicate returns true /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static K<M, A> repeatUntil<M, A>( Schedule schedule, K<M, A> ma, Func<A, bool> predicate) where M : MonadUnliftIO<M> => ma.RepeatUntilIO(schedule, predicate); /// <summary> /// Keeps repeating the computation until the scheduler expires, or the predicate returns true /// </summary> /// <param name="schedule">Scheduler strategy for repeating</param> /// <param name="ma">Computation to repeat</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of `ma`</returns> public static IO<A> repeatUntil<A>( Schedule schedule, K<IO, A> ma, Func<A, bool> predicate) => ma.As().RepeatUntil(schedule, predicate); /// <summary> /// Keeps retrying the computation /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retry<M, A>(K<M, A> ma) where M : MonadUnliftIO<M> => ma.RetryIO(); /// <summary> /// Keeps retrying the computation /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retry<A>(K<IO, A> ma) => ma.As().Retry(); /// <summary> /// Keeps retrying the computation until the scheduler expires /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retry<M, A>(Schedule schedule, K<M, A> ma) where M : MonadUnliftIO<M> => ma.RetryIO(schedule); /// <summary> /// Keeps retrying the computation until the scheduler expires /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retry<A>(Schedule schedule, K<IO, A> ma) => ma.As().Retry(schedule); /// <summary> /// Keeps retrying the computation until the predicate returns false /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retryWhile<M, A>( K<M, A> ma, Func<Error, bool> predicate) where M : MonadUnliftIO<M> => ma.RetryWhileIO(predicate); /// <summary> /// Keeps retrying the computation until the predicate returns false /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retryWhile<A>( K<IO, A> ma, Func<Error, bool> predicate) => ma.As().RetryWhile(predicate); /// <summary> /// Keeps retrying the computation until the scheduler expires, or the predicate returns false /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retryWhile<M, A>( Schedule schedule, K<M, A> ma, Func<Error, bool> predicate) where M : MonadUnliftIO<M> => ma.RetryWhileIO(schedule, predicate); /// <summary> /// Keeps retrying the computation until the scheduler expires, or the predicate returns false /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retryWhile<A>( Schedule schedule, K<IO, A> ma, Func<Error, bool> predicate) => ma.As().RetryWhile(schedule, predicate); /// <summary> /// Keeps retrying the computation until the predicate returns true /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retryUntil<M, A>( K<M, A> ma, Func<Error, bool> predicate) where M : MonadUnliftIO<M> => ma.RetryUntilIO(predicate); /// <summary> /// Keeps retrying the computation until the predicate returns true /// </summary> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retryUntil<A>( K<IO, A> ma, Func<Error, bool> predicate) => ma.As().RetryUntil(predicate); /// <summary> /// Keeps retrying the computation until the scheduler expires, or the predicate returns true /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static K<M, A> retryUntil<M, A>( Schedule schedule, K<M, A> ma, Func<Error, bool> predicate) where M : MonadUnliftIO<M> => ma.RetryUntilIO(schedule, predicate); /// <summary> /// Keeps retrying the computation until the scheduler expires, or the predicate returns true /// </summary> /// <param name="schedule">Scheduler strategy for retrying</param> /// <param name="ma">Computation to retry</param> /// <typeparam name="A">Computation bound value type</typeparam> /// <returns>The result of the last invocation of ma</returns> public static IO<A> retryUntil<A>( Schedule schedule, K<IO, A> ma, Func<Error, bool> predicate) => ma.As().RetryUntil(schedule, predicate); }
Prelude
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/Amb.cs
{ "start": 825, "end": 2396 }
internal sealed class ____ : IDisposable { private readonly AmbObserver _leftObserver; private readonly AmbObserver _rightObserver; private int _winner; public AmbCoordinator(IObserver<TSource> observer) { _leftObserver = new AmbObserver(observer, this, true); _rightObserver = new AmbObserver(observer, this, false); } public void Run(IObservable<TSource> left, IObservable<TSource> right) { _leftObserver.Run(left); _rightObserver.Run(right); } public void Dispose() { _leftObserver.Dispose(); _rightObserver.Dispose(); } /// <summary> /// Try winning the race for the right of emission. /// </summary> /// <param name="isLeft">If true, the contender is the left source.</param> /// <returns>True if the contender has won the race.</returns> public bool TryWin(bool isLeft) { var index = isLeft ? 1 : 2; if (Volatile.Read(ref _winner) == index) { return true; } if (Interlocked.CompareExchange(ref _winner, index, 0) == 0) { (isLeft ? _rightObserver : _leftObserver).Dispose(); return true; } return false; }
AmbCoordinator
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite.SqlServer/Converters/SqlServerSpecialConverters.cs
{ "start": 99, "end": 241 }
public class ____ : RowVersionConverter { public override string ColumnDefinition => "rowversion"; } }
SqlServerRowVersionConverter
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Bugzilla/Bugzilla42329.cs
{ "start": 2938, "end": 3475 }
public class ____ : ContentPageEx { public _42329_FrameWithListView() { var lv = new ListView(); var label = new Label() { Text = LabelPage1, AutomationId = LabelPage1 }; label.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(OpenRoot) }); var frame = new Frame { Content = lv }; Title = Page1Title; Content = new StackLayout { Children = { label, frame } }; } } static void OpenRoot() { Reference.IsPresented = true; }
_42329_FrameWithListView
csharp
ServiceStack__ServiceStack.OrmLite
tests/ServiceStack.OrmLite.Tests/Issues/ParamNameIssues.cs
{ "start": 349, "end": 1140 }
public class ____ : OrmLiteProvidersTestBase { public ParamNameIssues(DialectContext context) : base(context) {} [Test] public void Does_use_ParamName_filter() { OrmLiteConfig.ParamNameFilter = name => name.Replace("-", ""); using (var db = OpenDbConnection()) { db.DropAndCreateTable<LegacyRow>(); db.InsertAll(new [] { new LegacyRow { Name = "Row1", Age = 1 }, new LegacyRow { Name = "Row2", Age = 2 }, }); var rows = db.Select<LegacyRow>(); Assert.That(rows.Count, Is.EqualTo(2)); } OrmLiteConfig.ParamNameFilter = null; } } }
ParamNameIssues
csharp
abpframework__abp
framework/src/Volo.Abp.Ldap/Volo/Abp/Ldap/LdapManager.cs
{ "start": 236, "end": 1990 }
public class ____ : ILdapManager, ITransientDependency { public ILogger<LdapManager> Logger { get; set; } protected ILdapSettingProvider LdapSettingProvider { get; } public LdapManager(ILdapSettingProvider ldapSettingProvider) { LdapSettingProvider = ldapSettingProvider; Logger = NullLogger<LdapManager>.Instance; } public virtual async Task<bool> AuthenticateAsync(string username, string password) { try { using (var conn = await CreateLdapConnectionAsync()) { await AuthenticateLdapConnectionAsync(conn, username, password); return true; } } catch (Exception ex) { Logger.LogException(ex); return false; } } protected virtual async Task<ILdapConnection> CreateLdapConnectionAsync() { var ldapConnection = new LdapConnection(); await ConfigureLdapConnectionAsync(ldapConnection); await ConnectAsync(ldapConnection); return ldapConnection; } protected virtual Task ConfigureLdapConnectionAsync(ILdapConnection ldapConnection) { return Task.CompletedTask; } protected virtual async Task ConnectAsync(ILdapConnection ldapConnection) { ldapConnection.Connect(await LdapSettingProvider.GetServerHostAsync(), await LdapSettingProvider.GetServerPortAsync()); } protected virtual async Task AuthenticateLdapConnectionAsync(ILdapConnection connection, string username, string password) { await connection.BindAsync(Native.LdapAuthType.Simple, new LdapCredential() { UserName = username, Password = password }); } }
LdapManager
csharp
MassTransit__MassTransit
src/MassTransit/Clients/BusClientFactoryContext.cs
{ "start": 74, "end": 1628 }
public class ____ : ClientFactoryContext { readonly IBus _bus; public BusClientFactoryContext(IBus bus, RequestTimeout defaultTimeout = default) { _bus = bus; DefaultTimeout = defaultTimeout.HasValue ? defaultTimeout : RequestTimeout.Default; } public ConnectHandle ConnectConsumePipe<T>(IPipe<ConsumeContext<T>> pipe) where T : class { return _bus.ConnectConsumePipe(pipe); } public ConnectHandle ConnectConsumePipe<T>(IPipe<ConsumeContext<T>> pipe, ConnectPipeOptions options) where T : class { return _bus.ConnectConsumePipe(pipe, options); } public ConnectHandle ConnectRequestPipe<T>(Guid requestId, IPipe<ConsumeContext<T>> pipe) where T : class { return _bus.ConnectRequestPipe(requestId, pipe); } public Uri ResponseAddress => _bus.Address; public IRequestSendEndpoint<T> GetRequestEndpoint<T>(ConsumeContext? consumeContext = default) where T : class { return new PublishRequestSendEndpoint<T>(_bus, consumeContext); } public IRequestSendEndpoint<T> GetRequestEndpoint<T>(Uri destinationAddress, ConsumeContext? consumeContext = default) where T : class { return new SendRequestSendEndpoint<T>(_bus, destinationAddress, consumeContext); } public RequestTimeout DefaultTimeout { get; } } }
BusClientFactoryContext
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Types/Composite/Directives/EntityKeyDescriptorExtensions.cs
{ "start": 2393, "end": 2599 }
interface ____. /// </para> /// <para> /// <see href="https://graphql.github.io/composite-schemas-spec/draft/#sec--key"/> /// </para> /// </summary> /// <param name="descriptor">The
type
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui.Core/Interfaces/IDialogFragmentService.android.cs
{ "start": 85, "end": 1614 }
public interface ____ { void OnFragmentAttached(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, Context context); void OnFragmentCreated(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, Bundle? savedInstanceState); void OnFragmentDestroyed(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentDetached(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentPaused(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentPreAttached(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, Context context); void OnFragmentPreCreated(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, Bundle? savedInstanceState); void OnFragmentResumed(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentSaveInstanceState(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, Bundle outState); void OnFragmentStarted(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentStopped(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); void OnFragmentViewCreated(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f, View v, Bundle? savedInstanceState); void OnFragmentViewDestroyed(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment f); }
IDialogFragmentService
csharp
RicoSuter__NSwag
src/NSwag.Generation.WebApi.Tests/Attributes/ModelBinderQueryParametersTests.cs
{ "start": 708, "end": 944 }
public class ____ : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { return true; } }
CustomModelBinder
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/TimeService/time_service_should.cs
{ "start": 798, "end": 937 }
public class ____ : Message { public int Id { get; } public TestResponseMessage(int id) { Id = id; } } [TestFixture]
TestResponseMessage
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.Zero.Common/Localization/MultiTenantLocalizationSource.cs
{ "start": 304, "end": 8007 }
public class ____ : DictionaryBasedLocalizationSource, IMultiTenantLocalizationSource { public new MultiTenantLocalizationDictionaryProvider DictionaryProvider { get { return base.DictionaryProvider.As<MultiTenantLocalizationDictionaryProvider>(); } } public ILogger Logger { get; set; } public MultiTenantLocalizationSource(string name, MultiTenantLocalizationDictionaryProvider dictionaryProvider) : base(name, dictionaryProvider) { Logger = NullLogger.Instance; } public override void Initialize(ILocalizationConfiguration configuration, IIocResolver iocResolver) { base.Initialize(configuration, iocResolver); if (Logger is NullLogger && iocResolver.IsRegistered(typeof(ILoggerFactory))) { Logger = iocResolver.Resolve<ILoggerFactory>().Create(typeof (MultiTenantLocalizationSource)); } } public string FindKeyOrNull(int? tenantId, string value, CultureInfo culture, bool tryDefaults = true) { var cultureName = culture.Name; var dictionaries = DictionaryProvider.Dictionaries; //Try to get from original dictionary (with country code) if (dictionaries.TryGetValue(cultureName, out var originalDictionary)) { var keyOriginal = originalDictionary .As<IMultiTenantLocalizationDictionary>() .TryGetKey(tenantId, value); if (keyOriginal != null) { return keyOriginal; } } if (!tryDefaults) { return null; } //Try to get from same language dictionary (without country code) if (cultureName.Contains("-")) //Example: "tr-TR" (length=5) { if (dictionaries.TryGetValue(GetBaseCultureName(cultureName), out var langDictionary)) { var keyLang = langDictionary.As<IMultiTenantLocalizationDictionary>().TryGetKey(tenantId, value); if (keyLang != null) { return keyLang; } } } //Try to get from default language var defaultDictionary = DictionaryProvider.DefaultDictionary; if (defaultDictionary == null) { return null; } var keyDefault = defaultDictionary.As<IMultiTenantLocalizationDictionary>().TryGetKey(tenantId, value); if (keyDefault == null) { return null; } return keyDefault; } public string GetString(int? tenantId, string name, CultureInfo culture) { var value = GetStringOrNull(tenantId, name, culture); if (value == null) { return ReturnGivenNameOrThrowException(name, culture); } return value; } public string GetStringOrNull(int? tenantId, string name, CultureInfo culture, bool tryDefaults = true) { var cultureName = culture.Name; var dictionaries = DictionaryProvider.Dictionaries; //Try to get from original dictionary (with country code) if (dictionaries.TryGetValue(cultureName, out var originalDictionary)) { var strOriginal = originalDictionary .As<IMultiTenantLocalizationDictionary>() .GetOrNull(tenantId, name); if (strOriginal != null) { return strOriginal.Value; } } if (!tryDefaults) { return null; } //Try to get from same language dictionary (without country code) if (cultureName.Contains("-")) //Example: "tr-TR" (length=5) { if (dictionaries.TryGetValue(GetBaseCultureName(cultureName), out var langDictionary)) { var strLang = langDictionary.As<IMultiTenantLocalizationDictionary>().GetOrNull(tenantId, name); if (strLang != null) { return strLang.Value; } } } //Try to get from default language var defaultDictionary = DictionaryProvider.DefaultDictionary; if (defaultDictionary == null) { return null; } var strDefault = defaultDictionary.As<IMultiTenantLocalizationDictionary>().GetOrNull(tenantId, name); if (strDefault == null) { return null; } return strDefault.Value; } public List<string> GetStrings(int? tenantId, List<string> names, CultureInfo culture) { var value = GetStringsOrNull(tenantId, names, culture); if (value == null) { return ReturnGivenNamesOrThrowException(names, culture); } return value; } public List<string> GetStringsOrNull(int? tenantId, List<string> names, CultureInfo culture, bool tryDefaults = true) { var cultureName = culture.Name; var dictionaries = DictionaryProvider.Dictionaries; //Try to get from original dictionary (with country code) if (dictionaries.TryGetValue(cultureName, out var originalDictionary)) { var strOriginal = originalDictionary .As<IMultiTenantLocalizationDictionary>() .GetStringsOrNull(tenantId, names); if (!strOriginal.IsNullOrEmpty()) { return strOriginal.Select(x => x.Value).ToList(); } } if (!tryDefaults) { return null; } //Try to get from same language dictionary (without country code) if (cultureName.Contains("-")) //Example: "tr-TR" (length=5) { if (dictionaries.TryGetValue(GetBaseCultureName(cultureName), out var langDictionary)) { var strLang = langDictionary.As<IMultiTenantLocalizationDictionary>().GetStringsOrNull(tenantId, names); if (!strLang.IsNullOrEmpty()) { return strLang.Select(x => x.Value).ToList(); } } } //Try to get from default language var defaultDictionary = DictionaryProvider.DefaultDictionary; if (defaultDictionary == null) { return null; } var strDefault = defaultDictionary.As<IMultiTenantLocalizationDictionary>().GetStringsOrNull(tenantId, names); if (strDefault.IsNullOrEmpty()) { return null; } return strDefault.Select(x => x.Value).ToList(); } public override void Extend(ILocalizationDictionary dictionary) { DictionaryProvider.Extend(dictionary); } private static string GetBaseCultureName(string cultureName) { return cultureName.Contains("-") ? cultureName.Left(cultureName.IndexOf("-", StringComparison.Ordinal)) : cultureName; } } }
MultiTenantLocalizationSource
csharp
MaterialDesignInXAML__MaterialDesignInXamlToolkit
src/MaterialDesignThemes.Wpf/ColorReference.cs
{ "start": 82, "end": 1254 }
record ____ ColorReference(ThemeColorReference ThemeReference, Color? Color) { public static ColorReference SecondaryLight { get; } = new ColorReference(ThemeColorReference.SecondaryLight, null); public static ColorReference SecondaryMid { get; } = new ColorReference(ThemeColorReference.SecondaryMid, null); public static ColorReference SecondaryDark { get; } = new ColorReference(ThemeColorReference.SecondaryDark, null); public static ColorReference PrimaryLight { get; } = new ColorReference(ThemeColorReference.PrimaryLight, null); public static ColorReference PrimaryMid { get; } = new ColorReference(ThemeColorReference.PrimaryMid, null); public static ColorReference PrimaryDark { get; } = new ColorReference(ThemeColorReference.PrimaryDark, null); public static implicit operator ColorReference(Color color) => new(ThemeColorReference.None, color); public static implicit operator ColorReference(ThemeColorReference @ref) => new(@ref, null); public static implicit operator Color(ColorReference color) => color.Color ?? throw new InvalidOperationException($"{nameof(ColorReference)} does not contain any color"); }
struct
csharp
dotnet__reactive
Rx.NET/Source/tests/Tests.System.Reactive/Tests/Linq/Observable/DematerializeTest.cs
{ "start": 410, "end": 6086 }
public class ____ : ReactiveTest { [TestMethod] public void Dematerialize_ArgumentChecking() { ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Dematerialize<int>(null)); } [TestMethod] public void Dematerialize_Range1() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, Notification.CreateOnNext(41)), OnNext(210, Notification.CreateOnNext(42)), OnNext(220, Notification.CreateOnNext(43)), OnCompleted<Notification<int>>(250) ); var res = scheduler.Start(() => xs.Dematerialize() ); res.Messages.AssertEqual( OnNext(210, 42), OnNext(220, 43), OnCompleted<int>(250) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } [TestMethod] public void Dematerialize_Range2() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, Notification.CreateOnNext(41)), OnNext(210, Notification.CreateOnNext(42)), OnNext(220, Notification.CreateOnNext(43)), OnNext(230, Notification.CreateOnCompleted<int>()) ); var res = scheduler.Start(() => xs.Dematerialize() ); res.Messages.AssertEqual( OnNext(210, 42), OnNext(220, 43), OnCompleted<int>(230) ); xs.Subscriptions.AssertEqual( Subscribe(200, 230) ); } [TestMethod] public void Dematerialize_Error1() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, Notification.CreateOnNext(41)), OnNext(210, Notification.CreateOnNext(42)), OnNext(220, Notification.CreateOnNext(43)), OnError<Notification<int>>(230, ex) ); var res = scheduler.Start(() => xs.Dematerialize() ); res.Messages.AssertEqual( OnNext(210, 42), OnNext(220, 43), OnError<int>(230, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 230) ); } [TestMethod] public void Dematerialize_Error2() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, Notification.CreateOnNext(41)), OnNext(210, Notification.CreateOnNext(42)), OnNext(220, Notification.CreateOnNext(43)), OnNext(230, Notification.CreateOnError<int>(ex)) ); var res = scheduler.Start(() => xs.Dematerialize() ); res.Messages.AssertEqual( OnNext(210, 42), OnNext(220, 43), OnError<int>(230, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 230) ); } [TestMethod] public void Materialize_Dematerialize_Never() { var scheduler = new TestScheduler(); var xs = Observable.Never<int>(); var res = scheduler.Start(() => xs.Materialize().Dematerialize() ); res.Messages.AssertEqual( ); } [TestMethod] public void Materialize_Dematerialize_Empty() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.Materialize().Dematerialize() ); res.Messages.AssertEqual( OnCompleted<int>(250) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } [TestMethod] public void Materialize_Dematerialize_Return() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.Materialize().Dematerialize() ); res.Messages.AssertEqual( OnNext(210, 2), OnCompleted<int>(250) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } [TestMethod] public void Materialize_Dematerialize_Throw() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnError<int>(250, ex) ); var res = scheduler.Start(() => xs.Materialize().Dematerialize() ); res.Messages.AssertEqual( OnError<int>(250, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } } }
DematerializeTest
csharp
xunit__xunit
src/xunit.v3.core/Runners/XunitTestCaseRunnerContext.cs
{ "start": 859, "end": 1377 }
public class ____( IXunitTestCase testCase, IReadOnlyCollection<IXunitTest> tests, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource, string displayName, string? skipReason, ExplicitOption explicitOption, object?[] constructorArguments) : XunitTestCaseRunnerBaseContext<IXunitTestCase, IXunitTest>(testCase, tests, messageBus, aggregator, cancellationTokenSource, displayName, skipReason, explicitOption, constructorArguments) { }
XunitTestCaseRunnerContext
csharp
bitwarden__server
src/Core/Platform/PlatformServiceCollectionExtensions.cs
{ "start": 137, "end": 616 }
public static class ____ { /// <summary> /// Extend DI to include commands and queries exported from the Platform /// domain. /// </summary> public static IServiceCollection AddPlatformServices(this IServiceCollection services) { services.AddScoped<IGetInstallationQuery, GetInstallationQuery>(); services.AddScoped<IUpdateInstallationCommand, UpdateInstallationCommand>(); return services; } }
PlatformServiceCollectionExtensions
csharp
dotnet__maui
src/Controls/tests/ManualTests/Tests/Editor/D18.xaml.cs
{ "start": 189, "end": 277 }
public partial class ____ : ContentPage { public D18() { InitializeComponent(); } }
D18
csharp
aspnetboilerplate__aspnetboilerplate
test/aspnet-core-demo/AbpAspNetCoreDemo.Tests/Tests/RazorUowPageFilterTests.cs
{ "start": 208, "end": 2332 }
public class ____ : IClassFixture<WebApplicationFactory<Startup>> { private readonly WebApplicationFactory<Startup> _factory; public RazorUowPageFilterTests(WebApplicationFactory<Startup> factory) { _factory = factory; } [Theory] [InlineData("/UowFilterPageDemo", "200", "Razor page unit of work filter example")] [InlineData("/UowFilterPageDemo2", "500", "Current UnitOfWork is null")] public async Task RazorPage_UowPageFilter_Get_Test(string url, string responseCode, string responseText) { // Arrange var client = _factory.CreateClient(); // Act var response = await client.GetAsync(url); // Assert response.StatusCode.ShouldBe(Enum.Parse<HttpStatusCode>(responseCode)); var result = await response.Content.ReadAsStringAsync(); result.ShouldContain(responseText); } [Theory] [InlineData("/UowFilterPageDemo", "500", "Current UnitOfWork is null")] [InlineData("/UowFilterPageDemo2", "500", "Current UnitOfWork is null")] public async Task RazorPage_UowPageFilter_Post_Test(string url, string responseCode, string responseText) { // Arrange var client = _factory.CreateClient(); // Act var response = await client.PostAsync(url, new StringContent("")); // Assert response.StatusCode.ShouldBe(Enum.Parse<HttpStatusCode>(responseCode)); var result = await response.Content.ReadAsStringAsync(); result.ShouldContain(responseText); } [Theory] [InlineData("Get")] [InlineData("Post")] public async Task RazorPage_UowPageFilter_NoAction_Test(string method) { // Arrange var client = _factory.CreateClient(); // Act var requestMessage = new HttpRequestMessage(new HttpMethod(method), "/UowFilterPageDemo3"); var response = await client.SendAsync(requestMessage); // Assert response.EnsureSuccessStatusCode(); (await response.Content.ReadAsStringAsync()).ShouldContain("<title>UowFilterPageDemo3</title>"); } }
RazorUowPageFilterTests
csharp
reactiveui__ReactiveUI
src/ReactiveUI.Testing/IBuilderExtensions.cs
{ "start": 550, "end": 5684 }
public static class ____ { /// <summary> /// Adds the specified field to the builder. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public static TBuilder With<TBuilder, TField>(this TBuilder builder, out TField field, TField value) where TBuilder : IBuilder { field = value; return builder; } /// <summary> /// Adds the specified list of fields to the builder. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="field">The field.</param> /// <param name="values">The values.</param> /// <returns>The builder.</returns> public static TBuilder With<TBuilder, TField>( this TBuilder builder, ref List<TField>? field, IEnumerable<TField> values) where TBuilder : IBuilder { if (field is null) { throw new ArgumentNullException(nameof(field)); } field.AddRange(values); return builder; } /// <summary> /// Adds the specified field to the builder. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public static TBuilder With<TBuilder, TField>(this TBuilder builder, ref List<TField>? field, TField value) where TBuilder : IBuilder { if (field is null) { throw new ArgumentNullException(nameof(field)); } field.Add(value); return builder; } /// <summary> /// Adds the specified key value pair to the provided dictionary. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="dictionary">The dictionary.</param> /// <param name="keyValuePair">The key value pair.</param> /// <returns>The builder.</returns> public static TBuilder With<TBuilder, TKey, TField>( this TBuilder builder, ref Dictionary<TKey, TField> dictionary, KeyValuePair<TKey, TField> keyValuePair) where TBuilder : IBuilder where TKey : notnull { if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } dictionary.Add(keyValuePair.Key, keyValuePair.Value); return builder; } /// <summary> /// Adds the specified key and value to the provided dictionary. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public static TBuilder With<TBuilder, TKey, TField>( this TBuilder builder, ref Dictionary<TKey, TField> dictionary, TKey key, TField value) where TBuilder : IBuilder where TKey : notnull { if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } dictionary.Add(key, value); return builder; } /// <summary> /// Adds the specified dictionary to the provided dictionary. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TField">The type of the field.</typeparam> /// <param name="builder">This builder.</param> /// <param name="dictionary">The dictionary.</param> /// <param name="keyValuePair">The key value pair.</param> /// <returns> The builder.</returns> public static TBuilder With<TBuilder, TKey, TField>( this TBuilder builder, ref Dictionary<TKey, TField> dictionary, IDictionary<TKey, TField> keyValuePair) where TKey : notnull { if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } dictionary = (Dictionary<TKey, TField>)keyValuePair; return builder; } } #pragma warning restore SA1402, SA1649, CA1040
IBuilderExtensions
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/MongoCollectionImpl.cs
{ "start": 27439, "end": 71191 }
struct ____ operation = CreateFindOneAndReplaceOperation(filter, replacementObject, options); return ExecuteWriteOperationAsync(session, operation, options?.Timeout, cancellationToken); } public override TProjection FindOneAndUpdate<TProjection>(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TProjection> options, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return FindOneAndUpdate(session, filter, update, options, cancellationToken); } public override TProjection FindOneAndUpdate<TProjection>(IClientSessionHandle session, FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TProjection> options, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options ??= new FindOneAndUpdateOptions<TDocument, TProjection>(); if (update is PipelineUpdateDefinition<TDocument> && (options.ArrayFilters != null && options.ArrayFilters.Any())) { throw new NotSupportedException("An arrayfilter is not supported in the pipeline-style update."); } var operation = CreateFindOneAndUpdateOperation(filter, update, options); return ExecuteWriteOperation(session, operation, options?.Timeout, cancellationToken); } public override async Task<TProjection> FindOneAndUpdateAsync<TProjection>(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TProjection> options, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return await FindOneAndUpdateAsync(session, filter, update, options, cancellationToken).ConfigureAwait(false); } public override Task<TProjection> FindOneAndUpdateAsync<TProjection>(IClientSessionHandle session, FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TProjection> options, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options ??= new FindOneAndUpdateOptions<TDocument, TProjection>(); if (update is PipelineUpdateDefinition<TDocument> && (options.ArrayFilters != null && options.ArrayFilters.Any())) { throw new NotSupportedException("An arrayfilter is not supported in the pipeline-style update."); } var operation = CreateFindOneAndUpdateOperation(filter, update, options); return ExecuteWriteOperationAsync(session, operation, options?.Timeout, cancellationToken); } [Obsolete("Use Aggregation pipeline instead.")] public override IAsyncCursor<TResult> MapReduce<TResult>(BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options = null, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return MapReduce(session, map, reduce, options, cancellationToken: cancellationToken); } [Obsolete("Use Aggregation pipeline instead.")] public override IAsyncCursor<TResult> MapReduce<TResult>(IClientSessionHandle session, BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(map, nameof(map)); Ensure.IsNotNull(reduce, nameof(reduce)); options ??= new MapReduceOptions<TDocument, TResult>(); var outputOptions = options.OutputOptions ?? MapReduceOutputOptions.Inline; var resultSerializer = ResolveResultSerializer<TResult>(options.ResultSerializer); var renderArgs = GetRenderArgs(); if (outputOptions == MapReduceOutputOptions.Inline) { var operation = CreateMapReduceOperation(map, reduce, options, resultSerializer, renderArgs); return ExecuteReadOperation(session, operation, options.Timeout, cancellationToken); } else { var mapReduceOperation = CreateMapReduceOutputToCollectionOperation(map, reduce, options, outputOptions, renderArgs); ExecuteWriteOperation(session, mapReduceOperation, options.Timeout, cancellationToken); return CreateMapReduceOutputToCollectionResultCursor(session, options, mapReduceOperation.OutputCollectionNamespace, resultSerializer); } } [Obsolete("Use Aggregation pipeline instead.")] public override async Task<IAsyncCursor<TResult>> MapReduceAsync<TResult>(BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options = null, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return await MapReduceAsync(session, map, reduce, options, cancellationToken).ConfigureAwait(false); } [Obsolete("Use Aggregation pipeline instead.")] public override async Task<IAsyncCursor<TResult>> MapReduceAsync<TResult>(IClientSessionHandle session, BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(map, nameof(map)); Ensure.IsNotNull(reduce, nameof(reduce)); options ??= new MapReduceOptions<TDocument, TResult>(); var outputOptions = options.OutputOptions ?? MapReduceOutputOptions.Inline; var resultSerializer = ResolveResultSerializer<TResult>(options.ResultSerializer); var renderArgs = GetRenderArgs(); if (outputOptions == MapReduceOutputOptions.Inline) { var operation = CreateMapReduceOperation(map, reduce, options, resultSerializer, renderArgs); return await ExecuteReadOperationAsync(session, operation, options.Timeout, cancellationToken).ConfigureAwait(false); } else { var mapReduceOperation = CreateMapReduceOutputToCollectionOperation(map, reduce, options, outputOptions, renderArgs); await ExecuteWriteOperationAsync(session, mapReduceOperation, options.Timeout, cancellationToken).ConfigureAwait(false); return CreateMapReduceOutputToCollectionResultCursor(session, options, mapReduceOperation.OutputCollectionNamespace, resultSerializer); } } public override IFilteredMongoCollection<TDerivedDocument> OfType<TDerivedDocument>() { var derivedDocumentSerializer = _settings.SerializerRegistry.GetSerializer<TDerivedDocument>(); var ofTypeSerializer = new OfTypeSerializer<TDocument, TDerivedDocument>(derivedDocumentSerializer); var derivedDocumentCollection = new MongoCollectionImpl<TDerivedDocument>(_database, _collectionNamespace, _settings, _cluster, _operationExecutor, ofTypeSerializer); var rootOfTypeFilter = Builders<TDocument>.Filter.OfType<TDerivedDocument>(); var renderArgs = GetRenderArgs(); var renderedOfTypeFilter = rootOfTypeFilter.Render(renderArgs); var ofTypeFilter = new BsonDocumentFilterDefinition<TDerivedDocument>(renderedOfTypeFilter); return new OfTypeMongoCollection<TDocument, TDerivedDocument>(this, derivedDocumentCollection, ofTypeFilter); } public override IChangeStreamCursor<TResult> Watch<TResult>( PipelineDefinition<ChangeStreamDocument<TDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return Watch(session, pipeline, options, cancellationToken); } public override IChangeStreamCursor<TResult> Watch<TResult>( IClientSessionHandle session, PipelineDefinition<ChangeStreamDocument<TDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(pipeline, nameof(pipeline)); var operation = CreateChangeStreamOperation(pipeline, options); return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken); } public override async Task<IChangeStreamCursor<TResult>> WatchAsync<TResult>( PipelineDefinition<ChangeStreamDocument<TDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { using var session = _operationExecutor.StartImplicitSession(); return await WatchAsync(session, pipeline, options, cancellationToken).ConfigureAwait(false); } public override Task<IChangeStreamCursor<TResult>> WatchAsync<TResult>( IClientSessionHandle session, PipelineDefinition<ChangeStreamDocument<TDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(pipeline, nameof(pipeline)); var operation = CreateChangeStreamOperation(pipeline, options); return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken); } public override IMongoCollection<TDocument> WithReadConcern(ReadConcern readConcern) { var newSettings = _settings.Clone(); newSettings.ReadConcern = readConcern; return new MongoCollectionImpl<TDocument>(_database, _collectionNamespace, newSettings, _cluster, _operationExecutor); } public override IMongoCollection<TDocument> WithReadPreference(ReadPreference readPreference) { var newSettings = _settings.Clone(); newSettings.ReadPreference = readPreference; return new MongoCollectionImpl<TDocument>(_database, _collectionNamespace, newSettings, _cluster, _operationExecutor); } public override IMongoCollection<TDocument> WithWriteConcern(WriteConcern writeConcern) { var newSettings = _settings.Clone(); newSettings.WriteConcern = writeConcern; return new MongoCollectionImpl<TDocument>(_database, _collectionNamespace, newSettings, _cluster, _operationExecutor); } // private methods private WriteRequest ConvertWriteModelToWriteRequest(WriteModel<TDocument> model, int index, RenderArgs<TDocument> renderArgs) { switch (model.ModelType) { case WriteModelType.InsertOne: var insertOneModel = (InsertOneModel<TDocument>)model; if (_settings.AssignIdOnInsert) { _documentSerializer.SetDocumentIdIfMissing(this, insertOneModel.Document); } return new InsertRequest(new BsonDocumentWrapper(insertOneModel.Document, _documentSerializer)) { CorrelationId = index }; case WriteModelType.DeleteMany: var deleteManyModel = (DeleteManyModel<TDocument>)model; return new DeleteRequest(deleteManyModel.Filter.Render(renderArgs)) { CorrelationId = index, Collation = deleteManyModel.Collation, Hint = deleteManyModel.Hint, Limit = 0 }; case WriteModelType.DeleteOne: var deleteOneModel = (DeleteOneModel<TDocument>)model; return new DeleteRequest(deleteOneModel.Filter.Render(renderArgs)) { CorrelationId = index, Collation = deleteOneModel.Collation, Hint = deleteOneModel.Hint, Limit = 1 }; case WriteModelType.ReplaceOne: var replaceOneModel = (ReplaceOneModel<TDocument>)model; return new UpdateRequest( UpdateType.Replacement, replaceOneModel.Filter.Render(renderArgs), new BsonDocumentWrapper(replaceOneModel.Replacement, _documentSerializer)) { Collation = replaceOneModel.Collation, CorrelationId = index, Hint = replaceOneModel.Hint, IsMulti = false, IsUpsert = replaceOneModel.IsUpsert, Sort = replaceOneModel.Sort?.Render(renderArgs) }; case WriteModelType.UpdateMany: var updateManyModel = (UpdateManyModel<TDocument>)model; return new UpdateRequest( UpdateType.Update, updateManyModel.Filter.Render(renderArgs), updateManyModel.Update.Render(renderArgs)) { ArrayFilters = RenderArrayFilters(updateManyModel.ArrayFilters), Collation = updateManyModel.Collation, CorrelationId = index, Hint = updateManyModel.Hint, IsMulti = true, IsUpsert = updateManyModel.IsUpsert }; case WriteModelType.UpdateOne: var updateOneModel = (UpdateOneModel<TDocument>)model; return new UpdateRequest( UpdateType.Update, updateOneModel.Filter.Render(renderArgs), updateOneModel.Update.Render(renderArgs)) { ArrayFilters = RenderArrayFilters(updateOneModel.ArrayFilters), Collation = updateOneModel.Collation, CorrelationId = index, Hint = updateOneModel.Hint, IsMulti = false, IsUpsert = updateOneModel.IsUpsert, Sort = updateOneModel.Sort?.Render(renderArgs) }; default: throw new InvalidOperationException("Unknown type of WriteModel provided."); } } private AggregateOperation<TResult> CreateAggregateOperation<TResult>(RenderedPipelineDefinition<TResult> renderedPipeline, AggregateOptions options) { return new AggregateOperation<TResult>( _collectionNamespace, renderedPipeline.Documents, renderedPipeline.OutputSerializer, _messageEncoderSettings) { AllowDiskUse = options.AllowDiskUse, BatchSize = options.BatchSize, Collation = options.Collation, Comment = options.Comment, Hint = options.Hint, Let = options.Let, MaxAwaitTime = options.MaxAwaitTime, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, #pragma warning disable 618 UseCursor = options.UseCursor #pragma warning restore 618 }; } private IAsyncCursor<TResult> CreateAggregateToCollectionResultCursor<TResult>(IClientSessionHandle session, RenderedPipelineDefinition<TResult> pipeline, AggregateOptions options) { var outputCollectionNamespace = AggregateHelper.GetOutCollection(pipeline.Documents.Last(), _collectionNamespace.DatabaseNamespace); var findOperation = new FindOperation<TResult>(outputCollectionNamespace, pipeline.OutputSerializer, _messageEncoderSettings) { BatchSize = options.BatchSize, Collation = options.Collation, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads }; // we want to delay execution of the find because the user may // not want to iterate the results at all... var forkedSession = session.Fork(); var deferredCursor = new DeferredAsyncCursor<TResult>( () => forkedSession.Dispose(), ct => ExecuteReadOperation(forkedSession, findOperation, ReadPreference.Primary, options?.Timeout, ct), ct => ExecuteReadOperationAsync(forkedSession, findOperation, ReadPreference.Primary, options?.Timeout, ct)); return deferredCursor; } private AggregateToCollectionOperation CreateAggregateToCollectionOperation<TResult>(RenderedPipelineDefinition<TResult> renderedPipeline, AggregateOptions options) { return new AggregateToCollectionOperation( _collectionNamespace, renderedPipeline.Documents, _messageEncoderSettings) { AllowDiskUse = options.AllowDiskUse, BypassDocumentValidation = options.BypassDocumentValidation, Collation = options.Collation, Comment = options.Comment, Hint = options.Hint, Let = options.Let, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, ReadPreference = _settings.ReadPreference, WriteConcern = _settings.WriteConcern }; } private BulkMixedWriteOperation CreateBulkWriteOperation( IClientSessionHandle session, IReadOnlyList<WriteModel<TDocument>> requests, BulkWriteOptions options) { options ??= new BulkWriteOptions(); var renderArgs = GetRenderArgs(); var effectiveWriteConcern = session.IsInTransaction ? WriteConcern.Acknowledged : _settings.WriteConcern; var writeModels = requests.Select((model, index) => { model.ThrowIfNotValid(); return ConvertWriteModelToWriteRequest(model, index, renderArgs); }).ToArray(); return new BulkMixedWriteOperation( _collectionNamespace, writeModels, _messageEncoderSettings) { BypassDocumentValidation = options.BypassDocumentValidation, Comment = options.Comment, IsOrdered = options.IsOrdered, Let = options.Let, RetryRequested = _database.Client.Settings.RetryWrites, WriteConcern = effectiveWriteConcern }; } private ChangeStreamOperation<TResult> CreateChangeStreamOperation<TResult>( PipelineDefinition<ChangeStreamDocument<TDocument>, TResult> pipeline, ChangeStreamOptions options) { var translationOptions = _database.Client.Settings.TranslationOptions; return ChangeStreamHelper.CreateChangeStreamOperation( this, pipeline, _documentSerializer, options, _settings.ReadConcern, messageEncoderSettings: _messageEncoderSettings, _database.Client.Settings.RetryReads, translationOptions); } private CountDocumentsOperation CreateCountDocumentsOperation( FilterDefinition<TDocument> filter, CountOptions options) { options ??= new CountOptions(); var renderArgs = GetRenderArgs(); return new CountDocumentsOperation(_collectionNamespace, _messageEncoderSettings) { Collation = options.Collation, Comment = options.Comment, Filter = filter.Render(renderArgs), Hint = options.Hint, Limit = options.Limit, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, Skip = options.Skip }; } private CountOperation CreateCountOperation( FilterDefinition<TDocument> filter, CountOptions options) { options ??= new CountOptions(); var renderArgs = GetRenderArgs(); return new CountOperation(_collectionNamespace, _messageEncoderSettings) { Collation = options.Collation, Comment = options.Comment, Filter = filter.Render(renderArgs), Hint = options.Hint, Limit = options.Limit, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, Skip = options.Skip }; } private DistinctOperation<TField> CreateDistinctOperation<TField>( FieldDefinition<TDocument, TField> field, FilterDefinition<TDocument> filter, DistinctOptions options) { options ??= new DistinctOptions(); var renderArgs = GetRenderArgs(); var renderedField = field.Render(renderArgs); var valueSerializer = GetValueSerializerForDistinct(renderedField, _settings.SerializerRegistry); return new DistinctOperation<TField>( _collectionNamespace, valueSerializer, renderedField.FieldName, _messageEncoderSettings) { Collation = options.Collation, Comment = options.Comment, Filter = filter.Render(renderArgs), MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, }; } private DistinctOperation<TItem> CreateDistinctManyOperation<TItem>( FieldDefinition<TDocument, IEnumerable<TItem>> field, FilterDefinition<TDocument> filter, DistinctOptions options) { options ??= new DistinctOptions(); var renderArgs = GetRenderArgs(); var renderedField = field.Render(renderArgs); var itemSerializer = GetItemSerializerForDistinctMany(renderedField, _settings.SerializerRegistry); return new DistinctOperation<TItem>( _collectionNamespace, itemSerializer, renderedField.FieldName, _messageEncoderSettings) { Collation = options.Collation, Comment = options.Comment, Filter = filter.Render(renderArgs), MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, }; } private EstimatedDocumentCountOperation CreateEstimatedDocumentCountOperation(EstimatedDocumentCountOptions options) { return new EstimatedDocumentCountOperation(_collectionNamespace, _messageEncoderSettings) { Comment = options?.Comment, MaxTime = options?.MaxTime, RetryRequested = _database.Client.Settings.RetryReads }; } private FindOneAndDeleteOperation<TProjection> CreateFindOneAndDeleteOperation<TProjection>( FilterDefinition<TDocument> filter, FindOneAndDeleteOptions<TDocument, TProjection> options) { options ??= new FindOneAndDeleteOptions<TDocument, TProjection>(); var renderArgs = GetRenderArgs(); var projection = options.Projection ?? new ClientSideDeserializationProjectionDefinition<TDocument, TProjection>(); var renderedProjection = projection.Render(renderArgs with { RenderForFind = true }); return new FindOneAndDeleteOperation<TProjection>( _collectionNamespace, filter.Render(renderArgs), new FindAndModifyValueDeserializer<TProjection>(renderedProjection.ProjectionSerializer), _messageEncoderSettings) { Collation = options.Collation, Comment = options.Comment, Hint = options.Hint, Let = options.Let, MaxTime = options.MaxTime, Projection = renderedProjection.Document, Sort = options.Sort?.Render(renderArgs), WriteConcern = _settings.WriteConcern, RetryRequested = _database.Client.Settings.RetryWrites }; } private FindOneAndReplaceOperation<TProjection> CreateFindOneAndReplaceOperation<TProjection>( FilterDefinition<TDocument> filter, object replacement, FindOneAndReplaceOptions<TDocument, TProjection> options) { options ??= new FindOneAndReplaceOptions<TDocument, TProjection>(); var renderArgs = GetRenderArgs(); var projection = options.Projection ?? new ClientSideDeserializationProjectionDefinition<TDocument, TProjection>(); var renderedProjection = projection.Render(renderArgs with { RenderForFind = true }); return new FindOneAndReplaceOperation<TProjection>( _collectionNamespace, filter.Render(renderArgs), new BsonDocumentWrapper(replacement, _documentSerializer), new FindAndModifyValueDeserializer<TProjection>(renderedProjection.ProjectionSerializer), _messageEncoderSettings) { BypassDocumentValidation = options.BypassDocumentValidation, Collation = options.Collation, Comment = options.Comment, Hint = options.Hint, IsUpsert = options.IsUpsert, Let = options.Let, MaxTime = options.MaxTime, Projection = renderedProjection.Document, ReturnDocument = options.ReturnDocument, Sort = options.Sort?.Render(renderArgs), WriteConcern = _settings.WriteConcern, RetryRequested = _database.Client.Settings.RetryWrites }; } private FindOneAndUpdateOperation<TProjection> CreateFindOneAndUpdateOperation<TProjection>( FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TProjection> options) { var renderArgs = GetRenderArgs(); var projection = options.Projection ?? new ClientSideDeserializationProjectionDefinition<TDocument, TProjection>(); var renderedProjection = projection.Render(renderArgs with { RenderForFind = true }); return new FindOneAndUpdateOperation<TProjection>( _collectionNamespace, filter.Render(renderArgs), update.Render(renderArgs), new FindAndModifyValueDeserializer<TProjection>(renderedProjection.ProjectionSerializer), _messageEncoderSettings) { ArrayFilters = RenderArrayFilters(options.ArrayFilters), BypassDocumentValidation = options.BypassDocumentValidation, Collation = options.Collation, Comment = options.Comment, Hint = options.Hint, IsUpsert = options.IsUpsert, Let = options.Let, MaxTime = options.MaxTime, Projection = renderedProjection.Document, ReturnDocument = options.ReturnDocument, Sort = options.Sort?.Render(renderArgs), WriteConcern = _settings.WriteConcern, RetryRequested = _database.Client.Settings.RetryWrites }; } private FindOperation<TProjection> CreateFindOperation<TProjection>( FilterDefinition<TDocument> filter, FindOptions<TDocument, TProjection> options) { options ??= new FindOptions<TDocument, TProjection>(); var renderArgs = GetRenderArgs(options.TranslationOptions); var projection = options.Projection ?? new ClientSideDeserializationProjectionDefinition<TDocument, TProjection>(); var renderedProjection = projection.Render(renderArgs with { RenderForFind = true }); return new FindOperation<TProjection>( _collectionNamespace, renderedProjection.ProjectionSerializer, _messageEncoderSettings) { AllowDiskUse = options.AllowDiskUse, AllowPartialResults = options.AllowPartialResults, BatchSize = options.BatchSize, Collation = options.Collation, Comment = options.Comment, CursorType = options.CursorType, Filter = filter.Render(renderArgs), Hint = options.Hint, Let = options.Let, Limit = options.Limit, Max = options.Max, MaxAwaitTime = options.MaxAwaitTime, MaxTime = options.MaxTime, Min = options.Min, NoCursorTimeout = options.NoCursorTimeout, #pragma warning disable 618 OplogReplay = options.OplogReplay, #pragma warning restore 618 Projection = renderedProjection.Document, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads, ReturnKey = options.ReturnKey, ShowRecordId = options.ShowRecordId, Skip = options.Skip, Sort = options.Sort?.Render(renderArgs) }; } #pragma warning disable CS0618 // Type or member is obsolete private MapReduceOperation<TResult> CreateMapReduceOperation<TResult>( BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options, IBsonSerializer<TResult> resultSerializer, RenderArgs<TDocument> renderArgs) { return new MapReduceOperation<TResult>( #pragma warning restore CS0618 // Type or member is obsolete _collectionNamespace, map, reduce, resultSerializer, _messageEncoderSettings) { Collation = options.Collation, Filter = options.Filter?.Render(renderArgs), FinalizeFunction = options.Finalize, #pragma warning disable 618 JavaScriptMode = options.JavaScriptMode, #pragma warning restore 618 Limit = options.Limit, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, Scope = options.Scope, Sort = options.Sort?.Render(renderArgs), Verbose = options.Verbose }; } #pragma warning disable CS0618 // Type or member is obsolete private MapReduceOutputToCollectionOperation CreateMapReduceOutputToCollectionOperation<TResult>( BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions<TDocument, TResult> options, MapReduceOutputOptions outputOptions, RenderArgs<TDocument> renderArgs) { var collectionOutputOptions = (MapReduceOutputOptions.CollectionOutput)outputOptions; var databaseNamespace = collectionOutputOptions.DatabaseName == null ? _collectionNamespace.DatabaseNamespace : new DatabaseNamespace(collectionOutputOptions.DatabaseName); var outputCollectionNamespace = new CollectionNamespace(databaseNamespace, collectionOutputOptions.CollectionName); return new MapReduceOutputToCollectionOperation( #pragma warning restore CS0618 // Type or member is obsolete _collectionNamespace, outputCollectionNamespace, map, reduce, _messageEncoderSettings) { BypassDocumentValidation = options.BypassDocumentValidation, Collation = options.Collation, Filter = options.Filter?.Render(renderArgs), FinalizeFunction = options.Finalize, #pragma warning disable 618 JavaScriptMode = options.JavaScriptMode, #pragma warning restore 618 Limit = options.Limit, MaxTime = options.MaxTime, #pragma warning disable 618 NonAtomicOutput = collectionOutputOptions.NonAtomic, #pragma warning restore 618 Scope = options.Scope, OutputMode = collectionOutputOptions.OutputMode, #pragma warning disable 618 ShardedOutput = collectionOutputOptions.Sharded, #pragma warning restore 618 Sort = options.Sort?.Render(renderArgs), Verbose = options.Verbose, WriteConcern = _settings.WriteConcern }; } #pragma warning disable CS0618 // Type or member is obsolete private IAsyncCursor<TResult> CreateMapReduceOutputToCollectionResultCursor<TResult>(IClientSessionHandle session, MapReduceOptions<TDocument, TResult> options, CollectionNamespace outputCollectionNamespace, IBsonSerializer<TResult> resultSerializer) #pragma warning restore CS0618 // Type or member is obsolete { var findOperation = new FindOperation<TResult>( outputCollectionNamespace, resultSerializer, _messageEncoderSettings) { Collation = options.Collation, MaxTime = options.MaxTime, ReadConcern = _settings.ReadConcern, RetryRequested = _database.Client.Settings.RetryReads }; // we want to delay execution of the find because the user may // not want to iterate the results at all... var forkedSession = session.Fork(); var deferredCursor = new DeferredAsyncCursor<TResult>( () => forkedSession.Dispose(), ct => ExecuteReadOperation(forkedSession, findOperation, ReadPreference.Primary, options?.Timeout, ct), ct => ExecuteReadOperationAsync(forkedSession, findOperation, ReadPreference.Primary, options?.Timeout, ct)); return deferredCursor; } private OperationContext CreateOperationContext(IClientSessionHandle session, TimeSpan? timeout, CancellationToken cancellationToken) { var operationContext = session.WrappedCoreSession.CurrentTransaction?.OperationContext; if (operationContext != null && timeout != null) { throw new InvalidOperationException("Cannot specify per operation timeout inside transaction."); } return operationContext?.Fork() ?? new OperationContext(timeout ?? _settings.Timeout, cancellationToken); } private TResult ExecuteReadOperation<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) => ExecuteReadOperation(session, operation, null, timeout, cancellationToken); private TResult ExecuteReadOperation<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, ReadPreference explicitReadPreference, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return _operationExecutor.ExecuteReadOperation(operationContext, session, operation, readPreference, true); } private Task<TResult> ExecuteReadOperationAsync<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) => ExecuteReadOperationAsync(session, operation, null, timeout, cancellationToken); private async Task<TResult> ExecuteReadOperationAsync<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, ReadPreference explicitReadPreference, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return await _operationExecutor.ExecuteReadOperationAsync(operationContext, session, operation, readPreference, true).ConfigureAwait(false); } private TResult ExecuteWriteOperation<TResult>(IClientSessionHandle session, IWriteOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return _operationExecutor.ExecuteWriteOperation(operationContext, session, operation, true); } private async Task<TResult> ExecuteWriteOperationAsync<TResult>(IClientSessionHandle session, IWriteOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, session, operation, true).ConfigureAwait(false); } private MessageEncoderSettings GetMessageEncoderSettings() { var messageEncoderSettings = new MessageEncoderSettings { { MessageEncoderSettingsName.ReadEncoding, _settings.ReadEncoding ?? Utf8Encodings.Strict }, { MessageEncoderSettingsName.WriteEncoding, _settings.WriteEncoding ?? Utf8Encodings.Strict } }; if (_database.Client is MongoClient mongoClient) { mongoClient.ConfigureAutoEncryptionMessageEncoderSettings(messageEncoderSettings); } return messageEncoderSettings; } private IBsonSerializer<TField> GetValueSerializerForDistinct<TField>(RenderedFieldDefinition<TField> renderedField, IBsonSerializerRegistry serializerRegistry) { if (renderedField.UnderlyingSerializer != null) { if (renderedField.UnderlyingSerializer.ValueType == typeof(TField)) { return (IBsonSerializer<TField>)renderedField.UnderlyingSerializer; } var arraySerializer = renderedField.UnderlyingSerializer as IBsonArraySerializer; if (arraySerializer != null) { BsonSerializationInfo itemSerializationInfo; if (arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo)) { if (itemSerializationInfo.Serializer.ValueType == typeof(TField)) { return (IBsonSerializer<TField>)itemSerializationInfo.Serializer; } } } } return serializerRegistry.GetSerializer<TField>(); } private IBsonSerializer<TItem> GetItemSerializerForDistinctMany<TItem>(RenderedFieldDefinition<IEnumerable<TItem>> renderedField, IBsonSerializerRegistry serializerRegistry) { if (renderedField.UnderlyingSerializer != null) { if (renderedField.UnderlyingSerializer is IBsonArraySerializer arraySerializer) { BsonSerializationInfo itemSerializationInfo; if (arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo)) { if (itemSerializationInfo.Serializer.ValueType == typeof(TItem)) { return (IBsonSerializer<TItem>)itemSerializationInfo.Serializer; } } } } return serializerRegistry.GetSerializer<TItem>(); } private RenderArgs<TDocument> GetRenderArgs() { var translationOptions = _database.Client.Settings.TranslationOptions; return new RenderArgs<TDocument>(_documentSerializer, _settings.SerializerRegistry, translationOptions: translationOptions); } private RenderArgs<TDocument> GetRenderArgs(ExpressionTranslationOptions translationOptions) { translationOptions = translationOptions.AddMissingOptionsFrom(_database.Client.Settings.TranslationOptions); return new RenderArgs<TDocument>(_documentSerializer, _settings.SerializerRegistry, translationOptions: translationOptions); } private IEnumerable<BsonDocument> RenderArrayFilters(IEnumerable<ArrayFilterDefinition> arrayFilters) { if (arrayFilters == null) { return null; } var renderedArrayFilters = new List<BsonDocument>(); foreach (var arrayFilter in arrayFilters) { var renderedArrayFilter = arrayFilter.Render(null, _settings.SerializerRegistry); renderedArrayFilters.Add(renderedArrayFilter); } return renderedArrayFilters; } private IBsonSerializer<TResult> ResolveResultSerializer<TResult>(IBsonSerializer<TResult> resultSerializer) { if (resultSerializer != null) { return resultSerializer; } if (typeof(TResult) == typeof(TDocument) && _documentSerializer != null) { return (IBsonSerializer<TResult>)_documentSerializer; } return _settings.SerializerRegistry.GetSerializer<TResult>(); } // nested types
var
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/LoggerExtensions.cs
{ "start": 422, "end": 580 }
struct ____(ServerEndPoint server) { public override string ToString() => Format.ToString(server); } internal readonly
ServerEndPointLogValue
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/Automatonymous/AnyStateTransition_Specs.cs
{ "start": 137, "end": 995 }
public class ____ { [Test] public void Should_be_running() { Assert.That(_instance.CurrentState, Is.EqualTo(_machine.Running)); } [Test] public void Should_have_entered_running() { Assert.That(_instance.LastEntered, Is.EqualTo(_machine.Running)); } [Test] public void Should_have_left_initial() { Assert.That(_instance.LastLeft, Is.EqualTo(_machine.Initial)); } Instance _instance; InstanceStateMachine _machine; [OneTimeSetUp] public void Setup() { _instance = new Instance(); _machine = new InstanceStateMachine(); _machine.RaiseEvent(_instance, x => x.Initialized) .Wait(); }
When_any_state_transition_occurs
csharp
dotnetcore__Util
src/Util.Scheduling/NullScheduler.cs
{ "start": 72, "end": 815 }
public class ____ : IScheduler { /// <summary> /// 空调度器实例 /// </summary> public static readonly IScheduler Instance = new NullScheduler(); /// <summary> /// 启动 /// </summary> public Task StartAsync( CancellationToken cancellationToken = default ) { return Task.CompletedTask; } /// <summary> /// 暂停 /// </summary> public Task PauseAsync() { return Task.CompletedTask; } /// <summary> /// 恢复 /// </summary> public Task ResumeAsync() { return Task.CompletedTask; } /// <summary> /// 停止 /// </summary> public Task StopAsync( CancellationToken cancellationToken = default ) { return Task.CompletedTask; } }
NullScheduler
csharp
grandnode__grandnode2
src/Web/Grand.Web/Models/Checkout/CheckoutPaymentMethodModel.cs
{ "start": 572, "end": 921 }
public class ____ : BaseModel { public string PaymentMethodSystemName { get; set; } public string Name { get; set; } public string Description { get; set; } public string Fee { get; set; } public bool Selected { get; set; } public string LogoUrl { get; set; } } #endregion }
PaymentMethodModel
csharp
dotnetcore__FreeSql
Extensions/FreeSql.Extensions.Linq/SelectedQueryProvider.cs
{ "start": 336, "end": 1825 }
public interface ____<TOut> { Select0Provider SelectOwner { get; } #if net40 #else Task<List<TOut>> ToListAsync(CancellationToken cancellationToken = default); Task<TOut> ToOneAsync(CancellationToken cancellationToken = default); Task<TOut> FirstAsync(CancellationToken cancellationToken = default); Task<bool> AnyAsync(CancellationToken cancellationToken = default); Task<long> CountAsync(CancellationToken cancellationToken = default); #endif List<TOut> ToList(); TOut ToOne(); TOut First(); string ToSql(); bool Any(); long Count(); ISelectedQuery<TOut> Count(out long count); ISelectedQuery<TOut> Skip(int offset); ISelectedQuery<TOut> Offset(int offset); ISelectedQuery<TOut> Limit(int limit); ISelectedQuery<TOut> Take(int limit); ISelectedQuery<TOut> Page(int pageNumber, int pageSize); ISelectedQuery<TOut> Where(Expression<Func<TOut, bool>> exp); ISelectedQuery<TOut> WhereIf(bool condition, Expression<Func<TOut, bool>> exp); ISelectedQuery<TOut> OrderBy<TMember>(Expression<Func<TOut, TMember>> column); ISelectedQuery<TOut> OrderByIf<TMember>(bool condition, Expression<Func<TOut, TMember>> column, bool descending = false); ISelectedQuery<TOut> OrderByDescending<TMember>(Expression<Func<TOut, TMember>> column); } } namespace FreeSql.Internal.CommonProvider {
ISelectedQuery
csharp
dotnet__aspnetcore
src/Shared/test/testassets/MockHostTypes/ServiceProvider.cs
{ "start": 179, "end": 287 }
public class ____ : IServiceProvider { public object GetService(Type serviceType) => null; }
ServiceProvider
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.Core/MetadataControl/MetadataItem.cs
{ "start": 381, "end": 1260 }
public struct ____ { /// <summary> /// Gets or sets the label of the item. /// </summary> public string Label { get; set; } /// <summary> /// Gets or sets the automation name that will be set on the item. /// If not set, <see cref="Label"/> will be used. /// </summary> public string AccessibleLabel { get; set; } /// <summary> /// Gets or sets the command associated to the item. /// If null, the item will be displayed as a text field. /// If set, the item will be displayed as an hyperlink. /// </summary> public ICommand Command { get; set; } /// <summary> /// Gets or sets the parameter that will be provided to the <see cref="Command"/>. /// </summary> public object CommandParameter { get; set; } } }
MetadataItem
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/XamlIlTests.cs
{ "start": 527, "end": 6549 }
public class ____ : XamlTestBase { [Fact] public void Transitions_Should_Be_Properly_Parsed() { var parsed = (Grid)AvaloniaRuntimeXamlLoader.Parse(@" <Grid xmlns='https://github.com/avaloniaui' > <Grid.Transitions> <Transitions> <DoubleTransition Property='Opacity' Easing='CircularEaseIn' Duration='0:0:0.5' /> </Transitions> </Grid.Transitions> </Grid>"); Assert.Equal(1, parsed.Transitions.Count); Assert.Equal(Visual.OpacityProperty, parsed.Transitions[0].Property); } [Fact] public void Parser_Should_Override_Precompiled_Xaml() { var precompiled = new XamlIlClassWithPrecompiledXaml(); Assert.Equal(Brushes.Red, precompiled.Background); Assert.Equal(1, precompiled.Opacity); var loaded = (XamlIlClassWithPrecompiledXaml)AvaloniaRuntimeXamlLoader.Parse(@" <UserControl xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Class='Avalonia.Markup.Xaml.UnitTests.XamlIlClassWithPrecompiledXaml' Opacity='0'> </UserControl>"); Assert.Equal(loaded.Opacity, 0); Assert.Null(loaded.Background); } [Fact] public void RelativeSource_TemplatedParent_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { AvaloniaRuntimeXamlLoader.Load(@" <Application xmlns='https://github.com/avaloniaui' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests' > <Application.Styles> <Style Selector='Button'> <Setter Property='Template'> <ControlTemplate> <Grid><Grid><Grid> <Canvas> <Canvas.Background> <SolidColorBrush> <SolidColorBrush.Color> <MultiBinding> <MultiBinding.Converter> <local:XamlIlBugTestsBrushToColorConverter/> </MultiBinding.Converter> <Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/> <Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/> <Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/> </MultiBinding> </SolidColorBrush.Color> </SolidColorBrush> </Canvas.Background> </Canvas> </Grid></Grid></Grid> </ControlTemplate> </Setter> </Style> </Application.Styles> </Application>", null, Application.Current); var parsed = (Window)AvaloniaRuntimeXamlLoader.Parse(@" <Window xmlns='https://github.com/avaloniaui' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests' > <Button Background='Red' /> </Window> "); var btn = ((Button)parsed.Content); btn.ApplyTemplate(); var canvas = (Canvas)btn.GetVisualChildren().First() .VisualChildren.First() .VisualChildren.First() .VisualChildren.First(); Assert.Equal(Brushes.Red.Color, ((ISolidColorBrush)canvas.Background).Color); } } [Fact] public void Event_Handlers_Should_Work_For_Templates() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var w =new XamlIlBugTestsEventHandlerCodeBehind(); w.ApplyTemplate(); w.Show(); Dispatcher.UIThread.RunJobs(); var itemsPresenter = ((ItemsControl)w.Content).GetVisualChildren().FirstOrDefault(); var item = itemsPresenter .GetVisualChildren().First() .GetVisualChildren().First() .GetVisualChildren().First(); ((Control)item).DataContext = "test"; Assert.Equal("test", w.SavedContext); } } [Fact] public void Custom_Properties_Should_Work_With_XClass() { var precompiled = new XamlIlClassWithCustomProperty(); Assert.Equal("123", precompiled.Test); var loaded = (XamlIlClassWithCustomProperty)AvaloniaRuntimeXamlLoader.Parse(@" <UserControl xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Class='Avalonia.Markup.Xaml.UnitTests.XamlIlClassWithCustomProperty' Test='321'> </UserControl>"); Assert.Equal("321", loaded.Test); } static void AssertThrows(Action callback, Func<Exception, bool> check) { try { callback(); } catch (Exception e) when (check(e)) { return; } throw new Exception("Expected exception was not thrown"); } public static object SomeStaticProperty { get; set; } [Fact] public void Bug2570() { SomeStaticProperty = "123"; AssertThrows(() => AvaloniaRuntimeXamlLoader .Load(@" <UserControl xmlns='https://github.com/avaloniaui' xmlns:d='http://schemas.microsoft.com/expression/blend/2008' xmlns:tests='clr-namespace:Avalonia.Markup.Xaml.UnitTests' d:DataContext='{x:Static tests:XamlIlTests.SomeStaticPropery}' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'/>", typeof(XamlIlTests).Assembly, designMode: true), e => e.Message.Contains("Unable to resolve ") && e.Message.Contains(" as static field, property, constant or
XamlIlTests
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.MediaProperties/ImageEncodingProperties.cs
{ "start": 304, "end": 9647 }
public partial class ____ : global::Windows.Media.MediaProperties.IMediaEncodingProperties { #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 uint Width { get { throw new global::System.NotImplementedException("The member uint ImageEncodingProperties.Width is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=uint%20ImageEncodingProperties.Width"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.ImageEncodingProperties", "uint ImageEncodingProperties.Width"); } } #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 uint Height { get { throw new global::System.NotImplementedException("The member uint ImageEncodingProperties.Height is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=uint%20ImageEncodingProperties.Height"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.ImageEncodingProperties", "uint ImageEncodingProperties.Height"); } } #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 Subtype { get { throw new global::System.NotImplementedException("The member string ImageEncodingProperties.Subtype is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20ImageEncodingProperties.Subtype"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.ImageEncodingProperties", "string ImageEncodingProperties.Subtype"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Media.MediaProperties.MediaPropertySet Properties { get { throw new global::System.NotImplementedException("The member MediaPropertySet ImageEncodingProperties.Properties is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=MediaPropertySet%20ImageEncodingProperties.Properties"); } } #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 Type { get { throw new global::System.NotImplementedException("The member string ImageEncodingProperties.Type is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20ImageEncodingProperties.Type"); } } #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 ImageEncodingProperties() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.ImageEncodingProperties", "ImageEncodingProperties.ImageEncodingProperties()"); } #endif // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.ImageEncodingProperties() // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Width.set // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Width.get // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Height.set // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Height.get // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Properties.get // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Type.get // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Subtype.set // Forced skipping of method Windows.Media.MediaProperties.ImageEncodingProperties.Subtype.get #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Media.MediaProperties.ImageEncodingProperties Copy() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.Copy() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.Copy%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreateHeif() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreateHeif() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreateHeif%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreateUncompressed(global::Windows.Media.MediaProperties.MediaPixelFormat format) { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreateUncompressed(MediaPixelFormat format) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreateUncompressed%28MediaPixelFormat%20format%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreateBmp() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreateBmp() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreateBmp%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreateJpeg() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreateJpeg() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreateJpeg%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreatePng() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreatePng() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreatePng%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Media.MediaProperties.ImageEncodingProperties CreateJpegXR() { throw new global::System.NotImplementedException("The member ImageEncodingProperties ImageEncodingProperties.CreateJpegXR() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ImageEncodingProperties%20ImageEncodingProperties.CreateJpegXR%28%29"); } #endif // Processing: Windows.Media.MediaProperties.IMediaEncodingProperties } }
ImageEncodingProperties
csharp
dotnet__reactive
Ix.NET/Source/System.Linq.Async.Queryable.Tests/AsyncEnumerableQueryTest.cs
{ "start": 260, "end": 828 }
public class ____ { [Fact] public void CastToUntypedIAsyncQueryable() { var query = Enumerable.Empty<string>().ToAsyncEnumerable().AsAsyncQueryable(); Assert.IsAssignableFrom<IAsyncQueryable>(query); } [Fact] public void CastToUntypedIOrderedAsyncQueryable() { var query = Enumerable.Empty<string>().ToAsyncEnumerable().AsAsyncQueryable().OrderBy(s => s.Length); Assert.IsAssignableFrom<IOrderedAsyncQueryable>(query); } } }
AsyncEnumerableQueryTest
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/Mappings/ConstructorParameter/DateTimeStylesMapTests.cs
{ "start": 4132, "end": 4337 }
private class ____ { public int Id { get; private set; } public DateTimeOffset Date { get; private set; } public Foo(int id, DateTimeOffset date) { Id = id; Date = date; } }
Foo
csharp
PrismLibrary__Prism
src/Prism.Core/Dialogs/DialogUtilities.cs
{ "start": 286, "end": 2535 }
public static class ____ { /// <summary> /// Initializes <see cref="IDialogAware.RequestClose"/> /// </summary> /// <param name="dialogAware"></param> /// <param name="callback"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static void InitializeListener(IDialogAware dialogAware, Func<IDialogResult, Task> callback) { var listener = new DialogCloseListener(callback); SetListener(dialogAware, listener); } /// <summary> /// Initializes <see cref="IDialogAware.RequestClose"/> /// </summary> /// <param name="dialogAware"></param> /// <param name="callback"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static void InitializeListener(IDialogAware dialogAware, Action<IDialogResult> callback) { var listener = new DialogCloseListener(callback); SetListener(dialogAware, listener); } private static void SetListener(IDialogAware dialogAware, DialogCloseListener listener) { var setter = GetListenerSetter(dialogAware, dialogAware.GetType()); setter(listener); } private static Action<DialogCloseListener> GetListenerSetter(IDialogAware dialogAware, Type type) { var propInfo = type.GetProperty(nameof(IDialogAware.RequestClose)); if (propInfo is not null && propInfo.PropertyType == typeof(DialogCloseListener) && propInfo.SetMethod is not null) { return x => propInfo.SetValue(dialogAware, x); } var fields = type.GetRuntimeFields().Where(x => x.FieldType == typeof(DialogCloseListener)); var field = fields.FirstOrDefault(x => x.Name == $"<{nameof(IDialogAware.RequestClose)}>k__BackingField"); if (field is not null) { return x => field.SetValue(dialogAware, x); } else if (fields.Any()) { field = fields.First(); return x => field.SetValue(dialogAware, x); } var baseType = type.BaseType; if (baseType is null || baseType == typeof(object)) throw new DialogException(DialogException.UnableToSetTheDialogCloseListener); return GetListenerSetter(dialogAware, baseType); } }
DialogUtilities
csharp
EventStore__EventStore
src/KurrentDB.Core.XUnit.Tests/Scavenge/ScavengeOptionsCalculatorTests.cs
{ "start": 611, "end": 2337 }
public class ____ { private const string SectionName = KurrentConfigurationKeys.Prefix; private static ScavengeOptionsCalculator GenSut( KeyValuePair<string, string?>[]? vNodeOptions = null, int? threshold = null) { vNodeOptions ??= []; var message = new ClientMessage.ScavengeDatabase( envelope: IEnvelope.NoOp, correlationId: Guid.NewGuid(), user: SystemAccounts.Anonymous, startFromChunk: 0, threads: 1, threshold: threshold, throttlePercent: 100, syncOnly: false); var config = new ConfigurationBuilder().AddInMemoryCollection( vNodeOptions.Append(new($"{SectionName}:ClusterSize", "1"))) .Build(); var options = ClusterVNodeOptions.FromConfiguration(config); var archiveOptions = config.GetSection($"{SectionName}:Archive").Get<ArchiveOptions>() ?? new(); var sut = new ScavengeOptionsCalculator(options, archiveOptions, message); return sut; } [Fact] public void merging_enabled_by_default() { var sut = GenSut([ ]); Assert.True(sut.MergeChunks); } [Fact] public void merging_can_be_disabled() { var sut = GenSut([ new($"{SectionName}:DisableScavengeMerging", "true"), ]); Assert.False(sut.MergeChunks); } [Fact] public void merging_is_disabled_when_archiving_is_enabled() { var sut = GenSut( vNodeOptions: [ new($"{SectionName}:Archive:Enabled", "true"), ]); Assert.False(sut.MergeChunks); } [Theory] [InlineData(null, 0)] [InlineData(-5, -5)] [InlineData(0, 0)] [InlineData(5, 5)] public void threshold_can_be_set(int? configuredThreshold, int expectedThreshold) { var sut = GenSut(threshold: configuredThreshold); Assert.Equal(expectedThreshold, sut.ChunkExecutionThreshold); } }
ScavengeOptionsCalculatorTests
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/Models/ListViewGroupedViewModel.cs
{ "start": 355, "end": 5254 }
internal class ____ : ViewModelBase { Random _rnd = null; private bool _areStickyHeadersEnabled; private double _variableWidth; public IEnumerable<IGrouping<string, string>> GroupedSampleItems { get; } public IEnumerable<object> GroupedSampleItemsAsSource { get; } public IEnumerable<IGrouping<int, int>> GroupedNumericItems { get; } public IEnumerable<object> GroupedNumericItemsAsSource { get; } public string[] UngroupedSampleItems { get; } public bool AreStickyHeadersEnabled { get => _areStickyHeadersEnabled; set { _areStickyHeadersEnabled = value; RaisePropertyChanged(); } } public IEnumerable<object> GroupedTownsAsSource { get; } public IEnumerable<object> EmptyGroupsAsSource { get; } public IEnumerable<object> EmptyAsSource { get; } public double VariableWidth { get => _variableWidth; set { _variableWidth = value; RaisePropertyChanged(); } } public ListViewGroupedViewModel(Private.Infrastructure.UnitTestDispatcherCompat dispatcher) : base(dispatcher) { _rnd = new Random(); GroupedSampleItems = GetGroupedSampleItems(); GroupedSampleItemsAsSource = ListViewViewModel.GetAsCollectionViewSource(GetGroupedSampleItems()); GroupedNumericItems = GetGroupedNumericItems(); GroupedNumericItemsAsSource = ListViewViewModel.GetAsCollectionViewSource(GetGroupedNumericItems()); //TODO: Restore dynamic samples based on IObservable //.Attach("ChangingGroupedSampleItems", () => GetChangingGroupedSampleItems()) //.Attach("ChangingGroupedSampleItemsAsSource", // () => GetChangingGroupedSampleItems() // .SelectMany(s => // GetAsCollectionViewSource(CancellationToken.None, s).ToObservable() // ) //) UngroupedSampleItems = _sampleItems; //.Attach("ChangingIntArray", () => GetChangingIntArray()) AreStickyHeadersEnabled = true; GroupedTownsAsSource = ListViewViewModel.GetAsCollectionViewSource(GetTownsGroupedAlphabetically()); EmptyGroupsAsSource = ListViewViewModel.GetAsCollectionViewSource(GetAllEmptyGroups()); EmptyAsSource = ListViewViewModel.GetAsCollectionViewSource(Enumerable.Empty<IGrouping<string, string>>()); VariableWidth = 500d; // ) //); } /// <summary> /// Group by first character /// </summary> /// <returns></returns> private IEnumerable<IGrouping<string, string>> GetGroupedSampleItems() { return _sampleItems .GroupBy(s => s[0].ToString().ToUpperInvariant()) .Concat(new EmptyGroup<string, string>("This header should not appear if GroupStyle.HidesEmptyGroups is true)")); } private IEnumerable<IGrouping<int, int>> GetGroupedNumericItems() { return _sampleNumbers .GroupBy(i => GetFirstDigit(i)) .OrderBy(g => g.Key) .Concat(new EmptyGroup<int, int>(1111111111)); //Should not appear if GroupStyle.HidesEmptyGroups is true } private int GetFirstDigit(int number) { number = Math.Abs(number); while (number >= 10) { number /= 10; } return number; } /// <summary> /// Group by Random character at interval /// </summary> /// <returns></returns> private IObservable<IEnumerable<IGrouping<string, string>>> GetChangingGroupedSampleItems() { throw new NotImplementedException(); //return Observable.Interval(TimeSpan.FromSeconds(3), Schedulers.Default) // .Select((i) => // { // var stringIndex = _rnd.Next(0, 9); // var itemsToGroup = _rnd.Next(_sampleItems.Length / 2, _sampleItems.Length); // return _sampleItems // .Take(itemsToGroup) // .Select(s => s.Substring(startIndex: stringIndex) + s.Substring(startIndex: 0, length: stringIndex)) // .GroupBy(s => s[0].ToString()) // .Concat(new EmptyGroup<string, string>("This header should not appear if GroupStyle.HidesEmptyGroups is true)")) // .ToArray(); // } // ); } private IObservable<long[]> GetChangingIntArray() { throw new NotImplementedException(); //var baseArray = new[] { 1, 2, 3, 4 }; //return Observable.Interval(TimeSpan.FromSeconds(1), Schedulers.Default) // .Select(i => baseArray.Select(n => (i + 1) * n).ToArray()); } private static IEnumerable<IGrouping<string, string>> GetTownsGroupedAlphabetically() { return Enumerable.Range(1, 2) .Select(x => new EmptyGroup<string, string>(x.ToString())) .Concat( // left join from letter in _alphabet join g in SampleTowns.GroupBy(x => x.Substring(0, 1)) on letter equals g.Key into groupedTowns select groupedTowns.FirstOrDefault() ?? new EmptyGroup<string, string>(letter) ) .ToList(); } private static IEnumerable<IGrouping<string, string>> GetAllEmptyGroups() { return "Blarg".Select(c => new EmptyGroup<string, string>(c.ToString())).ToArray(); } public double[] WidthChoices { get; } = Enumerable.Range(1, 5).Select(i => i * 100d).ToArray();
ListViewGroupedViewModel
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/IProducerEventCountingGrain.cs
{ "start": 210, "end": 603 }
public interface ____ : IGrainWithGuidKey { Task BecomeProducer(Guid streamId, string providerToUse); /// <summary> /// Sends a single event and, upon successful completion, updates the number of events produced. /// </summary> /// <returns></returns> Task SendEvent(); Task<int> GetNumberProduced(); } }
IProducerEventCountingGrain
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs
{ "start": 692, "end": 1493 }
public class ____ : Attribute { private string _id; private string _name; private string _category = ""; private string[] _dependencies = []; /// <summary> /// Gets the default list delimiters used for parsing dependency strings. /// Supported delimiters are semicolon (;), comma (,), and space ( ). /// </summary> /// <remarks> /// Semicolon delimiters are most common from a CSPROJ perspective. /// </remarks> protected internal static readonly char[] ListDelimiters = [';', ',', ' ']; /// <summary> /// Initializes a new instance of the <see cref="FeatureAttribute"/> class. /// </summary> public FeatureAttribute() { } /// <summary> /// Initializes a new instance of the <see cref="FeatureAttribute"/>
FeatureAttribute
csharp
microsoft__semantic-kernel
dotnet/samples/Concepts/Plugins/CopilotAgentBasedPlugins.cs
{ "start": 2052, "end": 13108 }
public class ____(ITestOutputHelper output) : BaseTest(output) { private static readonly PromptExecutionSettings s_promptExecutionSettings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto( options: new FunctionChoiceBehaviorOptions { AllowStrictSchemaAdherence = true } ) }; public static readonly IEnumerable<object[]> s_parameters = [ // function names are sanitized operationIds from the OpenAPI document ["MessagesPlugin", "me_ListMessages", new KernelArguments(s_promptExecutionSettings) { { "_top", "1" } }, "MessagesPlugin"], ["DriveItemPlugin", "drives_GetItemsContent", new KernelArguments(s_promptExecutionSettings) { { "driveItem-Id", "test.txt" } }, "DriveItemPlugin", "MessagesPlugin"], ["ContactsPlugin", "me_ListContacts", new KernelArguments(s_promptExecutionSettings) { { "_count", "true" } }, "ContactsPlugin", "MessagesPlugin"], ["CalendarPlugin", "me_calendar_ListEvents", new KernelArguments(s_promptExecutionSettings) { { "_top", "1" } }, "CalendarPlugin", "MessagesPlugin"], // Multiple API dependencies (multiple auth requirements) scenario within the same plugin // Graph API uses MSAL ["AstronomyPlugin", "me_ListMessages", new KernelArguments(s_promptExecutionSettings) { { "_top", "1" } }, "AstronomyPlugin"], // Astronomy API uses API key authentication ["AstronomyPlugin", "apod", new KernelArguments(s_promptExecutionSettings) { { "_date", "2022-02-02" } }, "AstronomyPlugin"], ]; [Theory, MemberData(nameof(s_parameters))] public async Task RunCopilotAgentPluginAsync(string pluginToTest, string functionToTest, KernelArguments? arguments, params string[] pluginsToLoad) { WriteSampleHeadingToConsole(pluginToTest, functionToTest, arguments, pluginsToLoad); var kernel = new Kernel(); await AddCopilotAgentPluginsAsync(kernel, pluginsToLoad); var result = await kernel.InvokeAsync(pluginToTest, functionToTest, arguments); Console.WriteLine("--------------------"); Console.WriteLine($"\nResult:\n{result}\n"); Console.WriteLine("--------------------"); } private void WriteSampleHeadingToConsole(string pluginToTest, string functionToTest, KernelArguments? arguments, params string[] pluginsToLoad) { Console.WriteLine(); Console.WriteLine("======== [CopilotAgent Plugins Sample] ========"); Console.WriteLine($"======== Loading Plugins: {string.Join(" ", pluginsToLoad)} ========"); Console.WriteLine($"======== Calling Plugin Function: {pluginToTest}.{functionToTest} with parameters {arguments?.Select(x => x.Key + " = " + x.Value).Aggregate((x, y) => x + ", " + y)} ========"); Console.WriteLine(); } private static readonly HashSet<string> s_fieldsToIgnore = new( [ "@odata.type", "attachments", "allowNewTimeProposals", "bccRecipients", "bodyPreview", "calendar", "categories", "ccRecipients", "changeKey", "conversationId", "coordinates", "conversationIndex", "createdDateTime", "discriminator", "lastModifiedDateTime", "locations", "extensions", "flag", "from", "hasAttachments", "iCalUId", "id", "inferenceClassification", "internetMessageHeaders", "instances", "isCancelled", "isDeliveryReceiptRequested", "isDraft", "isOrganizer", "isRead", "isReadReceiptRequested", "multiValueExtendedProperties", "onlineMeeting", "onlineMeetingProvider", "onlineMeetingUrl", "organizer", "originalStart", "parentFolderId", "range", "receivedDateTime", "recurrence", "replyTo", "sender", "sentDateTime", "seriesMasterId", "singleValueExtendedProperties", "transactionId", "time", "uniqueBody", "uniqueId", "uniqueIdType", "webLink", ], StringComparer.OrdinalIgnoreCase ); private const string RequiredPropertyName = "required"; private const string PropertiesPropertyName = "properties"; /// <summary> /// Trims the properties from the request body schema. /// Most models in strict mode enforce a limit on the properties. /// </summary> /// <param name="schema">Source schema</param> /// <returns>the trimmed schema for the request body</returns> private static KernelJsonSchema? TrimPropertiesFromRequestBody(KernelJsonSchema? schema) { if (schema is null) { return null; } var originalSchema = JsonSerializer.Serialize(schema.RootElement); var node = JsonNode.Parse(originalSchema); if (node is not JsonObject jsonNode) { return schema; } TrimPropertiesFromJsonNode(jsonNode); return KernelJsonSchema.Parse(node.ToString()); } private static void TrimPropertiesFromJsonNode(JsonNode jsonNode) { if (jsonNode is not JsonObject jsonObject) { return; } if (jsonObject.TryGetPropertyValue(RequiredPropertyName, out var requiredRawValue) && requiredRawValue is JsonArray requiredArray) { jsonNode[RequiredPropertyName] = new JsonArray(requiredArray.Where(x => x is not null).Select(x => x!.GetValue<string>()).Where(x => !s_fieldsToIgnore.Contains(x)).Select(x => JsonValue.Create(x)).ToArray()); } if (jsonObject.TryGetPropertyValue(PropertiesPropertyName, out var propertiesRawValue) && propertiesRawValue is JsonObject propertiesObject) { var properties = propertiesObject.Where(x => s_fieldsToIgnore.Contains(x.Key)).Select(static x => x.Key).ToArray(); foreach (var property in properties) { propertiesObject.Remove(property); } } foreach (var subProperty in jsonObject) { if (subProperty.Value is not null) { TrimPropertiesFromJsonNode(subProperty.Value); } } } private static readonly RestApiParameterFilter s_restApiParameterFilter = (RestApiParameterFilterContext context) => { if (("me_sendMail".Equals(context.Operation.Id, StringComparison.OrdinalIgnoreCase) || ("me_calendar_CreateEvents".Equals(context.Operation.Id, StringComparison.OrdinalIgnoreCase)) && "payload".Equals(context.Parameter.Name, StringComparison.OrdinalIgnoreCase))) { context.Parameter.Schema = TrimPropertiesFromRequestBody(context.Parameter.Schema); return context.Parameter; } return context.Parameter; }; internal static async Task<CopilotAgentPluginParameters> GetAuthenticationParametersAsync() { if (TestConfiguration.MSGraph.Scopes is null) { throw new InvalidOperationException("Missing Scopes configuration for Microsoft Graph API."); } LocalUserMSALCredentialManager credentialManager = await LocalUserMSALCredentialManager.CreateAsync().ConfigureAwait(false); var token = await credentialManager.GetTokenAsync( TestConfiguration.MSGraph.ClientId, TestConfiguration.MSGraph.TenantId, TestConfiguration.MSGraph.Scopes.ToArray(), TestConfiguration.MSGraph.RedirectUri).ConfigureAwait(false); #pragma warning restore SKEXP0050 BearerAuthenticationProviderWithCancellationToken authenticationProvider = new(() => Task.FromResult(token)); #pragma warning disable SKEXP0040 // Microsoft Graph API execution parameters var graphOpenApiFunctionExecutionParameters = new OpenApiFunctionExecutionParameters( authCallback: authenticationProvider.AuthenticateRequestAsync, serverUrlOverride: new Uri("https://graph.microsoft.com/v1.0"), enableDynamicOperationPayload: false, enablePayloadNamespacing: false) { ParameterFilter = s_restApiParameterFilter }; // NASA API execution parameters var nasaOpenApiFunctionExecutionParameters = new OpenApiFunctionExecutionParameters( authCallback: async (request, cancellationToken) => { var uriBuilder = new UriBuilder(request.RequestUri ?? throw new InvalidOperationException("The request URI is null.")); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query["api_key"] = "DEMO_KEY"; uriBuilder.Query = query.ToString(); request.RequestUri = uriBuilder.Uri; }, enableDynamicOperationPayload: false, enablePayloadNamespacing: false); var apiManifestPluginParameters = new CopilotAgentPluginParameters { FunctionExecutionParameters = new() { { "https://graph.microsoft.com/v1.0", graphOpenApiFunctionExecutionParameters }, { "https://api.nasa.gov/planetary", nasaOpenApiFunctionExecutionParameters } } }; return apiManifestPluginParameters; } private async Task AddCopilotAgentPluginsAsync(Kernel kernel, params string[] pluginNames) { #pragma warning disable SKEXP0050 var apiManifestPluginParameters = await GetAuthenticationParametersAsync().ConfigureAwait(false); var manifestLookupDirectory = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "Resources", "Plugins", "CopilotAgentPlugins"); foreach (var pluginName in pluginNames) { try { #pragma warning disable CA1308 // Normalize strings to uppercase await kernel.ImportPluginFromCopilotAgentPluginAsync( pluginName, Path.Combine(manifestLookupDirectory, pluginName, $"{pluginName[..^6].ToLowerInvariant()}-apiplugin.json"), apiManifestPluginParameters) .ConfigureAwait(false); #pragma warning restore CA1308 // Normalize strings to uppercase Console.WriteLine($">> {pluginName} is created."); #pragma warning restore SKEXP0040 } catch (Exception ex) { Console.WriteLine("Plugin creation failed. Message: {0}", ex.Message); throw new AggregateException($"Plugin creation failed for {pluginName}", ex); } } } }
CopilotAgentBasedPlugins
csharp
dotnet__aspnetcore
src/Identity/UI/src/Areas/Identity/Pages/V4/Account/ExternalLogin.cshtml.cs
{ "start": 2351, "end": 4322 }
public class ____ { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [EmailAddress] public string Email { get; set; } = default!; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IActionResult OnGet() => throw new NotImplementedException(); /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IActionResult OnPost(string provider, [StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null) => throw new NotImplementedException(); /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Task<IActionResult> OnGetCallbackAsync([StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null, string? remoteError = null) => throw new NotImplementedException(); /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Task<IActionResult> OnPostConfirmationAsync([StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null) => throw new NotImplementedException(); }
InputModel
csharp
dotnet__aspnetcore
src/SignalR/server/Core/src/Internal/NonInvokingSingleClientProxy.cs
{ "start": 188, "end": 953 }
internal sealed class ____ : ISingleClientProxy { private readonly IClientProxy _clientProxy; private readonly string _memberName; public NonInvokingSingleClientProxy(IClientProxy clientProxy, string memberName) { _clientProxy = clientProxy; _memberName = memberName; } public Task SendCoreAsync(string method, object?[] args, CancellationToken cancellationToken = default) => _clientProxy.SendCoreAsync(method, args, cancellationToken); public Task<T> InvokeCoreAsync<T>(string method, object?[] args, CancellationToken cancellationToken = default) => throw new NotImplementedException($"The default implementation of {_memberName} does not support client return results."); }
NonInvokingSingleClientProxy
csharp
EventStore__EventStore
src/KurrentDB.Core.XUnit.Tests/Scavenge/Infrastructure/MockScavengePointSource.cs
{ "start": 918, "end": 1461 }
public class ____ : IScavengePointSource { private readonly ILogRecord[][] _log; private readonly DateTime _effectiveNow; private readonly List<ScavengePoint> _added; public MockScavengePointSource( DbResult dbResult, DateTime effectiveNow, List<ScavengePoint> added) { _log = dbResult.Recs; _effectiveNow = effectiveNow; _added = added; } public Task<ScavengePoint> GetLatestScavengePointOrDefaultAsync( CancellationToken cancellationToken) { ScavengePoint scavengePoint = default; foreach (var
MockScavengePointSource
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.MySql.Tests/OrmLiteComplexTypesTests.cs
{ "start": 184, "end": 1328 }
public class ____ : OrmLiteTestBase { public OrmLiteComplexTypesTests() { LogManager.LogFactory = new ConsoleLogFactory(); } [Test] public void Can_insert_into_ModelWithComplexTypes_table() { using var db = OpenDbConnection(); db.CreateTable<ModelWithComplexTypes>(true); var row = ModelWithComplexTypes.Create(1); db.Insert(row); } [Test] public void Can_insert_and_select_from_ModelWithComplexTypes_table() { using var db = OpenDbConnection(); db.CreateTable<ModelWithComplexTypes>(true); var row = ModelWithComplexTypes.Create(1); db.Insert(row); var rows = db.Select<ModelWithComplexTypes>(); Assert.That(rows, Has.Count.EqualTo(1)); ModelWithComplexTypes.AssertIsEqual(rows[0], row); } [Test] public void Can_insert_and_select_from_OrderLineData() { using var db = OpenDbConnection(); db.CreateTable<SampleOrderLine>(true); var orderIds = new[] { 1, 2, 3, 4, 5 }.ToList(); orderIds.ForEach(x => db.Insert( SampleOrderLine.Create(Guid.NewGuid(), x, 1))); var rows = db.Select<SampleOrderLine>(); Assert.That(rows, Has.Count.EqualTo(orderIds.Count)); } }
OrmLiteComplexTypesTests
csharp
HangfireIO__Hangfire
tests/Hangfire.Core.Tests/Utils/DataCompatibilityRangeTheoryAttribute.cs
{ "start": 243, "end": 705 }
internal sealed class ____ : TheoryAttribute { public DataCompatibilityRangeTheoryAttribute() { MinLevel = DataCompatibilityRangeFactAttribute.PossibleMinLevel; MaxExcludingLevel = DataCompatibilityRangeFactAttribute.PossibleMaxExcludingLevel; } public CompatibilityLevel MinLevel { get; set; } public CompatibilityLevel MaxExcludingLevel { get; set; } } }
DataCompatibilityRangeTheoryAttribute
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui/Converters/VariableMultiValueConverter.shared.cs
{ "start": 242, "end": 1350 }
public enum ____ { /// <summary>None of the values should be true.</summary> None, /// <summary>All the values should be true.</summary> All, /// <summary>Any of the values should be true.</summary> Any, /// <summary>The exact number as configured in <see cref="Converters.VariableMultiValueConverter.Count"/> should be true.</summary> Exact, /// <summary>At least the number as configured in <see cref="Converters.VariableMultiValueConverter.Count"/> should be true.</summary> GreaterThan, /// <summary>At most the number as configured in <see cref="Converters.VariableMultiValueConverter.Count"/> should be true.</summary> LessThan } /// <summary> /// The <see cref="VariableMultiValueConverter"/> is a converter that allows users to convert multiple <see cref="bool"/> value bindings to a single <see cref="bool"/>. It does this by enabling them to specify whether All, Any, None or a specific number of values are true as specified in <see cref="ConditionType"/>. This is useful when combined with the <see cref="MultiBinding"/>. /// </summary> [AcceptEmptyServiceProvider]
MultiBindingCondition
csharp
files-community__Files
src/Files.App/Data/Items/TagsListItem.cs
{ "start": 371, "end": 520 }
public sealed class ____ : TagsListItem { public TagViewModel Tag { get; set; } public TagItem(TagViewModel tag) { Tag = tag; } }
TagItem
csharp
EventStore__EventStore
src/KurrentDB.AutoScavenge/Domain/AutoScavengeStatusResponse.cs
{ "start": 388, "end": 477 }
public enum ____ { NotConfigured, Waiting, InProgress, Pausing, Paused, } }
Status
csharp
dotnet__aspnetcore
src/Components/Components/src/PersistentState/PersistComponentStateRegistration.cs
{ "start": 199, "end": 429 }
struct ____( Func<Task> callback, IComponentRenderMode? renderMode) { public Func<Task> Callback { get; } = callback; public IComponentRenderMode? RenderMode { get; } = renderMode; }
PersistComponentStateRegistration
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui.Core/Handlers/SemanticOrderView/SemanticOrderViewHandler.macios.cs
{ "start": 121, "end": 274 }
public partial class ____ { /// <inheritdoc/> protected override ContentView CreatePlatformView() => new MauiSemanticOrderView(); }
SemanticOrderViewHandler
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Administration/Domain/MeetingGroupProposals/IMeetingGroupProposalRepository.cs
{ "start": 92, "end": 317 }
public interface ____ { Task AddAsync(MeetingGroupProposal meetingGroupProposal); Task<MeetingGroupProposal> GetByIdAsync(MeetingGroupProposalId meetingGroupProposalId); } }
IMeetingGroupProposalRepository
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/SystemJsonAttribute.cs
{ "start": 300, "end": 430 }
public class ____(UseSystemJson use) : AttributeBase { public UseSystemJson Use { get; set; } = use; } #endif
SystemJsonAttribute
csharp
nuke-build__nuke
source/Nuke.Build/Execution/Extensions/InjectNonParameterValuesAttribute.cs
{ "start": 333, "end": 1345 }
internal class ____ : BuildExtensionAttributeBase, IOnBuildInitialized { public void OnBuildInitialized( IReadOnlyCollection<ExecutableTarget> executableTargets, IReadOnlyCollection<ExecutableTarget> executionPlan) { ValueInjectionUtility.InjectValues(Build, (member, attribute) => { if (attribute.GetType() == typeof(ParameterAttribute)) return false; if (!Build.GetType().HasCustomAttribute<OnDemandValueInjectionAttribute>() && !member.HasCustomAttribute<OnDemandAttribute>()) return true; if (member.HasCustomAttribute<RequiredAttribute>()) return false; var requiredMembers = executionPlan.SelectMany(x => x.DelegateRequirements) .Where(x => x is not Expression<Func<bool>>) .Select(x => x.GetMemberInfo()).ToList(); return requiredMembers.Contains(member); }); } }
InjectNonParameterValuesAttribute
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Bugzilla/Bugzilla41271.cs
{ "start": 577, "end": 1320 }
class ____ : ViewCell { Label firstNameLabel = new Label(); Label lastNameLabel = new Label(); Label cityLabel = new Label(); Label stateLabel = new Label(); public ListViewCell() { View = new StackLayout { Orientation = StackOrientation.Horizontal, Children = { firstNameLabel, lastNameLabel, cityLabel, stateLabel } }; } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); var item = BindingContext as Person; if (item != null) { firstNameLabel.Text = item.FirstName; lastNameLabel.Text = item.LastName; cityLabel.Text = item.City; stateLabel.Text = item.State; AutomationId = item.State; } } }
ListViewCell
csharp
duplicati__duplicati
Duplicati/Library/Utility/EnumerableExtensions.cs
{ "start": 1368, "end": 2761 }
public static class ____ { /// <summary> /// Filters a sequence of values to exclude null elements. /// </summary> /// <param name="source">The sequence to filter.</param> /// <returns>A sequence that contains only the non-null elements from the input sequence.</returns> public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) => source.Where(x => x != null) .Select(x => x!); /// <summary> /// Filters a sequence of values to exclude null elements. /// </summary> /// <param name="source">The sequence to filter.</param> /// <returns>A sequence that contains only the non-null elements from the input sequence.</returns> public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : struct => source.Where(x => x != null) .Select(x => x!.Value); /// <summary> /// Filters a sequence of values to exclude null or whitespace elements. /// </summary> /// <param name="source">The sequence to filter.</param> /// <returns>A sequence that contains only the non-null and non-whitespace elements from the input sequence.</returns> public static IEnumerable<string> WhereNotNullOrWhiteSpace(this IEnumerable<string?> source) => source.Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => x!); }
EnumerableExtensions
csharp
dotnet__maui
src/Controls/src/Xaml/MarkupExtensions/BindingExtension.cs
{ "start": 277, "end": 2563 }
public sealed class ____ : IMarkupExtension<BindingBase> { public string Path { get; set; } = Binding.SelfPath; public BindingMode Mode { get; set; } = BindingMode.Default; public IValueConverter Converter { get; set; } public object ConverterParameter { get; set; } public string StringFormat { get; set; } public object Source { get; set; } public string UpdateSourceEventName { get; set; } public object TargetNullValue { get; set; } public object FallbackValue { get; set; } [EditorBrowsable(EditorBrowsableState.Never)] public TypedBindingBase TypedBinding { get; set; } BindingBase IMarkupExtension<BindingBase>.ProvideValue(IServiceProvider serviceProvider) { if (TypedBinding is null) { return CreateBinding(); } TypedBinding.Mode = Mode; TypedBinding.Converter = Converter; TypedBinding.ConverterParameter = ConverterParameter; TypedBinding.StringFormat = StringFormat; TypedBinding.Source = Source; TypedBinding.UpdateSourceEventName = UpdateSourceEventName; TypedBinding.FallbackValue = FallbackValue; TypedBinding.TargetNullValue = TargetNullValue; return TypedBinding; [UnconditionalSuppressMessage("TrimAnalysis", "IL2026", Justification = "If this method is invoked, we have already produced warnings in XamlC " + "when the compilation of this binding failed or was skipped.")] BindingBase CreateBinding() { Type bindingXDataType = null; if (serviceProvider is not null && (serviceProvider.GetService(typeof(IXamlTypeResolver)) is IXamlTypeResolver typeResolver) && (serviceProvider.GetService(typeof(IXamlDataTypeProvider)) is IXamlDataTypeProvider dataTypeProvider) && dataTypeProvider.BindingDataType != null) { typeResolver.TryResolve(dataTypeProvider.BindingDataType, out bindingXDataType); } return new Binding(Path, Mode, Converter, ConverterParameter, StringFormat, Source) { UpdateSourceEventName = UpdateSourceEventName, FallbackValue = FallbackValue, TargetNullValue = TargetNullValue, DataType = bindingXDataType, }; } } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<BindingBase>).ProvideValue(serviceProvider); } } }
BindingExtension
csharp
dotnet__aspnetcore
src/Http/Headers/test/HeaderUtilitiesTest.cs
{ "start": 245, "end": 15905 }
public class ____ { private const string Rfc1123Format = "r"; [Theory] [MemberData(nameof(TestValues))] public void ReturnsSameResultAsRfc1123String(DateTimeOffset dateTime, bool quoted) { var formatted = dateTime.ToString(Rfc1123Format); var expected = quoted ? $"\"{formatted}\"" : formatted; var actual = HeaderUtilities.FormatDate(dateTime, quoted); Assert.Equal(expected, actual); } public static TheoryData<DateTimeOffset, bool> TestValues { get { var data = new TheoryData<DateTimeOffset, bool>(); var date = new DateTimeOffset(new DateTime(2018, 1, 1, 1, 1, 1)); foreach (var quoted in new[] { true, false }) { data.Add(date, quoted); for (var i = 1; i < 60; i++) { data.Add(date.AddSeconds(i), quoted); data.Add(date.AddMinutes(i), quoted); } for (var i = 1; i < DateTime.DaysInMonth(date.Year, date.Month); i++) { data.Add(date.AddDays(i), quoted); } for (var i = 1; i < 11; i++) { data.Add(date.AddMonths(i), quoted); } for (var i = 1; i < 5; i++) { data.Add(date.AddYears(i), quoted); } } return data; } } [Theory] [InlineData("h=1", "h", 1)] [InlineData("directive1=3, directive2=10", "directive1", 3)] [InlineData("directive1 =45, directive2=80", "directive1", 45)] [InlineData("directive1= 89 , directive2=22", "directive1", 89)] [InlineData("directive1= 89 , directive2= 42", "directive2", 42)] [InlineData("directive1= 89 , directive= 42", "directive", 42)] [InlineData("directive1,,,,,directive2 = 42 ", "directive2", 42)] [InlineData("directive1=;,directive2 = 42 ", "directive2", 42)] [InlineData("directive1;;,;;,directive2 = 42 ", "directive2", 42)] [InlineData("directive1=value;q=0.6,directive2 = 42 ", "directive2", 42)] public void TryParseSeconds_Succeeds(string headerValues, string targetValue, int expectedValue) { TimeSpan? value; Assert.True(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue, out value)); Assert.Equal(TimeSpan.FromSeconds(expectedValue), value); } [Theory] [InlineData("", "")] [InlineData(null, null)] [InlineData("h=", "h")] [InlineData("directive1=, directive2=10", "directive1")] [InlineData("directive1 , directive2=80", "directive1")] [InlineData("h=10", "directive")] [InlineData("directive1", "directive")] [InlineData("directive1,,,,,,,", "directive")] [InlineData("h=directive", "directive")] [InlineData("directive1, directive2=80", "directive")] [InlineData("directive1=;, directive2=10", "directive1")] [InlineData("directive1;directive2=10", "directive2")] public void TryParseSeconds_Fails(string? headerValues, string? targetValue) { TimeSpan? value; Assert.False(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue!, out value)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1234567890)] [InlineData(long.MaxValue)] public void FormatNonNegativeInt64_MatchesToString(long value) { Assert.Equal(value.ToString(CultureInfo.InvariantCulture), HeaderUtilities.FormatNonNegativeInt64(value)); } [Theory] [InlineData(-1)] [InlineData(-1234567890)] [InlineData(long.MinValue)] public void FormatNonNegativeInt64_Throws_ForNegativeValues(long value) { Assert.Throws<ArgumentOutOfRangeException>(() => HeaderUtilities.FormatNonNegativeInt64(value)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(-1)] [InlineData(-1234567890)] [InlineData(1234567890)] [InlineData(long.MinValue)] [InlineData(long.MaxValue)] public void FormatInt64_MatchesToString(long value) { Assert.Equal(value.ToString(CultureInfo.InvariantCulture), HeaderUtilities.FormatInt64(value)); } [Theory] [InlineData("h", "h", true)] [InlineData("h=", "h", true)] [InlineData("h=1", "h", true)] [InlineData("H", "h", true)] [InlineData("H=", "h", true)] [InlineData("H=1", "h", true)] [InlineData("h", "H", true)] [InlineData("h=", "H", true)] [InlineData("h=1", "H", true)] [InlineData("directive1, directive=10", "directive1", true)] [InlineData("directive1=, directive=10", "directive1", true)] [InlineData("directive1=3, directive=10", "directive1", true)] [InlineData("directive1 , directive=80", "directive1", true)] [InlineData(" directive1, directive=80", "directive1", true)] [InlineData("directive1 =45, directive=80", "directive1", true)] [InlineData("directive1= 89 , directive=22", "directive1", true)] [InlineData("directive1, directive", "directive", true)] [InlineData("directive1, directive=", "directive", true)] [InlineData("directive1, directive=10", "directive", true)] [InlineData("directive1=3, directive", "directive", true)] [InlineData("directive1=3, directive=", "directive", true)] [InlineData("directive1=3, directive=10", "directive", true)] [InlineData("directive1= 89 , directive= 42", "directive", true)] [InlineData("directive1= 89 , directive = 42", "directive", true)] [InlineData("directive1,,,,,directive2 = 42 ", "directive2", true)] [InlineData("directive1;;,;;,directive2 = 42 ", "directive2", true)] [InlineData("directive1=;,directive2 = 42 ", "directive2", true)] [InlineData("directive1=value;q=0.6,directive2 = 42 ", "directive2", true)] [InlineData(null, null, false)] [InlineData(null, "", false)] [InlineData("", null, false)] [InlineData("", "", false)] [InlineData("h=10", "directive", false)] [InlineData("directive1", "directive", false)] [InlineData("directive1,,,,,,,", "directive", false)] [InlineData("h=directive", "directive", false)] [InlineData("directive1, directive2=80", "directive", false)] [InlineData("directive1;, directive2=80", "directive", false)] [InlineData("directive1=value;q=0.6;directive2 = 42 ", "directive2", false)] public void ContainsCacheDirective_MatchesExactValue(string? headerValues, string? targetValue, bool contains) { Assert.Equal(contains, HeaderUtilities.ContainsCacheDirective(new StringValues(headerValues), targetValue!)); } [Theory] [InlineData("")] [InlineData(null)] [InlineData("-1")] [InlineData("a")] [InlineData("1.1")] [InlineData("9223372036854775808")] // long.MaxValue + 1 public void TryParseNonNegativeInt64_Fails(string? valueString) { long value = 1; Assert.False(HeaderUtilities.TryParseNonNegativeInt64(valueString, out value)); Assert.Equal(0, value); } [Theory] [InlineData("0", 0)] [InlineData("9223372036854775807", 9223372036854775807)] // long.MaxValue public void TryParseNonNegativeInt64_Succeeds(string valueString, long expected) { long value = 1; Assert.True(HeaderUtilities.TryParseNonNegativeInt64(valueString, out value)); Assert.Equal(expected, value); } [Theory] [InlineData("")] [InlineData(null)] [InlineData("-1")] [InlineData("a")] [InlineData("1.1")] [InlineData("1,000")] [InlineData("2147483648")] // int.MaxValue + 1 public void TryParseNonNegativeInt32_Fails(string? valueString) { int value = 1; Assert.False(HeaderUtilities.TryParseNonNegativeInt32(valueString, out value)); Assert.Equal(0, value); } [Theory] [InlineData("0", 0)] [InlineData("2147483647", 2147483647)] // int.MaxValue public void TryParseNonNegativeInt32_Succeeds(string valueString, long expected) { int value = 1; Assert.True(HeaderUtilities.TryParseNonNegativeInt32(valueString, out value)); Assert.Equal(expected, value); } [Theory] [InlineData("\"hello\"", "hello")] [InlineData("\"hello", "\"hello")] [InlineData("hello\"", "hello\"")] [InlineData("\"\"hello\"\"", "\"hello\"")] public void RemoveQuotes_BehaviorCheck(string input, string expected) { var actual = HeaderUtilities.RemoveQuotes(input); Assert.Equal(expected.AsSpan(), actual); } [Theory] [InlineData("\"hello\"", true)] [InlineData("\"hello", false)] [InlineData("hello\"", false)] [InlineData("\"\"hello\"\"", true)] public void IsQuoted_BehaviorCheck(string input, bool expected) { var actual = HeaderUtilities.IsQuoted(input); Assert.Equal(expected, actual); } [Theory] [InlineData("value", "value")] [InlineData("\"value\"", "value")] [InlineData("\"hello\\\\\"", "hello\\")] [InlineData("\"hello\\\"\"", "hello\"")] [InlineData("\"hello\\\"foo\\\\bar\\\\baz\\\\\"", "hello\"foo\\bar\\baz\\")] [InlineData("\"quoted value\"", "quoted value")] [InlineData("\"quoted\\\"valuewithquote\"", "quoted\"valuewithquote")] [InlineData("\"hello\\\"", "hello\\")] public void UnescapeAsQuotedString_BehaviorCheck(string input, string expected) { var actual = HeaderUtilities.UnescapeAsQuotedString(input); Assert.Equal(expected.AsSpan(), actual); } [Theory] [InlineData("value", "\"value\"")] [InlineData("23", "\"23\"")] [InlineData(";;;", "\";;;\"")] [InlineData("\"value\"", "\"\\\"value\\\"\"")] [InlineData("unquoted \"value", "\"unquoted \\\"value\"")] [InlineData("value\\morevalues\\evenmorevalues", "\"value\\\\morevalues\\\\evenmorevalues\"")] // We have to assume that the input needs to be quoted here [InlineData("\"\"double quoted string\"\"", "\"\\\"\\\"double quoted string\\\"\\\"\"")] [InlineData("\t", "\"\t\"")] public void SetAndEscapeValue_BehaviorCheck(string input, string expected) { var actual = HeaderUtilities.EscapeAsQuotedString(input); Assert.Equal(expected.AsSpan(), actual); } [Theory] [InlineData("\n")] [InlineData("\b")] [InlineData("\r")] public void SetAndEscapeValue_ControlCharactersThrowFormatException(string input) { Assert.Throws<FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString(input); }); } [Fact] public void SetAndEscapeValue_ThrowsFormatExceptionOnDelCharacter() { Assert.Throws<FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString($"{(char)0x7F}"); }); } [Theory] [InlineData("text;q=0", 0d, 1)] [InlineData("text;q=1", 1d, 1)] public void TryParseQualityDouble_WithoutDecimalPart_ReturnsCorrectQuality( string inputString, double expectedQuality, int expectedLength) => VerifyTryParseQualityDoubleSuccess(inputString, 7, expectedQuality, expectedLength); [Theory] [InlineData("text;q=0,*;q=1", 0d, 1)] [InlineData("text;q=1,*;q=0", 1d, 1)] public void TryParseQualityDouble_WithoutDecimalPart_WithSubsequentCharacters_ReturnsCorrectQuality( string inputString, double expectedQuality, int expectedLength) => VerifyTryParseQualityDoubleSuccess(inputString, 7, expectedQuality, expectedLength); [Theory] [InlineData("text;q=0.", 0d, 2)] [InlineData("text;q=0.0", 0d, 3)] [InlineData("text;q=0.00000000", 0d, 10)] [InlineData("text;q=1.", 1d, 2)] [InlineData("text;q=1.0", 1d, 3)] [InlineData("text;q=1.000", 1d, 5)] [InlineData("text;q=1.00000000", 1d, 10)] [InlineData("text;q=0.1", 0.1d, 3)] [InlineData("text;q=0.001", 0.001d, 5)] [InlineData("text;q=0.00000001", 0.00000001d, 10)] [InlineData("text;q=0.12345678", 0.12345678d, 10)] [InlineData("text;q=0.98765432", 0.98765432d, 10)] public void TryParseQualityDouble_WithDecimalPart_ReturnsCorrectQuality( string inputString, double expectedQuality, int expectedLength) => VerifyTryParseQualityDoubleSuccess(inputString, 7, expectedQuality, expectedLength); [Theory] [InlineData("text;q=0.,*;q=1", 0d, 2)] [InlineData("text;q=0.0,*;q=1", 0d, 3)] [InlineData("text;q=0.00000000,*;q=1", 0d, 10)] [InlineData("text;q=1.,*;q=1", 1d, 2)] [InlineData("text;q=1.0,*;q=1", 1d, 3)] [InlineData("text;q=1.000,*;q=1", 1d, 5)] [InlineData("text;q=1.00000000,*;q=1", 1d, 10)] [InlineData("text;q=0.1,*;q=1", 0.1d, 3)] [InlineData("text;q=0.001,*;q=1", 0.001d, 5)] [InlineData("text;q=0.00000001,*;q=1", 0.00000001d, 10)] [InlineData("text;q=0.12345678,*;q=1", 0.12345678d, 10)] [InlineData("text;q=0.98765432,*;q=1", 0.98765432d, 10)] public void TryParseQualityDouble_WithDecimalPart_WithSubsequentCharacters_ReturnsCorrectQuality( string inputString, double expectedQuality, int expectedLength) => VerifyTryParseQualityDoubleSuccess(inputString, 7, expectedQuality, expectedLength); private static void VerifyTryParseQualityDoubleSuccess(string inputString, int startIndex, double expectedQuality, int expectedLength) { // Arrange var input = new StringSegment(inputString); // Act var result = HeaderUtilities.TryParseQualityDouble(input, startIndex, out var actualQuality, out var actualLength); // Assert Assert.True(result); Assert.Equal(expectedQuality, actualQuality); Assert.Equal(expectedLength, actualLength); } [Fact] public void TryParseQualityDouble_StartIndexIsOutOfRange_ReturnsFalse() => VerifyTryParseQualityDoubleFailure("text;q=0.1", 10); [Theory] [InlineData("text;q=2")] [InlineData("text;q=a")] [InlineData("text;q=.1")] [InlineData("text;q=/.1")] [InlineData("text;q=:.1")] public void TryParseQualityDouble_HasInvalidStartingCharacter_ReturnsFalse(string inputString) => VerifyTryParseQualityDoubleFailure(inputString, 7); [Theory] [InlineData("text;q=00")] [InlineData("text;q=00.")] [InlineData("text;q=00.0")] [InlineData("text;q=01.0")] [InlineData("text;q=10")] [InlineData("text;q=10.")] [InlineData("text;q=10.0")] [InlineData("text;q=11.0")] public void TryParseQualityDouble_HasMoreThanOneDigitBeforeDot_ReturnsFalse(string inputString) => VerifyTryParseQualityDoubleFailure(inputString, 7); [Theory] [InlineData("text;q=0.000000000")] [InlineData("text;q=1.000000000")] [InlineData("text;q=0.000000001")] public void TryParseQualityDouble_ExceedsQualityValueMaxCharacterCount_ReturnsFalse(string inputString) => VerifyTryParseQualityDoubleFailure(inputString, 7); [Theory] [InlineData("text;q=1.000000001")] [InlineData("text;q=2")] public void TryParseQualityDouble_ParsedQualityIsGreaterThanOne_ReturnsFalse(string inputString) => VerifyTryParseQualityDoubleFailure(inputString, 7); private static void VerifyTryParseQualityDoubleFailure(string inputString, int startIndex) { // Arrange var input = new StringSegment(inputString); // Act var result = HeaderUtilities.TryParseQualityDouble(input, startIndex, out var quality, out var length); // Assert Assert.False(result); Assert.Equal(0, quality); Assert.Equal(0, length); } }
HeaderUtilitiesTest
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/Serializers/ValueTupleSerializers.cs
{ "start": 20214, "end": 28435 }
public sealed class ____<T1, T2, T3, T4> : StructSerializerBase<ValueTuple<T1, T2, T3, T4>>, IBsonTupleSerializer { // private fields private readonly Lazy<IBsonSerializer<T1>> _lazyItem1Serializer; private readonly Lazy<IBsonSerializer<T2>> _lazyItem2Serializer; private readonly Lazy<IBsonSerializer<T3>> _lazyItem3Serializer; private readonly Lazy<IBsonSerializer<T4>> _lazyItem4Serializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="ValueTupleSerializer{T1, T2, T3, T4}"/> class. /// </summary> public ValueTupleSerializer() : this(BsonSerializer.SerializerRegistry) { } /// <summary> /// Initializes a new instance of the <see cref="ValueTupleSerializer{T1, T2, T3, T4}"/> class. /// </summary> /// <param name="item1Serializer">The Item1 serializer.</param> /// <param name="item2Serializer">The Item2 serializer.</param> /// <param name="item3Serializer">The Item3 serializer.</param> /// <param name="item4Serializer">The Item4 serializer.</param> public ValueTupleSerializer( IBsonSerializer<T1> item1Serializer, IBsonSerializer<T2> item2Serializer, IBsonSerializer<T3> item3Serializer, IBsonSerializer<T4> item4Serializer) { if (item1Serializer == null) { throw new ArgumentNullException(nameof(item1Serializer)); } if (item2Serializer == null) { throw new ArgumentNullException(nameof(item2Serializer)); } if (item3Serializer == null) { throw new ArgumentNullException(nameof(item3Serializer)); } if (item4Serializer == null) { throw new ArgumentNullException(nameof(item4Serializer)); } _lazyItem1Serializer = new Lazy<IBsonSerializer<T1>>(() => item1Serializer); _lazyItem2Serializer = new Lazy<IBsonSerializer<T2>>(() => item2Serializer); _lazyItem3Serializer = new Lazy<IBsonSerializer<T3>>(() => item3Serializer); _lazyItem4Serializer = new Lazy<IBsonSerializer<T4>>(() => item4Serializer); } /// <summary> /// Initializes a new instance of the <see cref="ValueTupleSerializer{T1, T2, T3, T4}" /> class. /// </summary> /// <param name="serializerRegistry">The serializer registry.</param> public ValueTupleSerializer(IBsonSerializerRegistry serializerRegistry) { if (serializerRegistry == null) { throw new ArgumentNullException(nameof(serializerRegistry)); } _lazyItem1Serializer = new Lazy<IBsonSerializer<T1>>(() => serializerRegistry.GetSerializer<T1>()); _lazyItem2Serializer = new Lazy<IBsonSerializer<T2>>(() => serializerRegistry.GetSerializer<T2>()); _lazyItem3Serializer = new Lazy<IBsonSerializer<T3>>(() => serializerRegistry.GetSerializer<T3>()); _lazyItem4Serializer = new Lazy<IBsonSerializer<T4>>(() => serializerRegistry.GetSerializer<T4>()); } // public properties /// <summary> /// Gets the Item1 serializer. /// </summary> public IBsonSerializer<T1> Item1Serializer => _lazyItem1Serializer.Value; /// <summary> /// Gets the Item2 serializer. /// </summary> public IBsonSerializer<T2> Item2Serializer => _lazyItem2Serializer.Value; /// <summary> /// Gets the Item3 serializer. /// </summary> public IBsonSerializer<T3> Item3Serializer => _lazyItem3Serializer.Value; /// <summary> /// Gets the Item4 serializer. /// </summary> public IBsonSerializer<T4> Item4Serializer => _lazyItem4Serializer.Value; // public methods /// <inheritdoc/> public override ValueTuple<T1, T2, T3, T4> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var reader = context.Reader; T1 item1 = default; T2 item2 = default; T3 item3 = default; T4 item4 = default; switch (reader.GetCurrentBsonType()) { case BsonType.Array: reader.ReadStartArray(); item1 = _lazyItem1Serializer.Value.Deserialize(context); item2 = _lazyItem2Serializer.Value.Deserialize(context); item3 = _lazyItem3Serializer.Value.Deserialize(context); item4 = _lazyItem4Serializer.Value.Deserialize(context); reader.ReadEndArray(); break; case BsonType.Document: reader.ReadStartDocument(); while (reader.ReadBsonType() != BsonType.EndOfDocument) { var name = reader.ReadName(); switch (name) { case "Item1": item1 = _lazyItem1Serializer.Value.Deserialize(context); break; case "Item2": item2 = _lazyItem2Serializer.Value.Deserialize(context); break; case "Item3": item3 = _lazyItem3Serializer.Value.Deserialize(context); break; case "Item4": item4 = _lazyItem4Serializer.Value.Deserialize(context); break; default: throw new BsonSerializationException($"Invalid element {name} found while deserializing a ValueTuple."); } } reader.ReadEndDocument(); break; default: throw new BsonSerializationException($"Cannot deserialize a ValueTuple when BsonType is: {reader.CurrentBsonType}."); } return new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4); } /// <inheritdoc/> public override bool Equals(object obj) { if (object.ReferenceEquals(obj, null)) { return false; } if (object.ReferenceEquals(this, obj)) { return true; } return base.Equals(obj) && obj is ValueTupleSerializer<T1, T2, T3, T4> other && object.ReferenceEquals(_lazyItem1Serializer.Value, other._lazyItem1Serializer.Value) && object.ReferenceEquals(_lazyItem2Serializer.Value, other._lazyItem2Serializer.Value) && object.ReferenceEquals(_lazyItem3Serializer.Value, other._lazyItem3Serializer.Value) && object.ReferenceEquals(_lazyItem4Serializer.Value, other._lazyItem4Serializer.Value); } /// <inheritdoc/> public override int GetHashCode() => 0; /// <inheritdoc/> public IBsonSerializer GetItemSerializer(int itemNumber) { return itemNumber switch { 1 => _lazyItem1Serializer.Value, 2 => _lazyItem2Serializer.Value, 3 => _lazyItem3Serializer.Value, 4 => _lazyItem4Serializer.Value, _ => throw new IndexOutOfRangeException(nameof(itemNumber)) }; } /// <inheritdoc/> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ValueTuple<T1, T2, T3, T4> value) { context.Writer.WriteStartArray(); _lazyItem1Serializer.Value.Serialize(context, value.Item1); _lazyItem2Serializer.Value.Serialize(context, value.Item2); _lazyItem3Serializer.Value.Serialize(context, value.Item3); _lazyItem4Serializer.Value.Serialize(context, value.Item4); context.Writer.WriteEndArray(); } } /// <summary> /// Represents a serializer for a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>. /// </summary> /// <typeparam name="T1">The type of item 1.</typeparam> /// <typeparam name="T2">The type of item 2.</typeparam> /// <typeparam name="T3">The type of item 3.</typeparam> /// <typeparam name="T4">The type of item 4.</typeparam> /// <typeparam name="T5">The type of item 5.</typeparam>
ValueTupleSerializer
csharp
microsoft__FASTER
cs/remote/src/FASTER.server/PubSub/FixedLenKeySerializer.cs
{ "start": 298, "end": 1319 }
sealed class ____<Key, Input> : IKeyInputSerializer<Key, Input> { /// <summary> /// Constructor /// </summary> public FixedLenKeySerializer() { } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref Key ReadKeyByRef(ref byte* src) { var _src = (void*)src; src += Unsafe.SizeOf<Key>(); return ref Unsafe.AsRef<Key>(_src); } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref Input ReadInputByRef(ref byte* src) { var _src = (void*)src; src += Unsafe.SizeOf<Input>(); return ref Unsafe.AsRef<Input>(_src); } /// <inheritdoc /> public bool Match(ref Key k, bool asciiKey, ref Key pattern, bool asciiPattern) { if (k.Equals(pattern)) return true; return false; } } }
FixedLenKeySerializer
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/DI/GraphQLBuilderExtensionTests.cs
{ "start": 62014, "end": 62087 }
private class ____ : BaseSchemaNodeVisitor { }
TestSchemaVisitor
csharp
dotnet__efcore
src/EFCore/Storage/ValueConversion/StringToDateTimeConverter.cs
{ "start": 536, "end": 1933 }
public class ____ : StringDateTimeConverter<string, DateTime> { /// <summary> /// Creates a new instance of this converter. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-value-converters">EF Core value converters</see> for more information and examples. /// </remarks> public StringToDateTimeConverter() : this(null) { } /// <summary> /// Creates a new instance of this converter. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-value-converters">EF Core value converters</see> for more information and examples. /// </remarks> /// <param name="mappingHints"> /// Hints that can be used by the <see cref="ITypeMappingSource" /> to create data types with appropriate /// facets for the converted data. /// </param> public StringToDateTimeConverter(ConverterMappingHints? mappingHints) : base( ToDateTime(), ToString(), DefaultHints.With(mappingHints)) { } /// <summary> /// A <see cref="ValueConverterInfo" /> for the default use of this converter. /// </summary> public static ValueConverterInfo DefaultInfo { get; } = new(typeof(string), typeof(DateTime), i => new StringToDateTimeConverter(i.MappingHints), DefaultHints); }
StringToDateTimeConverter
csharp
unoplatform__uno
src/SourceGenerators/System.Xaml/System.Xaml.Schema/XamlTypeTypeConverter.cs
{ "start": 1318, "end": 2845 }
public class ____ : TypeConverter { public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof (string); } public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof (string); } public override Object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, Object value) { throw new NotSupportedException (String.Format (CultureInfo.InvariantCulture, "Conversion from type {0} is not supported", value != null ? value.GetType () : null)); } public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (!CanConvertTo (context, destinationType)) throw new NotSupportedException (String.Format (CultureInfo.InvariantCulture, "Conversion to type {0} is not supported", destinationType)); var vctx = (IValueSerializerContext) context; var lookup = vctx != null ? (INamespacePrefixLookup) vctx.GetService (typeof (INamespacePrefixLookup)) : null; var xt = value as XamlType; if (xt != null && destinationType == typeof (string)) { if (lookup != null) return new XamlTypeName (xt).ToString (lookup); else return xt.UnderlyingType != null ? xt.UnderlyingType.ToString () : xt.ToString (); } else return base.ConvertTo (context, culture, value, destinationType); // it seems it still handles not-supported types (such as int). } } }
XamlTypeTypeConverter
csharp
getsentry__sentry-dotnet
test/Sentry.Extensions.Logging.Tests/MelDiagnosticLoggerTests.cs
{ "start": 125, "end": 2038 }
private class ____ { public ILogger<ISentryClient> MelLogger { get; set; } = Substitute.For<ILogger<ISentryClient>>(); public SentryLevel Level { get; set; } = SentryLevel.Warning; public MelDiagnosticLogger GetSut() => new(MelLogger, Level); } private readonly Fixture _fixture = new(); [Fact] public void LogLevel_ErrorLevel_IsEnabledTrue() { var sut = _fixture.GetSut(); _ = _fixture.MelLogger.IsEnabled(LogLevel.Error).Returns(true); Assert.True(sut.IsEnabled(SentryLevel.Error)); } [Fact] public void LogLevel_InfoLevel_IsEnabledFalse() { var sut = _fixture.GetSut(); _ = _fixture.MelLogger.IsEnabled(LogLevel.Information).Returns(true); Assert.False(sut.IsEnabled(SentryLevel.Info)); } [Fact] public void LogLevel_HigherLevel_IsEnabled() { _ = _fixture.MelLogger.IsEnabled(LogLevel.Debug).Returns(true); var sut = _fixture.GetSut(); Assert.False(sut.IsEnabled(SentryLevel.Info)); } // .NET Core 3+ has turned FormattedLogValues into an internal readonly struct // and now we can't match that with NSubstitute #if NETFRAMEWORK [Fact] public void Log_PassedThrough() { const SentryLevel expectedLevel = SentryLevel.Debug; const string expectedMessage = "test"; var expectedException = new Exception(); _fixture.Level = SentryLevel.Debug; var sut = _fixture.GetSut(); _ = _fixture.MelLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true); sut.Log(expectedLevel, expectedMessage, expectedException); _fixture.MelLogger.Received(1).Log( expectedLevel.ToMicrosoft(), 0, Arg.Is<object>(e => e.ToString() == expectedMessage), expectedException, Arg.Any<Func<object, Exception, string>>()); } #endif }
Fixture
csharp
abpframework__abp
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IInboxProcessor.cs
{ "start": 97, "end": 295 }
public interface ____ { Task StartAsync(InboxConfig inboxConfig, CancellationToken cancellationToken = default); Task StopAsync(CancellationToken cancellationToken = default); }
IInboxProcessor
csharp
grpc__grpc-dotnet
src/Grpc.Net.Client/GrpcChannel.cs
{ "start": 40745, "end": 40889 }
record ____ HttpHandlerContext(HttpHandlerType HttpHandlerType, TimeSpan? ConnectTimeout = null, TimeSpan? ConnectionIdleTimeout = null); }
struct
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/Enums/Proxy.cs
{ "start": 612, "end": 1599 }
internal static class ____ { /// <summary> /// Whether a proxy supports databases (e.g. database > 0). /// </summary> internal static bool SupportsDatabases(this Proxy proxy) => proxy switch { Proxy.Twemproxy => false, Proxy.Envoyproxy => false, _ => true, }; /// <summary> /// Whether a proxy supports pub/sub. /// </summary> internal static bool SupportsPubSub(this Proxy proxy) => proxy switch { Proxy.Twemproxy => false, Proxy.Envoyproxy => false, _ => true, }; /// <summary> /// Whether a proxy supports the <c>ConnectionMultiplexer.GetServer</c>. /// </summary> internal static bool SupportsServerApi(this Proxy proxy) => proxy switch { Proxy.Twemproxy => false, Proxy.Envoyproxy => false, _ => true, }; } }
ProxyExtensions
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32/OpenGl/WglDisplay.cs
{ "start": 308, "end": 7525 }
internal class ____ { private static bool? _initialized; private static readonly DebugCallbackDelegate _debugCallback = DebugCallback; private static IntPtr _bootstrapContext; private static IntPtr _bootstrapWindow; private static IntPtr _bootstrapDc; private static PixelFormatDescriptor _defaultPfd; private static int _defaultPixelFormat; public static IntPtr OpenGl32Handle = LoadLibrary("opengl32"); private delegate bool WglChoosePixelFormatARBDelegate(IntPtr hdc, int[]? piAttribIList, float[]? pfAttribFList, int nMaxFormats, int[] piFormats, out int nNumFormats); private static WglChoosePixelFormatARBDelegate? s_wglChoosePixelFormatArb; private delegate IntPtr WglCreateContextAttribsARBDelegate(IntPtr hDC, IntPtr hShareContext, int[]? attribList); private static WglCreateContextAttribsARBDelegate? s_wglCreateContextAttribsArb; private delegate void GlDebugMessageCallbackDelegate(IntPtr callback, IntPtr userParam); private static GlDebugMessageCallbackDelegate? s_glDebugMessageCallback; private delegate void DebugCallbackDelegate(int source, int type, int id, int severity, int len, IntPtr message, IntPtr userParam); [MemberNotNullWhen(true, nameof(s_wglChoosePixelFormatArb))] [MemberNotNullWhen(true, nameof(s_wglCreateContextAttribsArb))] private static bool Initialize() => _initialized ??= InitializeCore(); [MemberNotNullWhen(true, nameof(s_wglChoosePixelFormatArb))] [MemberNotNullWhen(true, nameof(s_wglCreateContextAttribsArb))] private static bool InitializeCore() { Dispatcher.UIThread.VerifyAccess(); _bootstrapWindow = WglGdiResourceManager.CreateOffscreenWindow(); _bootstrapDc = WglGdiResourceManager.GetDC(_bootstrapWindow); _defaultPfd = new PixelFormatDescriptor { Size = (ushort)Marshal.SizeOf<PixelFormatDescriptor>(), Version = 1, Flags = PixelFormatDescriptorFlags.PFD_DRAW_TO_WINDOW | PixelFormatDescriptorFlags.PFD_SUPPORT_OPENGL | PixelFormatDescriptorFlags.PFD_DOUBLEBUFFER, DepthBits = 24, StencilBits = 8, ColorBits = 32 }; _defaultPixelFormat = ChoosePixelFormat(_bootstrapDc, ref _defaultPfd); SetPixelFormat(_bootstrapDc, _defaultPixelFormat, ref _defaultPfd); _bootstrapContext = wglCreateContext(_bootstrapDc); if (_bootstrapContext == IntPtr.Zero) return false; wglMakeCurrent(_bootstrapDc, _bootstrapContext); s_wglCreateContextAttribsArb = Marshal.GetDelegateForFunctionPointer<WglCreateContextAttribsARBDelegate>( wglGetProcAddress("wglCreateContextAttribsARB")); s_wglChoosePixelFormatArb = Marshal.GetDelegateForFunctionPointer<WglChoosePixelFormatARBDelegate>( wglGetProcAddress("wglChoosePixelFormatARB")); s_glDebugMessageCallback = wglGetProcAddress("glDebugMessageCallback") is { } setDebugCallback && setDebugCallback != default ? Marshal.GetDelegateForFunctionPointer<GlDebugMessageCallbackDelegate>(setDebugCallback) : null; var formats = new int[1]; s_wglChoosePixelFormatArb(_bootstrapDc, new int[] { WGL_DRAW_TO_WINDOW_ARB, 1, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SUPPORT_OPENGL_ARB, 1, WGL_DOUBLE_BUFFER_ARB, 1, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 0, WGL_STENCIL_BITS_ARB, 0, 0, // End }, null, 1, formats, out int numFormats); if (numFormats != 0) { DescribePixelFormat(_bootstrapDc, formats[0], Marshal.SizeOf<PixelFormatDescriptor>(), ref _defaultPfd); _defaultPixelFormat = formats[0]; } wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); return true; } private static void DebugCallback(int source, int type, int id, int severity, int len, IntPtr message, IntPtr userparam) { var err = Marshal.PtrToStringAnsi(message, len); Console.Error.WriteLine(err); } public static WglContext? CreateContext(GlVersion[] versions, IGlContext? share) { if (!Initialize()) return null; var shareContext = share as WglContext; using (new WglRestoreContext(_bootstrapDc, _bootstrapContext, null)) { var window = WglGdiResourceManager.CreateOffscreenWindow(); var dc = WglGdiResourceManager.GetDC(window); SetPixelFormat(dc, _defaultPixelFormat, ref _defaultPfd); foreach (var version in versions) { if(version.Type != GlProfileType.OpenGL) continue; IntPtr context; using (shareContext?.Lock()) { var profileMask = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; if (version.IsCompatibilityProfile && (version.Major > 3 || version.Major == 3 && version.Minor >= 2)) profileMask = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; context = s_wglCreateContextAttribsArb(dc, shareContext?.Handle ?? IntPtr.Zero, new[] { // major WGL_CONTEXT_MAJOR_VERSION_ARB, version.Major, // minor WGL_CONTEXT_MINOR_VERSION_ARB, version.Minor, // core or compatibility profile WGL_CONTEXT_PROFILE_MASK_ARB, profileMask, // debug // WGL_CONTEXT_FLAGS_ARB, 1, // end 0, 0 }); } if (s_glDebugMessageCallback is not null) { using (new WglRestoreContext(dc, context, null)) s_glDebugMessageCallback(Marshal.GetFunctionPointerForDelegate(_debugCallback), IntPtr.Zero); } if (context != IntPtr.Zero) return new WglContext(shareContext, version, context, window, dc, _defaultPixelFormat, _defaultPfd); } WglGdiResourceManager.ReleaseDC(window, dc); WglGdiResourceManager.DestroyWindow(window); return null; } } } }
WglDisplay
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.Tests/Generation/EnumTests.cs
{ "start": 702, "end": 1378 }
public class ____ { public MetadataSchemaDetailViewItem MetadataSchemaDetailViewItem { get; set; } public MetadataSchemaCreateRequest MetadataSchemaCreateRequest { get; set; } } [Fact] public async Task When_enum_is_used_multiple_times_in_array_then_it_is_always_referenced() { // Arrange // Act var schema = NewtonsoftJsonSchemaGenerator.FromType<MyController>(new NewtonsoftJsonSchemaGeneratorSettings()); var json = schema.ToJson(); // Assert Assert.True(json.Split(["x-enumNames"], StringSplitOptions.None).Length == 2); //
MyController
csharp
nuke-build__nuke
source/Nuke.Common/Tools/Docker/Docker.Generated.cs
{ "start": 615934, "end": 616748 }
public partial class ____ : DockerOptionsBase { /// <summary>Password.</summary> [Argument(Format = "--password {value}", Secret = true)] public string Password => Get<string>(() => Password); /// <summary>Username.</summary> [Argument(Format = "--username {value}")] public string Username => Get<string>(() => Username); /// <summary>[SERVER]</summary> [Argument(Format = "{value}", Position = -1)] public string Server => Get<string>(() => Server); } #endregion #region DockerSwarmUnlockKeySettings /// <inheritdoc cref="DockerTasks.DockerSwarmUnlockKey(Nuke.Common.Tools.Docker.DockerSwarmUnlockKeySettings)"/> [PublicAPI] [ExcludeFromCodeCoverage] [Command(Type = typeof(DockerTasks), Command = nameof(DockerTasks.DockerSwarmUnlockKey), Arguments = "swarm unlock-key")]
DockerLoginSettings
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Controls.UnitTests/TabControlTests.cs
{ "start": 27946, "end": 29458 }
private class ____ : TopLevel { private readonly ILayoutManager _layoutManager; public bool IsClosed { get; private set; } public TestTopLevel(ITopLevelImpl impl, ILayoutManager layoutManager = null) : base(impl) { _layoutManager = layoutManager ?? new LayoutManager(this); } private protected override ILayoutManager CreateLayoutManager() => _layoutManager; } private static void Prepare(TabControl target) { ApplyTemplate(target); target.Measure(Size.Infinity); target.Arrange(new Rect(target.DesiredSize)); } private static void RaiseKeyEvent(Control target, Key key, KeyModifiers inputModifiers = 0) { target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, KeyModifiers = inputModifiers, Key = key }); } private static void ApplyTemplate(TabControl target) { target.ApplyTemplate(); target.Presenter.ApplyTemplate(); foreach (var tabItem in target.GetLogicalChildren().OfType<TabItem>()) { tabItem.Template = TabItemTemplate(); tabItem.ApplyTemplate(); tabItem.Presenter.UpdateChild(); } target.ContentPart.ApplyTemplate(); }
TestTopLevel
csharp
PrismLibrary__Prism
src/Prism.Core/Common/IParameters.cs
{ "start": 202, "end": 3209 }
public interface ____ : IEnumerable<KeyValuePair<string, object>> { /// <summary> /// Adds the specified key and value to the parameter collection. /// </summary> /// <param name="key">The key of the parameter to add.</param> /// <param name="value">The value of the parameter to add.</param> void Add(string key, object value); /// <summary> /// Determines whether the <see cref="IParameters"/> contains the specified <paramref name="key"/>. /// </summary> /// <param name="key">The key to search the parameters for existence.</param> /// <returns>true if the <see cref="IParameters"/> contains a parameter with the specified key; otherwise, false.</returns> bool ContainsKey(string key); /// <summary> /// Gets the number of parameters contained in the <see cref="IParameters"/>. /// </summary> int Count { get; } /// <summary> /// Gets a collection containing the keys in the <see cref="IParameters"/>. /// </summary> IEnumerable<string> Keys { get; } /// <summary> /// Gets the parameter associated with the specified <paramref name="key"/>. /// </summary> /// <typeparam name="T">The type of the parameter to get.</typeparam> /// <param name="key">The key of the parameter to find.</param> /// <returns>A matching value of <typeparamref name="T"/> if it exists.</returns> T GetValue<T>(string key); /// <summary> /// Gets the parameter associated with the specified <paramref name="key"/>. /// </summary> /// <typeparam name="T">The type of the parameter to get.</typeparam> /// <param name="key">The key of the parameter to find.</param> /// <returns>An <see cref="IEnumerable{T}"/> of all the values referenced by key.</returns> IEnumerable<T> GetValues<T>(string key); /// <summary> /// Gets the parameter associated with the specified <paramref name="key"/>. /// </summary> /// <typeparam name="T">The type of the parameter to get.</typeparam> /// <param name="key">The key of the parameter to get.</param> /// <param name="value"> /// When this method returns, contains the parameter associated with the specified key, /// if the key is found; otherwise, the default value for the type of the value parameter. /// </param> /// <returns>true if the <see cref="IParameters"/> contains a parameter with the specified key; otherwise, false.</returns> bool TryGetValue<T>(string key, [MaybeNullWhen(false)] out T value); /// <summary> /// Gets the parameter associated with the specified key (legacy). /// </summary> /// <param name="key">The key of the parameter to get.</param> /// <returns>A matching value if it exists.</returns> object? this[string key] { get; } } }
IParameters
csharp
dotnet__maui
src/Core/tests/DeviceTests/Stubs/SwipeItemsStub.cs
{ "start": 217, "end": 2143 }
public class ____ : StubBase, ISwipeItems { readonly ObservableCollection<Maui.ISwipeItem> _swipeItems; public SwipeItemsStub(IEnumerable<ISwipeItem> swipeItems) { _swipeItems = new ObservableCollection<Maui.ISwipeItem>(swipeItems) ?? throw new ArgumentNullException(nameof(swipeItems)); _swipeItems.CollectionChanged += OnSwipeItemsChanged; } public SwipeItemsStub() : this(Enumerable.Empty<ISwipeItem>()) { } public event NotifyCollectionChangedEventHandler CollectionChanged; public ISwipeItem this[int index] { get => _swipeItems.Count > index ? (ISwipeItem)_swipeItems[index] : null; set => _swipeItems[index] = value; } public int Count => _swipeItems.Count; public bool IsReadOnly => false; public SwipeMode Mode { get; set; } public SwipeBehaviorOnInvoked SwipeBehaviorOnInvoked { get; set; } public void Add(ISwipeItem item) { _swipeItems.Add(item); } public void Clear() { _swipeItems.Clear(); } public bool Contains(ISwipeItem item) { return _swipeItems.Contains(item); } public void CopyTo(ISwipeItem[] array, int arrayIndex) { _swipeItems.CopyTo(array, arrayIndex); } public IEnumerator<ISwipeItem> GetEnumerator() { foreach (ISwipeItem item in _swipeItems) yield return item; } public int IndexOf(ISwipeItem item) { return _swipeItems.IndexOf(item); } public void Insert(int index, ISwipeItem item) { _swipeItems.Insert(index, item); } public bool Remove(ISwipeItem item) { return _swipeItems.Remove(item); } public void RemoveAt(int index) { _swipeItems.RemoveAt(index); } void OnSwipeItemsChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { CollectionChanged?.Invoke(this, notifyCollectionChangedEventArgs); } IEnumerator IEnumerable.GetEnumerator() { return _swipeItems.GetEnumerator(); } } }
SwipeItemsStub
csharp
AutoFixture__AutoFixture
Src/AutoFixtureUnitTest/FixtureTest.cs
{ "start": 229289, "end": 230255 }
private class ____ { [EnumDataType(typeof(EnumType))] public ushort PropertyWithEnumDataType { get; set; } } [Fact] public void UshortDecoratedWithEnumDataTypeAttributeShouldPassValidation() { // Arrange var sut = new Fixture(); // Act var item = sut.Create<TypeWithUshortPropertyWithEnumDataType>(); // Assert Validator.ValidateObject(item, new ValidationContext(item), true); } [Fact] public void ShouldCorrectlyResolveUshortPropertiesDecoratedWithEnumDataTypeAttribute() { // Arrange var sut = new Fixture(); // Act var result = sut.Create<TypeWithUshortPropertyWithEnumDataType>(); // Assert Assert.Equal((ushort)EnumType.First, result.PropertyWithEnumDataType); }
TypeWithUshortPropertyWithEnumDataType
csharp
getsentry__sentry-dotnet
src/Sentry/Platforms/Native/CFunctions.cs
{ "start": 20811, "end": 22386 }
private struct ____ { private IntPtr __stack; private IntPtr __gr_top; private IntPtr __vr_top; private int __gr_offs; private int __vr_offs; } private static void WithAllocatedPtr(int size, Action<IntPtr> action) { var ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(size); action(ptr); } finally { Marshal.FreeHGlobal(ptr); } } private static void WithMarshalledStruct<T>(T structure, Action<IntPtr> action) where T : notnull => WithAllocatedPtr(Marshal.SizeOf(structure), ptr => { Marshal.StructureToPtr(structure, ptr, false); action(ptr); }); private static string? FormatWithVaList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(IntPtr format, IntPtr args) where T : struct { string? message = null; var argsStruct = Marshal.PtrToStructure<T>(args); var formattedLength = 0; WithMarshalledStruct(argsStruct, argsPtr => formattedLength = 1 + vsnprintf_linux(IntPtr.Zero, UIntPtr.Zero, format, argsPtr) ); WithAllocatedPtr(formattedLength, buffer => WithMarshalledStruct(argsStruct, argsPtr => { vsnprintf_linux(buffer, (UIntPtr)formattedLength, format, argsPtr); message = Marshal.PtrToStringAnsi(buffer); })); return message; } }
VaListArm64
csharp
microsoft__PowerToys
src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Calc/Helper/QueryHelper.cs
{ "start": 382, "end": 3079 }
partial class ____ { public static ListItem Query(string query, ISettingsInterface settings, bool isFallbackSearch, TypedEventHandler<object, object> handleSave = null) { ArgumentNullException.ThrowIfNull(query); if (!isFallbackSearch) { ArgumentNullException.ThrowIfNull(handleSave); } CultureInfo inputCulture = settings.InputUseEnglishFormat ? new CultureInfo("en-us") : CultureInfo.CurrentCulture; CultureInfo outputCulture = settings.OutputUseEnglishFormat ? new CultureInfo("en-us") : CultureInfo.CurrentCulture; // In case the user pastes a query with a leading = query = query.TrimStart('='); // Happens if the user has only typed the action key so far if (string.IsNullOrEmpty(query)) { return null; } NumberTranslator translator = NumberTranslator.Create(inputCulture, new CultureInfo("en-US")); var input = translator.Translate(query.Normalize(NormalizationForm.FormKC)); if (string.IsNullOrWhiteSpace(input)) { return ErrorHandler.OnError(isFallbackSearch, query, Properties.Resources.calculator_expression_empty); } if (!CalculateHelper.InputValid(input)) { return null; } try { // Using CurrentUICulture since this is user facing var result = CalculateEngine.Interpret(settings, input, outputCulture, out var errorMessage); // This could happen for some incorrect queries, like pi(2) if (result.Equals(default(CalculateResult))) { // If errorMessage is not default then do error handling return errorMessage == default ? null : ErrorHandler.OnError(isFallbackSearch, query, errorMessage); } if (isFallbackSearch) { // Fallback search return ResultHelper.CreateResult(result.RoundedResult, inputCulture, outputCulture, query); } return ResultHelper.CreateResult(result.RoundedResult, inputCulture, outputCulture, query, settings, handleSave); } catch (OverflowException) { // Result to big to convert to decimal return ErrorHandler.OnError(isFallbackSearch, query, Properties.Resources.calculator_not_covert_to_decimal); } catch (Exception e) { // Any other crash occurred // We want to keep the process alive if any the mages library throws any exceptions. return ErrorHandler.OnError(isFallbackSearch, query, default, e); } } }
QueryHelper
csharp
ardalis__CleanArchitecture
MinimalClean/src/MinimalClean.Architecture.Web/Domain/OrderAggregate/OrderItemId.cs
{ "start": 113, "end": 293 }
partial struct ____ { private static Validation Validate(Guid value) => value != Guid.Empty ? Validation.Ok : Validation.Invalid("OrderItemId cannot be empty."); }
OrderItemId
csharp
EventStore__EventStore
src/KurrentDB.Testing/Sample/HomeAutomation/HomeAutomationFakers.cs
{ "start": 2047, "end": 2976 }
public class ____ : Faker<LightStateChanged> { public LightStateChangedFaker(SmartLight device, long timestamp) { RuleFor(e => e.EventId, f => f.Random.Guid()) .RuleFor(e => e.Device, f => device.CreateDeviceInfo()) .RuleFor( e => e.IsOn, f => { if (f.Random.Bool(0.15f)) device.ToggleLight(); if (device.IsOn && f.Random.Bool(0.1f)) device.SetBrightness(device.Brightness + f.Random.Number(-20, 20)); return device.IsOn; } ) .RuleFor(e => e.Brightness, f => device.Brightness) .RuleFor(e => e.Color, f => f.Internet.Color()) .RuleFor(e => e.PowerConsumption, f => device.IsOn ? Math.Round(device.Brightness * 0.8 + f.Random.Double(0, 20), 2) : 0.0) .RuleFor(e => e.Timestamp, timestamp); } }
LightStateChangedFaker
csharp
AutoMapper__AutoMapper
src/UnitTests/CollectionMapping.cs
{ "start": 25626, "end": 32508 }
public class ____ { public int Id { get; set; } } private static IMapper mapper; private static void FillCollection<TSource, TDestination, TSourceItem, TDestinationItem>( TSource s, TDestination d, Func<TSource, IEnumerable<TSourceItem>> getSourceEnum, Func<TDestination, ICollection<TDestinationItem>> getDestinationColl) { ICollection<TDestinationItem> collection = getDestinationColl(d); collection.Clear(); foreach (TSourceItem sourceItem in getSourceEnum(s)) { collection.Add(mapper.Map<TSourceItem, TDestinationItem>(sourceItem)); } } [Fact] public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_list() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithCollection>() .ForMember(d => d.Details, o => o.UseDestinationValue()); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithCollection(new List<Detail>()); ICollection<Detail> originalCollection = master.Details; config.CreateMapper().Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); originalCollection.Count.ShouldBe(master.Details.Count); } [Fact] public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithCollection>() .ForMember(d => d.Details, o => o.UseDestinationValue()); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithCollection(new HashSet<Detail>()); ICollection<Detail> originalCollection = master.Details; config.CreateMapper().Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); originalCollection.Count.ShouldBe(master.Details.Count); } [Fact] public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set_with_aftermap() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithCollection>() .ForMember(d => d.Details, o => o.Ignore()) .AfterMap((s, d) => FillCollection(s, d, ss => ss.Details, dd => dd.Details)); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithCollection(new HashSet<Detail>()); ICollection<Detail> originalCollection = master.Details; mapper = config.CreateMapper(); mapper.Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); originalCollection.Count.ShouldBe(master.Details.Count); } [Fact] public void Should_keep_and_fill_destination_list() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithList>() .ForMember(d => d.Details, o => o.UseDestinationValue()); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithList(); IList<Detail> originalCollection = master.Details; config.CreateMapper().Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); originalCollection.Count.ShouldBe(master.Details.Count); } [Fact] public void Should_not_replace_destination_collection() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithCollection>() .ForMember(d => d.Details, opt => opt.UseDestinationValue()); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithCollection(new List<Detail>()); ICollection<Detail> originalCollection = master.Details; config.CreateMapper().Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); } [Fact] public void Should_be_able_to_map_to_a_collection_type_that_implements_ICollection_of_T() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithNoExistingCollection>(); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = config.CreateMapper().Map<MasterDto, MasterWithNoExistingCollection>(dto); master.Details.Count.ShouldBe(2); } [Fact] public void Should_not_replace_destination_list() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<MasterDto, MasterWithList>() .ForMember(d => d.Details, opt => opt.UseDestinationValue()); cfg.CreateMap<DetailDto, Detail>(); }); var dto = new MasterDto { Id = 1, Details = new[] { new DetailDto {Id = 2}, new DetailDto {Id = 3}, } }; var master = new MasterWithList(); IList<Detail> originalCollection = master.Details; config.CreateMapper().Map(dto, master); originalCollection.ShouldBeSameAs(master.Details); } [Fact] public void Should_map_to_NameValueCollection() { var c = new NameValueCollection(); var config = new MapperConfiguration(cfg => { }); var mappedCollection = config.CreateMapper().Map<NameValueCollection, NameValueCollection>(c); mappedCollection.ShouldNotBeSameAs(c); mappedCollection.ShouldNotBeNull(); } }
DetailDto
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.Custom/UnitTest1.cs
{ "start": 9335, "end": 38863 }
public class ____ { public int Id { get; set; } public string Name { get; set; } [Navigate("AuthorId")] public List<Post> Post { get; set; } } [Fact] public void Test1() { using (var conn = g.oracle.Ado.MasterPool.Get()) { var cmd = conn.Value.CreateCommand(); cmd.CommandText = @"SELECT a.""ID"" as1, a__Type.""NAME"" as2 FROM ""TB_TOPIC22"" a LEFT JOIN ""TESTTYPEINFO"" a__Type ON a__Type.""GUID"" = a.""TYPEGUID"" WHERE ROWNUM < 11"; var dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); var eof = dr.Read(); dr.Close(); } var ttt = g.oracle.Select<Post>().ToList(); var testrunsql1 = g.mysql.Select<TaskBuild>().Where(a => a.OptionsEntity04 > DateTime.Now.AddDays(0).ToString("yyyyMMdd").TryTo<int>()).ToSql(); var testrunsql3 = g.sqlserver.Select<TaskBuild>().Where(a => a.OptionsEntity04 > DateTime.Now.AddDays(0).ToString("yyyyMMdd").TryTo<int>()).ToSql(); var testrunsql4 = g.oracle.Select<TaskBuild>().Where(a => a.OptionsEntity04 > DateTime.Now.AddDays(0).ToString("yyyyMMdd").TryTo<int>()).ToSql(); var testformatsql1 = g.mysql.Select<TaskBuild>().Where(a => a.NamespaceName == $"1_{10100}").ToSql(); var testorderbysql = g.mysql.Select<TaskBuild>().OrderByDescending(a => a.OptionsEntity04 + (a.score ?? 0)).ToSql(); var floorSql1 = g.mysql.Select<TaskBuild>().Where(a => a.OptionsEntity04 / 10000 == 121212 / 10000).ToSql(); var floorSql2 = g.mysql.Select<TaskBuild>().Where(a => a.OptionsEntity04 / 10000.0 == 121212 / 10000).ToSql(); var testBoolSql1 = g.sqlserver.Select<TaskBuild>().Where(a => a.OptionsEntity01).ToSql(); var testBoolSql2 = g.sqlserver.Select<TaskBuild>().Where(a => a.Id == Guid.NewGuid() && a.OptionsEntity01).ToSql(); //g.mysql.Aop.AuditValue += (s, e) => //{ // if (e.Column.CsType == typeof(long) // && e.Property.GetCustomAttribute<KeyAttribute>(false) != null // && e.Value?.ToString() == "0") // e.Value = new Random().Next(); //}; //g.mysql.GetRepository<SystemUser>().Insert(GetSystemUser()); g.mysql.Aop.ParseExpression += new EventHandler<Aop.ParseExpressionEventArgs>((s, e) => { if (e.Expression.NodeType == ExpressionType.Call && (e.Expression as MethodCallExpression).Method.Name == "GetUNIX_TIMESTAMP") e.Result = "UNIX_TIMESTAMP(NOW())"; }); var dkkdksdjgj = g.mysql.Select<TaskBuild>().Where(a => a.OptionsEntity04 > GetUNIX_TIMESTAMP()).ToSql(); var dt1970 = new DateTime(1970, 1, 1); var dkkdksdjgj22 = g.mysql.Select<TaskBuild>().Where(a => a.OptionsEntity04 > DateTime.Now.Subtract(dt1970).TotalSeconds).ToSql(); var xxxhzytuple = g.sqlserver.Select<Templates, TaskBuild>() .Where(a => a.t1.Code == "xxx" && a.t2.OptionsEntity03 == true) .ToSql(); var xxxkdkd = g.oracle.Select<Templates, TaskBuild>() .InnerJoin((a,b) => true) .Where((a,b) => (DateTime.Now - a.EditTime).TotalMinutes > 100) .OrderBy((a,b) => g.oracle.Select<Templates>().Where(c => b.Id == c.Id2).Count()) .ToSql(); g.oracle.Aop.SyncStructureAfter += (s, e) => Trace.WriteLine(e.Sql); g.oracle.CodeFirst.SyncStructure<Class1>(); //g.mysql.Aop.ParseExpression += parseExp; //var sqdddd2 = g.mysql.Select<TaskBuild>().ToSql(t => t.OptionsEntity04 == t.NamespaceName.TryTo<int>()); var sqksdkfjl = g.mysql.Select<TaskBuild>() .LeftJoin(a => a.Templates.Id2 == a.TemplatesId) .LeftJoin(a => a.Parent.Id == a.Id) .LeftJoin(a => a.Parent.Templates.Id2 == a.Parent.TemplatesId) .ToSql(a => new { code1 = a.Templates.Code, code2 = a.Parent.Templates.Code }); var sqksdkfjl2223 = g.mysql.Select<TaskBuild>().From<TaskBuild, Templates, Templates>((s1, tb2, b1, b2) => s1 .LeftJoin(a => a.Id == tb2.TemplatesId) .LeftJoin(a => a.TemplatesId == b1.Id2) .LeftJoin(a => a.TemplatesId == b2.Id2) ).ToSql((a, tb2, b1, b2) => new { code1 = b1.Code, code2 = b2.Code }); var tkdkdksql = g.mysql.Select<TaskBuild>().From<Templates, Templates>((a, b, c) => a.LeftJoin(aa => aa.TemplatesId == b.Id2 && b.Code == "xx") .LeftJoin(aa => aa.TemplatesId == c.Id2)) .GroupBy((a, b, c) => new { a.NamespaceName, c.Code }) .ToSql("a.id"); var dcksdkdsk = g.mysql.Select<NewsArticle>().Where(a => a.testaddtime2.HasValue).ToSql(); var dcksdkdsk2 = g.mysql.Select<NewsArticle>().Where(a => !a.testaddtime2.HasValue).ToSql(); var testgrpsql = g.mysql.Select<TaskBuild>() .From<Templates>((a, b) => a.InnerJoin(aa => aa.TemplatesId == b.Id2)) .GroupBy((a, b) => b.Code) .ToSql(a => new { a.Key, sss = a.Sum(a.Value.Item1.OptionsEntity04) }); var testgrpsql2 = g.mysql.Select<TaskBuild>() .From<Templates>((a, b) => a.InnerJoin(aa => aa.TemplatesId == b.Id2)) .GroupBy((a, b) => b.Code) .ToList(a => new { a.Key, sss = a.Sum(a.Value.Item1.OptionsEntity04) }); var tbid = g.mysql.Select<TaskBuild>().First()?.Id ?? Guid.Empty; var testarray = new[] { 1, 2, 3 }; var tbidsql1 = g.mysql.Update<TaskBuild>().Where(a => a.Id == tbid) .Set(a => new TaskBuild { FileName = "111", TaskName = a.TaskName + "333", OptionsEntity02 = false, OptionsEntity04 = testarray[0] }).ToSql(); var tbidsql2 = g.mysql.Update<TaskBuild>().Where(a => a.Id == tbid) .Set(a => new { FileName = "111", TaskName = a.TaskName + "333", OptionsEntity02 = false, OptionsEntity04 = testarray[0] }).ToSql(); var dkdkdkd = g.oracle.Select<Templates>().ToList(); //var testaddlist = new List<NewsArticle>(); //for(var a = 0; a < 133905; a++) { // testaddlist.Add(new NewsArticle { // ArticleTitle = "testaddlist_topic" + a, // Hits = a, // }); //} //g.mysql.Insert<NewsArticle>(testaddlist) // //.NoneParameter() // .ExecuteAffrows(); g.mysql.Aop.ParseExpression += (s, e) => { if (e.Expression.NodeType == ExpressionType.Call) { var callExp = e.Expression as MethodCallExpression; if (callExp.Object?.Type == typeof(DateTime) && callExp.Method.Name == "ToString" && callExp.Arguments.Count == 1 && callExp.Arguments[0].Type == typeof(string) && callExp.Arguments[0].NodeType == ExpressionType.Constant) { var format = (callExp.Arguments[0] as ConstantExpression)?.Value?.ToString(); if (string.IsNullOrEmpty(format) == false) { var tmp = e.FreeParse(callExp.Object); switch (format) { case "yyyy-MM-dd HH:mm": tmp = $"date_format({tmp}, '%Y-%m-%d %H:%i')"; break; } e.Result = tmp; } } } }; g.mysql.Select<NewsArticle>().ToList(a => new { testaddtime = a.testaddtime.ToString("yyyy-MM-dd HH:mm") }); var ttdkdk = g.mysql.Select<NewsArticle>().Where<TaskBuild>(a => a.NamespaceName == "ddd").ToSql(); var tsqlddd = g.mysql.Select<NewsArticle>().Where(a => g.mysql.Select<TaskBuild>().Where(b => b.NamespaceName == a.ArticleTitle) .Where("@id=1", new { id = 1 }).Any() ).ToSql(); g.mysql.SetDbContextOptions(opt => opt.EnableCascadeSave = true); var trepo = g.mysql.GetRepository<TaskBuild, Guid>(); trepo.Insert(new TaskBuild { TaskName = "tt11", Builds = new[] { new TaskBuildInfo { Level = 1, Name = "t111_11" } } }); var ttdkdkd = trepo.Select.Where(a => a.Builds.AsSelect().Any()).ToList(); var list1113233 = trepo.Select.ToList(); var entity = new NewsArticle { ArticleId = 1, ArticleTitle = "测试标题" }; var where = new NewsArticle { ArticleId = 1, ChannelId = 1, }; g.mysql.Insert(new[] { entity }).ExecuteAffrows(); var sqldddkdk = g.mysql.Update<NewsArticle>(where) .SetSource(entity) .UpdateColumns(x => new { x.Status, x.CategoryId, x.ArticleTitle }) .ToSql(); var sql1111333 = g.mysql.Update<Model2>() .SetSource(new Model2 { id = 1, Title = "xxx", Parent_id = 0 }) .UpdateColumns(x => new { x.Parent_id, x.Date, x.Wa_xxx2 }) .NoneParameter() .ToSql(); g.mysql.Insert(new TestEnum { }).ExecuteAffrows(); var telist = g.mysql.Select<TestEnum>().ToList(); Assert.Throws<Exception>(() => g.mysql.CodeFirst.SyncStructure<TestEnumable>()); var TestEnumable = new TestEnumable(); g.mysql.GetRepository<Model1, int>().Insert(new Model1 { title = "test_" + DateTime.Now.ToString("yyyyMMddHHmmss"), M2Id = DateTime.Now.Second + DateTime.Now.Minute, Childs = new[] { new Model2 { Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0001", }, new Model2 { Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0002", }, new Model2 { Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0003", }, new Model2 { Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0004", } } }); var includet1 = g.mysql.Select<Model1>() .IncludeMany(a => a.Childs.Take(2), s => s.Where(a => a.id > 0)) .IncludeMany(a => a.TestManys.Take(1).Where(b => b.id == a.id)) .Where(a => a.id > 10) .ToList(); var ttt1 = g.mysql.Select<Model1>().Where(a => a.Childs.AsSelect().Any(b => b.Title == "111")).ToList(); var testpid1 = g.mysql.Insert<TestTypeInfo>().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); g.mysql.Insert<TestInfo>().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); var aggsql1 = select .GroupBy(a => a.Title) .ToSql(b => new { b.Key, cou = b.Count(), sum = b.Sum(b.Key), sum2 = b.Sum(b.Value.TypeGuid) }); var aggtolist1 = select .GroupBy(a => a.Title) .ToList(b => new { b.Key, cou = b.Count(), sum = b.Sum(b.Key), sum2 = b.Sum(b.Value.TypeGuid) }); var aggsql2 = select .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) .ToSql(b => new { b.Key.Title, b.Key.yyyy, cou = b.Count(), sum = b.Sum(b.Key.yyyy), sum2 = b.Sum(b.Value.TypeGuid) }); var aggtolist2 = select .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) .ToList(b => new { b.Key.Title, b.Key.yyyy, cou = b.Count(), sum = b.Sum(b.Key.yyyy), sum2 = b.Sum(b.Value.TypeGuid) }); var aggsql3 = select .GroupBy(a => a.Title) .ToSql(b => new { b.Key, cou = b.Count(), sum = b.Sum(b.Key), sum2 = b.Sum(b.Value.TypeGuid), sum3 = b.Sum(b.Value.Type.Parent.Parent.Id) }); var sqlrepos = g.mysql.GetRepository<TestTypeParentInfo, int>(); sqlrepos.Insert(new TestTypeParentInfo { Name = "testroot", Childs = new[] { new TestTypeParentInfo { Name = "testpath2", Childs = new[] { new TestTypeParentInfo { Name = "testpath3", Childs = new[] { new TestTypeParentInfo { Name = "11" } } } } } } }); var sql = g.mysql.Select<TestTypeParentInfo>().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToSql(); var sql222 = g.mysql.Select<TestTypeParentInfo>().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToList(); Expression<Func<TestInfo, object>> orderBy = null; orderBy = a => a.CreateTime; var testsql1 = select.OrderBy(orderBy).ToSql(); orderBy = a => a.Title; var testsql2 = select.OrderBy(orderBy).ToSql(); var testjson = @"[ { ""acptNumBelgCityName"":""泰州"", ""concPrsnName"":""常**"", ""srvReqstTypeName"":""家庭业务→网络质量→家庭宽带→自有宽带→功能使用→游戏过程中频繁掉线→全局流转"", ""srvReqstCntt"":""客户来电表示宽带使用( 所有)出现(频繁掉线不稳定) ,客户所在地址为(安装地址泰州地区靖江靖城街道工农路科技小区科技3区176号2栋2单元502),联系方式(具体联系方式),烦请协调处理。"", ""acptTime"":""2019-04-15 15:17:05"", ""acptStaffDeptId"":""0003002101010001000600020023"" }, { ""acptNumBelgCityName"":""苏州"", ""concPrsnName"":""龚**"", ""srvReqstTypeName"":""移动业务→基础服务→账/详单→全局流转→功能使用→账/详单信息不准确→全局流转"", ""srvReqstCntt"":""用户参与 2018年苏州任我用关怀活动 送的分钟数500分钟,说自己只使用了116分钟,但是我处查询到本月已经使用了306分钟\r\n,烦请处理"", ""acptTime"":""2019-04-15 15:12:05"", ""acptStaffDeptId"":""0003002101010001000600020023"" } ]"; //var dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(testjson); var reqs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ServiceRequestNew>>(testjson); reqs.ForEach(t => { g.oracle.Insert<ServiceRequestNew>(t).ExecuteAffrows(); }); var sql111 = g.mysql.Select<TestUser>().AsTable((a, b) => "(select * from TestUser where stringid > 10)").Page(1, 10).ToSql(); var xxx = g.mysql.Select<TestUser>().GroupBy(a => new { a.stringid }).ToList(a => a.Key.stringid); var tuser = g.mysql.Select<TestUser>().Where(u => u.accname == "admin") .InnerJoin(a => a.LogOn.id == a.stringid).ToSql(); var parentSelect1 = select.Where(a => a.Type.Parent.Parent.Parent.Parent.Name == "").Where(b => b.Type.Name == "").ToSql(); var collSelect1 = g.mysql.Select<Order>().Where(a => a.OrderDetails.AsSelect().Any(b => b.Id > 100) ); var collectionSelect = select.Where(a => //a.Type.Guid == a.TypeGuid && //a.Type.Parent.Id == a.Type.ParentId && a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( //b => b.ParentId == a.Type.Parent.Id ) ); var collectionSelect2 = select.Where(a => a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( b => b.Parent.Name == "xxx" && b.Parent.Parent.Name == "ccc" && b.Parent.Parent.Parent.Types.AsSelect().Any(cb => cb.Name == "yyy") ) ); var collectionSelect3 = select.Where(a => a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( bbb => bbb.Parent.Types.AsSelect().Where(lv2 => lv2.Name == bbb.Name + "111").Any( ) ) ); var neworder = new Order { CustomerName = "testCustomer", OrderTitle = "xxx#cccksksk", TransactionDate = DateTime.Now, OrderDetails = new List<OrderDetail>(new[] { new OrderDetail { }, new OrderDetail { } }) }; g.mysql.GetRepository<Order>().Insert(neworder); var order = g.mysql.Select<Order>().Where(a => a.Id == neworder.Id).ToOne(); //查询订单表 if (order == null) { var orderId = g.mysql.Insert(new Order { }).ExecuteIdentity(); order = g.mysql.Select<Order>(orderId).ToOne(); } var orderDetail1 = order.OrderDetails; //第一次访问,查询数据库 var orderDetail2 = order.OrderDetails; //第二次访问,不查 var order1 = orderDetail1.FirstOrDefault().Order; //访问导航属性,此时不查数据库,因为 OrderDetails 查询出来的时候已填充了该属性 var queryable = g.mysql.Queryable<TestInfo>().Where(a => a.Id == 1).ToList(); var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) //.Offset(a.Id) .Any() ).Any() ).ToList(); var groupbysql = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s .Where(a => a.Id == 1) .WhereIf(false, a => a.Id == 2) ) .WhereIf(true, (a, b, c) => a.Id == 3) .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) .OrderBy(a => a.Key.tt2) .OrderByDescending(a => a.Count()).ToSql(a => new { cou = a.Sum(a.Value.Item1.Id), a.Key.mod4, a.Key.tt2, max = a.Max("a.id"), max2 = Convert.ToInt64("max(a.id)") }); var groupbysql2 = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s .Where(a => a.Id == 1) .WhereIf(true, a => a.Id == 2) ) .WhereIf(false, (a, b, c) => a.Id == 3) .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) .OrderBy(a => a.Key.tt2) .OrderByDescending(a => a.Count()).ToSql(a => a.Key.mod4); var groupby = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s .Where(a => a.Id == 1) .WhereIf(true, a => a.Id == 2) ) .WhereIf(true, (a, b, c) => a.Id == 3) .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) .OrderBy(a => a.Key.tt2) .OrderByDescending(a => a.Count()) .ToList(a => new { a.Key.tt2, cou1 = a.Count(), empty = "", nil = (string)null, arg1 = a.Avg(a.Key.mod4), ccc2 = a.Key.tt2 ?? "now()", //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") }); var arrg = g.mysql.Select<TestInfo>().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); var arrg222 = g.mysql.Select<NullAggreTestTable>().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); var t1 = g.mysql.Select<TestInfo>().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); var t2 = g.mysql.Select<TestInfo>().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToList(); var sql2 = select.LeftJoin<TestTypeInfo>((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToList(); var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToList(); //g.mysql.Select<TestInfo, TestTypeInfo, TestTypeParentInfo>().Join((a, b, c) => new Model.JoinResult3( // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") //); //var sql4 = select.From<TestTypeInfo, TestTypeParentInfo>((a, b, c) => new SelectFrom() // .InnerJoin(a.TypeGuid == b.Guid) // .LeftJoin(c.Id == b.ParentId) // .Where(b.Name == "xxx")) //.Where(a => a.Id == 1).ToSql(); var sql4 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s .InnerJoin(a => a.TypeGuid == b.Guid) .LeftJoin(a => c.Id == b.ParentId) .Where(a => b.Name == "xxx")).ToList(); //.Where(a => a.Id == 1).ToSql(); var list111 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s .InnerJoin(a => a.TypeGuid == b.Guid) .LeftJoin(a => c.Id == b.ParentId) .Where(a => b.Name != "xxx")) .ToList((a, b, c) => new { a.Id, a.Title, a.Type, ccc = new { a.Id, a.Title }, tp = a.Type, tp2 = new { a.Id, tp2 = a.Type.Name }, tp3 = new { a.Id, tp33 = new { a.Id } } }); var ttt122 = g.mysql.Select<TestTypeParentInfo>().Where(a => a.Id > 0).ToList(); var sql5 = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToList(); //((JoinType.LeftJoin, a.TypeGuid == b.Guid), (JoinType.InnerJoin, b.ParentId == c.Id) var t11112 = g.mysql.Select<TestInfo>().ToList(a => new { a.Id, a.Title, a.Type, ccc = new { a.Id, a.Title }, tp = a.Type, tp2 = new { a.Id, tp2 = a.Type.Name }, tp3 = new { a.Id, tp33 = new { a.Id } } }); var t100 = g.mysql.Select<TestInfo>().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); var t101 = g.mysql.Select<TestInfo>().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); var t1111 = g.mysql.Select<TestInfo>().ToList(a => new { a.Id, a.Title, a.Type }); var t2222 = g.mysql.Select<TestInfo>().ToList(a => new { a.Id, a.Title, a.Type.Name }); var t3 = g.mysql.Insert<TestInfo>(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => a.Title).ToSql(); var t4 = g.mysql.Insert<TestInfo>(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); var t5 = g.mysql.Insert<TestInfo>(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.TypeGuid, a.CreateTime }).ToSql(); var t6 = g.mysql.Insert<TestInfo>(new[] { new TestInfo { }, new TestInfo { } }).InsertColumns(a => new { a.Title }).ToSql(); var t7 = g.mysql.Update<TestInfo>().ToSql(); var t8 = g.mysql.Update<TestInfo>().Where(new TestInfo { }).ToSql(); var t9 = g.mysql.Update<TestInfo>().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); var t10 = g.mysql.Update<TestInfo>().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); var t11 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).ToSql(); var t12 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Where(a => a.Title == "111").ToSql(); var t13 = g.mysql.Update<TestInfo>().Set(a => a.Title, "222111").ToSql(); var t14 = g.mysql.Update<TestInfo>().Set(a => a.Title, "222111").Where(new TestInfo { }).ToSql(); var t15 = g.mysql.Update<TestInfo>().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); var t16 = g.mysql.Update<TestInfo>().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); var t17 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").ToSql(); var t18 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").Where(a => a.Title == "111").ToSql(); var t19 = g.mysql.Update<TestInfo>().Set(a => a.TypeGuid + 222111).ToSql(); var t20 = g.mysql.Update<TestInfo>().Set(a => a.TypeGuid + 222111).Where(new TestInfo { }).ToSql(); var t21 = g.mysql.Update<TestInfo>().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); var t22 = g.mysql.Update<TestInfo>().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); var t23 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).ToSql(); var t24 = g.mysql.Update<TestInfo>().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).Where(a => a.Title == "111").ToSql(); var t1000 = g.mysql.Select<ExamPaper>().ToSql(); var t1001 = g.mysql.Insert<ExamPaper>().AppendData(new ExamPaper()).ToSql(); } }
AuthorTest
csharp
microsoft__semantic-kernel
dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiSchemaExtensions.cs
{ "start": 234, "end": 968 }
internal static class ____ { /// <summary> /// Gets a JSON serialized representation of an <see cref="OpenApiSchema"/> /// </summary> /// <param name="schema">The schema.</param> /// <returns>An instance of <see cref="KernelJsonSchema"/> that contains the JSON Schema.</returns> internal static KernelJsonSchema ToJsonSchema(this OpenApiSchema schema) { var schemaBuilder = new StringBuilder(); var jsonWriter = new OpenApiJsonWriter(new StringWriter(schemaBuilder, CultureInfo.InvariantCulture)); jsonWriter.Settings.InlineLocalReferences = true; schema.SerializeAsV3(jsonWriter); return KernelJsonSchema.Parse(schemaBuilder.ToString()); } }
OpenApiSchemaExtensions