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/StackTrace/StackFrame/StackFrameSourceCodeInfo.cs | {
"start": 350,
"end": 1554
} | internal sealed class ____
{
/// <summary>
/// Function containing instruction
/// </summary>
public string? Function { get; set; }
/// <summary>
/// File containing the instruction
/// </summary>
public string? File { get; set; }
/// <summary>
/// The line number of the instruction
/// </summary>
public int Line { get; set; }
/// <summary>
/// The line preceding the frame line
/// </summary>
public int PreContextLine { get; set; }
/// <summary>
/// Lines of code before the actual error line(s).
/// </summary>
public IEnumerable<string> PreContextCode { get; set; } = Enumerable.Empty<string>();
/// <summary>
/// Line(s) of code responsible for the error.
/// </summary>
public IEnumerable<string> ContextCode { get; set; } = Enumerable.Empty<string>();
/// <summary>
/// Lines of code after the actual error line(s).
/// </summary>
public IEnumerable<string> PostContextCode { get; set; } = Enumerable.Empty<string>();
/// <summary>
/// Specific error details for this stack frame.
/// </summary>
public string? ErrorDetails { get; set; }
}
| StackFrameSourceCodeInfo |
csharp | dotnet__maui | src/Core/src/Handlers/SwipeItemMenuItem/SwipeItemMenuItemHandler.iOS.cs | {
"start": 2615,
"end": 5033
} | partial class ____
{
public override void SetImageSource(UIImage? platformImage)
{
if (Handler?.PlatformView is not UIButton button || Handler?.VirtualView is not ISwipeItemMenuItem item)
return;
var frame = button.Frame;
if (frame == CGRect.Empty)
return;
if (platformImage == null)
{
button.SetImage(null, UIControlState.Normal);
}
else
{
var maxWidth = frame.Width * 0.5f;
var maxHeight = frame.Height * 0.5f;
var resizedImage = MaxResizeSwipeItemIconImage(platformImage, maxWidth, maxHeight);
try
{
button.SetImage(resizedImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
var tintColor = item.GetTextColor();
if (tintColor != null)
button.TintColor = tintColor.ToPlatform();
}
catch (Exception)
{
// UIImage ctor throws on file not found if MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure is true;
Handler.MauiContext?.CreateLogger<SwipeItemMenuItemHandler>()?.LogWarning("Cannot load SwipeItem Icon");
}
}
}
static UIImage MaxResizeSwipeItemIconImage(UIImage sourceImage, nfloat maxWidth, nfloat maxHeight)
{
var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
if (maxResizeFactor > 1)
{
return sourceImage;
}
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
var format = new UIGraphicsImageRendererFormat
{
Opaque = false,
Scale = 0
};
using (var renderer = new UIGraphicsImageRenderer(new CGSize(width, height), format))
{
var resultImage = renderer.CreateImage((UIGraphicsImageRendererContext imageContext) =>
{
var cgcontext = imageContext.CGContext;
// The image is drawn upside down because Core Graphics uses a bottom-left origin,
// whereas UIKit uses a top-left origin. Adjust the coordinate system to align with UIKit's top-left origin.
cgcontext.TranslateCTM(0, (nfloat)height);
cgcontext.ScaleCTM(1, -1);
cgcontext.DrawImage(new CGRect(0, 0, (nfloat)width, (nfloat)height), sourceImage.CGImage);
cgcontext.ScaleCTM(1, -1);
cgcontext.TranslateCTM(0, -(nfloat)height);
});
return resultImage;
}
}
}
| SwipeItemMenuItemImageSourcePartSetter |
csharp | unoplatform__uno | src/Uno.UI.Runtime.Skia.X11/X11_Bindings/x11bindings_X11Structs.cs | {
"start": 31570,
"end": 31652
} | public enum ____
{
JoinMiter = 0,
JoinRound = 1,
JoinBevel = 2
}
| GCJoinStyle |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Equivalency.Specs/TestTypes.cs | {
"start": 12197,
"end": 12263
} | public interface ____
{
int VehicleId { get; }
}
| IReadOnlyVehicle |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Scheduling/MessageSchedulerContext.cs | {
"start": 6104,
"end": 6787
} | interface ____ to send</typeparam>
/// <param name="scheduledTime">The time at which the message should be delivered to the queue</param>
/// <param name="values">The property values to initialize on the interface</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
Task<ScheduledMessage<T>> ScheduleSend<T>(DateTime scheduledTime, object values, IPipe<SendContext<T>> pipe,
CancellationToken cancellationToken = default)
where T : class;
/// <summary>
/// Sends an | type |
csharp | xunit__xunit | src/xunit.v3.assert.tests/Asserts/CollectionAssertsTests.cs | {
"start": 33991,
"end": 35177
} | public class ____
{
[Fact]
public static void AlwaysFalse()
{
var expected = new[] { 1, 2, 3, 4, 5 };
var actual = new List<int> { 1, 2, 3, 4, 5 };
var ex = Record.Exception(() => Assert.Equal(expected, actual, (x, y) => false));
Assert.IsType<EqualException>(ex);
Assert.Equal(
"Assert.Equal() Failure: Collections differ" + Environment.NewLine +
" ↓ (pos 0)" + Environment.NewLine +
"Expected: int[] [1, 2, 3, 4, 5]" + Environment.NewLine +
"Actual: List<int> [1, 2, 3, 4, 5]" + Environment.NewLine +
" ↑ (pos 0)",
ex.Message
);
}
[Fact]
public static void AlwaysTrue()
{
var expected = new[] { 1, 2, 3, 4, 5 };
var actual = new List<int> { 0, 0, 0, 0, 0 };
Assert.Equal(expected, actual, (x, y) => true);
}
// https://github.com/xunit/xunit/issues/2795
[Fact]
public void CollectionItemIsEnumerable()
{
var expected = new List<EnumerableItem> { new(1), new(3) };
var actual = new List<EnumerableItem> { new(0), new(2) };
Assert.Equal(expected, actual, (x, y) => x.Value / 2 == y.Value / 2);
}
| CollectionsWithFunc |
csharp | unoplatform__uno | src/Uno.UI/UI/Input/InputLightDismissEventArgs.cs | {
"start": 65,
"end": 122
} | partial class ____
{
}
}
#endif
| InputLightDismissEventArgs |
csharp | smartstore__Smartstore | src/Smartstore/Imaging/Adapters/ImageSharp/SharpImageFactory.cs | {
"start": 272,
"end": 3987
} | public class ____ : Disposable, IImageFactory
{
private readonly Timer _releaseMemTimer;
public SharpImageFactory(SmartConfiguration appConfig)
{
if (appConfig.ImagingMaxPoolSizeMB > 0)
{
SharpConfiguration.Default.MemoryAllocator = MemoryAllocator.Create(new MemoryAllocatorOptions
{
MaximumPoolSizeMegabytes = appConfig.ImagingMaxPoolSizeMB
});
}
// Release memory pool every 10 minutes
var releaseInterval = TimeSpan.FromMinutes(10);
_releaseMemTimer = new Timer(o => ReleaseMemory(), null, releaseInterval, releaseInterval);
}
public bool IsSupportedImage(string extension)
{
return FindInternalImageFormat(extension) != null;
}
public IImageFormat FindFormatByExtension(string extension)
{
var internalFormat = FindInternalImageFormat(extension);
if (internalFormat != null)
{
return ImageSharpUtility.CreateFormat(internalFormat);
}
return null;
}
public IImageFormat DetectFormat(Stream stream)
{
var internalFormat = Image.DetectFormat(stream);
if (internalFormat != null)
{
return ImageSharpUtility.CreateFormat(internalFormat);
}
return null;
}
public async Task<IImageFormat> DetectFormatAsync(Stream stream)
{
var internalFormat = await CommonHelper.TryAction(() => Image.DetectFormatAsync(stream));
if (internalFormat != null)
{
return ImageSharpUtility.CreateFormat(internalFormat);
}
return null;
}
public IImageInfo DetectInfo(Stream stream)
{
var info = CommonHelper.TryAction(() => Image.Identify(stream));
if (info?.Metadata?.DecodedImageFormat != null)
{
return new SharpImageInfo(info);
}
return null;
}
public async Task<IImageInfo> DetectInfoAsync(Stream stream)
{
var info = await CommonHelper.TryAction(() => Image.IdentifyAsync(stream));
if (info?.Metadata?.DecodedImageFormat != null)
{
return new SharpImageInfo(info);
}
return null;
}
public IProcessableImage Load(string path)
{
var image = Image.Load(path);
return new SharpImage(image);
}
public IProcessableImage Load(Stream stream)
{
var image = Image.Load(stream);
return new SharpImage(image);
}
public async Task<IProcessableImage> LoadAsync(Stream stream)
{
var image = await Image.LoadAsync(stream);
return new SharpImage(image);
}
internal static SixLabors.ImageSharp.Formats.IImageFormat FindInternalImageFormat(string extension)
{
if (extension.IsEmpty())
{
return null;
}
if (SharpConfiguration.Default.ImageFormatsManager.TryFindFormatByFileExtension(extension, out var format))
{
return format;
}
return null;
}
public void ReleaseMemory()
=> SharpConfiguration.Default.MemoryAllocator.ReleaseRetainedResources();
protected override void OnDispose(bool disposing)
{
if (disposing)
_releaseMemTimer.Dispose();
}
}
} | SharpImageFactory |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/FluentValidation/Validators/AbstractComparisonValidator.Partial.cs | {
"start": 87,
"end": 873
} | partial class ____
{
// Migration: comment out GetComparisonValue() to use modified version below:
public IComparable GetComparisonValue(PropertyValidatorContext context) {
if(_valueToCompareFunc != null) {
return (IComparable)_valueToCompareFunc(context.InstanceToValidate);
}
return GetComparableValue(context, ValueToCompare);
}
public IComparable GetComparableValue(PropertyValidatorContext context, object value)
{
if (context.PropertyValue == null || context.PropertyValue.GetType() == value.GetType())
return (IComparable) value;
return (IComparable)value.ConvertTo(context.PropertyValue.GetType());
}
}
} | AbstractComparisonValidator |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs | {
"start": 15598,
"end": 17562
} | public sealed class ____ : EventData
{
/// <summary>
/// The name of the event.
/// </summary>
public const string EventName = EventNamespace + "BeforeOnResourceExecuted";
/// <summary>
/// Initializes a new instance of <see cref="BeforeResourceFilterOnResourceExecutedEventData"/>.
/// </summary>
/// <param name="actionDescriptor">The <see cref="ActionDescriptor"/>.</param>
/// <param name="resourceExecutedContext">The <see cref="ResourceExecutedContext"/>.</param>
/// <param name="filter">The <see cref="IFilterMetadata"/>.</param>
public BeforeResourceFilterOnResourceExecutedEventData(ActionDescriptor actionDescriptor, ResourceExecutedContext resourceExecutedContext, IFilterMetadata filter)
{
ActionDescriptor = actionDescriptor;
ResourceExecutedContext = resourceExecutedContext;
Filter = filter;
}
/// <summary>
/// The action.
/// </summary>
public ActionDescriptor ActionDescriptor { get; }
/// <summary>
/// The context.
/// </summary>
public ResourceExecutedContext ResourceExecutedContext { get; }
/// <summary>
/// The resource filter that will run.
/// </summary>
public IFilterMetadata Filter { get; }
/// <inheritdoc/>
protected override int Count => 3;
/// <inheritdoc/>
protected override KeyValuePair<string, object> this[int index] => index switch
{
0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor),
1 => new KeyValuePair<string, object>(nameof(ResourceExecutedContext), ResourceExecutedContext),
2 => new KeyValuePair<string, object>(nameof(Filter), Filter),
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}
/// <summary>
/// An <see cref="EventData"/> that occurs after <see cref="IResourceFilter.OnResourceExecuted(ResourceExecutedContext)"/>.
/// </summary>
| BeforeResourceFilterOnResourceExecutedEventData |
csharp | JoshClose__CsvHelper | src/CsvHelper/Configuration/Attributes/NewLineAttribute.cs | {
"start": 695,
"end": 1426
} | public class ____ : Attribute, IClassMapper
{
/// The newline string to use. Default is \r\n (CRLF).
/// When writing, this value is always used.
/// When reading, this value is only used if explicitly set.
/// If not set, the parser uses one of \r\n, \r, or \n.
public string NewLine { get; private set; }
/// The newline string to use. Default is \r\n (CRLF).
/// When writing, this value is always used.
/// When reading, this value is only used if explicitly set.
/// If not set, the parser uses one of \r\n, \r, or \n.
public NewLineAttribute(string newLine)
{
NewLine = newLine;
}
/// <inheritdoc />
public void ApplyTo(CsvConfiguration configuration)
{
configuration.NewLine = NewLine;
}
}
| NewLineAttribute |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/test/Data.Sorting.Tests/Expression/QueryableSortVisitorAscTests.cs | {
"start": 4052,
"end": 4125
} | public class ____<T>
{
public T? Bar { get; set; }
}
| Foo |
csharp | grpc__grpc-dotnet | src/Grpc.Core.Api/ClientBase.cs | {
"start": 3408,
"end": 5351
} | class ____
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : this(new UnimplementedCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration)
{
this.configuration = GrpcPreconditions.CheckNotNull(configuration, "configuration");
this.callInvoker = configuration.CreateDecoratedCallInvoker();
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(ChannelBase channel) : this(channel.CreateCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : this(new ClientBaseConfiguration(callInvoker, null))
{
}
/// <summary>
/// Gets the call invoker.
/// </summary>
protected CallInvoker CallInvoker
{
get { return this.callInvoker; }
}
/// <summary>
/// Gets the configuration.
/// </summary>
internal ClientBaseConfiguration Configuration
{
get { return this.configuration; }
}
internal string ServiceNameDebuggerToString()
{
var serviceName = ClientDebuggerHelpers.GetServiceName(GetType());
if (serviceName == null)
{
return string.Empty;
}
return $@"Service = ""{serviceName}"", ";
}
| that |
csharp | open-telemetry__opentelemetry-dotnet | src/OpenTelemetry/Trace/Sampler/ParentBasedSampler.cs | {
"start": 654,
"end": 1924
} | public sealed class ____ : Sampler
{
private readonly Sampler rootSampler;
private readonly Sampler remoteParentSampled;
private readonly Sampler remoteParentNotSampled;
private readonly Sampler localParentSampled;
private readonly Sampler localParentNotSampled;
/// <summary>
/// Initializes a new instance of the <see cref="ParentBasedSampler"/> class.
/// </summary>
/// <param name="rootSampler">The <see cref="Sampler"/> to be called for root span/activity.</param>
public ParentBasedSampler(Sampler rootSampler)
{
Guard.ThrowIfNull(rootSampler);
this.rootSampler = rootSampler;
#pragma warning disable CA1062 // Validate arguments of public methods - needed for netstandard2.1
this.Description = $"ParentBased{{{rootSampler.Description}}}";
#pragma warning restore CA1062 // Validate arguments of public methods - needed for netstandard2.1
this.remoteParentSampled = new AlwaysOnSampler();
this.remoteParentNotSampled = new AlwaysOffSampler();
this.localParentSampled = new AlwaysOnSampler();
this.localParentNotSampled = new AlwaysOffSampler();
}
/// <summary>
/// Initializes a new instance of the <see cref="ParentBasedSampler"/> | ParentBasedSampler |
csharp | AutoMapper__AutoMapper | src/UnitTests/Bug/InitializeNRE.cs | {
"start": 853,
"end": 1038
} | public class ____
{
public string SomeData { get; set; }
public int SomeCount { get; set; }
public ICollection<string> Tags { get; set; }
}
| TestEntity |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/ModelBinding/Validation/ExplicitIndexCollectionValidationStrategy.cs | {
"start": 1346,
"end": 2395
} | internal sealed class ____ : IValidationStrategy
{
/// <summary>
/// Creates a new <see cref="ExplicitIndexCollectionValidationStrategy"/>.
/// </summary>
/// <param name="elementKeys">The keys of collection elements that were used during model binding.</param>
public ExplicitIndexCollectionValidationStrategy(IEnumerable<string> elementKeys)
{
ArgumentNullException.ThrowIfNull(elementKeys);
ElementKeys = elementKeys;
}
/// <summary>
/// Gets the keys of collection elements that were used during model binding.
/// </summary>
public IEnumerable<string> ElementKeys { get; }
/// <inheritdoc />
public IEnumerator<ValidationEntry> GetChildren(
ModelMetadata metadata,
string key,
object model)
{
var enumerator = DefaultCollectionValidationStrategy.Instance.GetEnumeratorForElementType(metadata, model);
return new Enumerator(metadata.ElementMetadata!, key, ElementKeys, enumerator);
}
| ExplicitIndexCollectionValidationStrategy |
csharp | restsharp__RestSharp | src/RestSharp/Parameters/ObjectParser.cs | {
"start": 661,
"end": 3276
} | static class ____ {
public static IEnumerable<ParsedParameter> GetProperties(this object obj, params string[] includedProperties) {
// automatically create parameters from object props
var type = obj.GetType();
var props = type.GetProperties();
var properties = new List<ParsedParameter>();
foreach (var prop in props.Where(x => IsAllowedProperty(x.Name))) {
var val = prop.GetValue(obj, null);
if (val == null) continue;
if (prop.PropertyType.IsArray)
properties.AddRange(GetArray(prop, val));
else
properties.Add(GetValue(prop, val));
}
return properties;
ParsedParameter GetValue(PropertyInfo propertyInfo, object? value) {
var attribute = propertyInfo.GetCustomAttribute<RequestPropertyAttribute>();
var name = attribute?.Name ?? propertyInfo.Name;
var val = ParseValue(attribute?.Format, value);
return new(name, val, attribute?.Encode ?? true);
}
IEnumerable<ParsedParameter> GetArray(PropertyInfo propertyInfo, object? value) {
var elementType = propertyInfo.PropertyType.GetElementType();
var array = (Array)value!;
var attribute = propertyInfo.GetCustomAttribute<RequestPropertyAttribute>();
var name = attribute?.Name ?? propertyInfo.Name;
var queryType = attribute?.ArrayQueryType ?? RequestArrayQueryType.CommaSeparated;
var encode = attribute?.Encode ?? true;
if (array.Length <= 0 || elementType == null) return [new(name, null, encode)];
// convert the array to an array of strings
var values = array
.Cast<object>()
.Select(item => ParseValue(attribute?.Format, item));
return queryType switch {
RequestArrayQueryType.CommaSeparated => [new(name, string.Join(",", values), encode)],
RequestArrayQueryType.ArrayParameters => values.Select(x => new ParsedParameter($"{name}[]", x, encode)),
_ => throw new ArgumentOutOfRangeException()
};
}
bool IsAllowedProperty(string propertyName)
=> includedProperties.Length == 0 || includedProperties.Length > 0 && includedProperties.Contains(propertyName);
string? ParseValue(string? format, object? value) => format == null ? value?.ToString() : string.Format($"{{0:{format}}}", value);
}
}
| ObjectParser |
csharp | mysql-net__MySqlConnector | tests/Conformance.Tests/CommandTests.cs | {
"start": 65,
"end": 209
} | public sealed class ____ : CommandTestBase<DbFactoryFixture>
{
public CommandTests(DbFactoryFixture fixture)
: base(fixture)
{
}
}
| CommandTests |
csharp | dotnet__reactive | AsyncRx.NET/System.Reactive.Async/Linq/Operators/While.cs | {
"start": 309,
"end": 4083
} | public partial class ____
{
// REVIEW: Use a tail-recursive sink.
public static IAsyncObservable<TSource> While<TSource>(Func<bool> condition, IAsyncObservable<TSource> source)
{
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (source == null)
throw new ArgumentNullException(nameof(source));
return Create<TSource>(async observer =>
{
var subscription = new SerialAsyncDisposable();
var o = default(IAsyncObserver<TSource>);
o = AsyncObserver.CreateUnsafe<TSource>(
observer.OnNextAsync,
observer.OnErrorAsync,
MoveNext
);
async ValueTask MoveNext()
{
var b = default(bool);
try
{
b = condition();
}
catch (Exception ex)
{
await observer.OnErrorAsync(ex).ConfigureAwait(false);
return;
}
if (b)
{
var sad = new SingleAssignmentAsyncDisposable();
await subscription.AssignAsync(sad).ConfigureAwait(false);
var d = await source.SubscribeSafeAsync(o).ConfigureAwait(false);
await sad.AssignAsync(d).ConfigureAwait(false);
}
else
{
await observer.OnCompletedAsync().ConfigureAwait(false);
}
}
await MoveNext().ConfigureAwait(false);
return subscription;
});
}
public static IAsyncObservable<TSource> While<TSource>(Func<ValueTask<bool>> condition, IAsyncObservable<TSource> source)
{
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (source == null)
throw new ArgumentNullException(nameof(source));
return Create<TSource>(async observer =>
{
var subscription = new SerialAsyncDisposable();
var o = default(IAsyncObserver<TSource>);
o = AsyncObserver.CreateUnsafe<TSource>(
observer.OnNextAsync,
observer.OnErrorAsync,
MoveNext
);
async ValueTask MoveNext()
{
var b = default(bool);
try
{
b = await condition().ConfigureAwait(false);
}
catch (Exception ex)
{
await observer.OnErrorAsync(ex).ConfigureAwait(false);
return;
}
if (b)
{
var sad = new SingleAssignmentAsyncDisposable();
await subscription.AssignAsync(sad).ConfigureAwait(false);
var d = await source.SubscribeSafeAsync(o).ConfigureAwait(false);
await sad.AssignAsync(d).ConfigureAwait(false);
}
else
{
await observer.OnCompletedAsync().ConfigureAwait(false);
}
}
await MoveNext().ConfigureAwait(false);
return subscription;
});
}
}
}
| AsyncObservable |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.DisplayManagement/Notify/Notifier.cs | {
"start": 131,
"end": 731
} | public class ____ : INotifier
{
private readonly List<NotifyEntry> _entries = [];
private readonly ILogger _logger;
public Notifier(ILogger<Notifier> logger)
{
_logger = logger;
}
public ValueTask AddAsync(NotifyType type, LocalizedHtmlString message)
{
_logger.LogInformation("Notification '{NotificationType}' with message '{NotificationMessage}'", type, message);
_entries.Add(new NotifyEntry { Type = type, Message = message });
return ValueTask.CompletedTask;
}
public IList<NotifyEntry> List()
=> _entries;
}
| Notifier |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Scaffolding/Baselines/BigModel/PrincipalBaseEntityType.cs | {
"start": 810,
"end": 78253
} | public partial class ____
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"Microsoft.EntityFrameworkCore.Scaffolding.CompiledModelTestBase+PrincipalBase",
typeof(CompiledModelTestBase.PrincipalBase),
baseEntityType,
discriminatorProperty: "Discriminator",
discriminatorValue: "PrincipalBase",
derivedTypesCount: 1,
propertyCount: 15,
navigationCount: 1,
skipNavigationCount: 1,
keyCount: 2);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long?),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
afterSaveBehavior: PropertySaveBehavior.Throw);
id.SetGetter(
long? (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Id(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => !(PrincipalBaseUnsafeAccessors.Id(instance).HasValue));
id.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, long? value) =>
{
PrincipalBaseUnsafeAccessors.Id(instance) = value;
return instance;
});
id.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, long? value) =>
{
PrincipalBaseUnsafeAccessors.Id(instance) = value;
return instance;
});
id.SetAccessors(
long? (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Id(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
long? (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Id(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
long? (IInternalEntry entry) => entry.ReadOriginalValue<long?>(id, 0),
long? (IInternalEntry entry) => ((InternalEntityEntry)entry).ReadRelationshipSnapshotValue<long?>(id, 0));
id.SetPropertyIndexes(
index: 0,
originalValueIndex: 0,
shadowIndex: -1,
relationshipIndex: 0,
storeGenerationIndex: -1);
id.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<long>(
bool (long v1, long v2) => v1 == v2,
int (long v) => ((object)v).GetHashCode(),
long (long v) => v),
keyComparer: new ValueComparer<long>(
bool (long v1, long v2) => v1 == v2,
int (long v) => ((object)v).GetHashCode(),
long (long v) => v),
providerValueComparer: new ValueComparer<long>(
bool (long v1, long v2) => v1 == v2,
int (long v) => ((object)v).GetHashCode(),
long (long v) => v),
clrType: typeof(long),
jsonValueReaderWriter: JsonInt64ReaderWriter.Instance);
id.SetCurrentValueComparer(new EntryCurrentValueComparer<long?>(id));
id.SetComparer(new NullableValueComparer<long>(id.TypeMapping.Comparer));
id.SetKeyComparer(new NullableValueComparer<long>(id.TypeMapping.KeyComparer));
var alternateId = runtimeEntityType.AddProperty(
"AlternateId",
typeof(Guid),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("AlternateId", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
propertyAccessMode: PropertyAccessMode.FieldDuringConstruction,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: new Guid("00000000-0000-0000-0000-000000000000"),
jsonValueReaderWriter: JsonGuidReaderWriter.Instance);
alternateId.SetGetter(
Guid (CompiledModelTestBase.PrincipalBase instance) => instance.AlternateId,
bool (CompiledModelTestBase.PrincipalBase instance) => instance.AlternateId == new Guid("00000000-0000-0000-0000-000000000000"));
alternateId.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, Guid value) =>
{
instance.AlternateId = value;
return instance;
});
alternateId.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, Guid value) =>
{
instance.AlternateId = value;
return instance;
});
alternateId.SetAccessors(
Guid (IInternalEntry entry) => ((CompiledModelTestBase.PrincipalBase)(entry.Entity)).AlternateId,
Guid (IInternalEntry entry) => ((CompiledModelTestBase.PrincipalBase)(entry.Entity)).AlternateId,
Guid (IInternalEntry entry) => entry.ReadOriginalValue<Guid>(alternateId, 1),
Guid (IInternalEntry entry) => ((InternalEntityEntry)entry).ReadRelationshipSnapshotValue<Guid>(alternateId, 1));
alternateId.SetPropertyIndexes(
index: 1,
originalValueIndex: 1,
shadowIndex: -1,
relationshipIndex: 1,
storeGenerationIndex: -1);
alternateId.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<Guid>(
bool (Guid v1, Guid v2) => v1 == v2,
int (Guid v) => ((object)v).GetHashCode(),
Guid (Guid v) => v),
keyComparer: new ValueComparer<Guid>(
bool (Guid v1, Guid v2) => v1 == v2,
int (Guid v) => ((object)v).GetHashCode(),
Guid (Guid v) => v),
providerValueComparer: new ValueComparer<Guid>(
bool (Guid v1, Guid v2) => v1 == v2,
int (Guid v) => ((object)v).GetHashCode(),
Guid (Guid v) => v),
clrType: typeof(Guid),
jsonValueReaderWriter: JsonGuidReaderWriter.Instance);
alternateId.SetCurrentValueComparer(new EntryCurrentValueComparer<Guid>(alternateId));
var discriminator = runtimeEntityType.AddProperty(
"Discriminator",
typeof(string),
afterSaveBehavior: PropertySaveBehavior.Throw,
valueGeneratorFactory: new DiscriminatorValueGeneratorFactory().Create);
discriminator.SetAccessors(
string (IInternalEntry entry) => entry.ReadShadowValue<string>(0),
string (IInternalEntry entry) => entry.ReadShadowValue<string>(0),
string (IInternalEntry entry) => entry.ReadOriginalValue<string>(discriminator, 2),
string (IInternalEntry entry) => entry.GetCurrentValue<string>(discriminator));
discriminator.SetPropertyIndexes(
index: 2,
originalValueIndex: 2,
shadowIndex: 0,
relationshipIndex: -1,
storeGenerationIndex: -1);
discriminator.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
keyComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
clrType: typeof(string),
jsonValueReaderWriter: JsonStringReaderWriter.Instance);
var enum1 = runtimeEntityType.AddProperty(
"Enum1",
typeof(CompiledModelTestBase.AnEnum),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("Enum1", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<Enum1>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: (CompiledModelTestBase.AnEnum)0);
enum1.SetGetter(
CompiledModelTestBase.AnEnum (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Enum1(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => object.Equals(((object)(PrincipalBaseUnsafeAccessors.Enum1(instance))), ((object)((CompiledModelTestBase.AnEnum)0L))));
enum1.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AnEnum value) =>
{
PrincipalBaseUnsafeAccessors.Enum1(instance) = value;
return instance;
});
enum1.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AnEnum value) =>
{
PrincipalBaseUnsafeAccessors.Enum1(instance) = value;
return instance;
});
enum1.SetAccessors(
CompiledModelTestBase.AnEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Enum1(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AnEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Enum1(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AnEnum (IInternalEntry entry) => entry.ReadOriginalValue<CompiledModelTestBase.AnEnum>(enum1, 3),
CompiledModelTestBase.AnEnum (IInternalEntry entry) => entry.GetCurrentValue<CompiledModelTestBase.AnEnum>(enum1));
enum1.SetPropertyIndexes(
index: 3,
originalValueIndex: 3,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
enum1.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
keyComparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
providerValueComparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
clrType: typeof(CompiledModelTestBase.AnEnum),
jsonValueReaderWriter: JsonSignedEnumReaderWriter<CompiledModelTestBase.AnEnum>.Instance);
var enum2 = runtimeEntityType.AddProperty(
"Enum2",
typeof(CompiledModelTestBase.AnEnum?),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("Enum2", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<Enum2>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
enum2.SetGetter(
CompiledModelTestBase.AnEnum? (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Enum2(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => !(PrincipalBaseUnsafeAccessors.Enum2(instance).HasValue));
enum2.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AnEnum? value) =>
{
PrincipalBaseUnsafeAccessors.Enum2(instance) = (value == null ? value : ((CompiledModelTestBase.AnEnum? )(((CompiledModelTestBase.AnEnum)value))));
return instance;
});
enum2.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AnEnum? value) =>
{
PrincipalBaseUnsafeAccessors.Enum2(instance) = (value == null ? value : ((CompiledModelTestBase.AnEnum? )(((CompiledModelTestBase.AnEnum)value))));
return instance;
});
enum2.SetAccessors(
CompiledModelTestBase.AnEnum? (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Enum2(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AnEnum? (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Enum2(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AnEnum? (IInternalEntry entry) => entry.ReadOriginalValue<CompiledModelTestBase.AnEnum?>(enum2, 4),
CompiledModelTestBase.AnEnum? (IInternalEntry entry) => entry.GetCurrentValue<CompiledModelTestBase.AnEnum?>(enum2));
enum2.SetPropertyIndexes(
index: 4,
originalValueIndex: 4,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
enum2.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
keyComparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
providerValueComparer: new ValueComparer<CompiledModelTestBase.AnEnum>(
bool (CompiledModelTestBase.AnEnum v1, CompiledModelTestBase.AnEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AnEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AnEnum (CompiledModelTestBase.AnEnum v) => v),
clrType: typeof(CompiledModelTestBase.AnEnum),
jsonValueReaderWriter: JsonSignedEnumReaderWriter<CompiledModelTestBase.AnEnum>.Instance);
enum2.SetComparer(new NullableValueComparer<CompiledModelTestBase.AnEnum>(enum2.TypeMapping.Comparer));
enum2.SetKeyComparer(new NullableValueComparer<CompiledModelTestBase.AnEnum>(enum2.TypeMapping.KeyComparer));
var flagsEnum1 = runtimeEntityType.AddProperty(
"FlagsEnum1",
typeof(CompiledModelTestBase.AFlagsEnum),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("FlagsEnum1", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<FlagsEnum1>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: (CompiledModelTestBase.AFlagsEnum)0);
flagsEnum1.SetGetter(
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.FlagsEnum1(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => object.Equals(((object)(PrincipalBaseUnsafeAccessors.FlagsEnum1(instance))), ((object)((CompiledModelTestBase.AFlagsEnum)0L))));
flagsEnum1.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AFlagsEnum value) =>
{
PrincipalBaseUnsafeAccessors.FlagsEnum1(instance) = value;
return instance;
});
flagsEnum1.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AFlagsEnum value) =>
{
PrincipalBaseUnsafeAccessors.FlagsEnum1(instance) = value;
return instance;
});
flagsEnum1.SetAccessors(
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.FlagsEnum1(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.FlagsEnum1(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => entry.ReadOriginalValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum1, 5),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => entry.GetCurrentValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum1));
flagsEnum1.SetPropertyIndexes(
index: 5,
originalValueIndex: 5,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
flagsEnum1.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
keyComparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
providerValueComparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
clrType: typeof(CompiledModelTestBase.AFlagsEnum),
jsonValueReaderWriter: JsonSignedEnumReaderWriter<CompiledModelTestBase.AFlagsEnum>.Instance);
var flagsEnum2 = runtimeEntityType.AddProperty(
"FlagsEnum2",
typeof(CompiledModelTestBase.AFlagsEnum),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("FlagsEnum2", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<FlagsEnum2>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
propertyAccessMode: PropertyAccessMode.Property,
sentinel: CompiledModelTestBase.AFlagsEnum.B | CompiledModelTestBase.AFlagsEnum.C);
flagsEnum2.SetGetter(
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Get_FlagsEnum2(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => object.Equals(((object)(PrincipalBaseUnsafeAccessors.Get_FlagsEnum2(instance))), ((object)(CompiledModelTestBase.AFlagsEnum.B | CompiledModelTestBase.AFlagsEnum.C))));
flagsEnum2.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AFlagsEnum value) =>
{
PrincipalBaseUnsafeAccessors.Set_FlagsEnum2(instance, value);
return instance;
});
flagsEnum2.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, CompiledModelTestBase.AFlagsEnum value) =>
{
PrincipalBaseUnsafeAccessors.Set_FlagsEnum2(instance, value);
return instance;
});
flagsEnum2.SetAccessors(
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Get_FlagsEnum2(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Get_FlagsEnum2(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => entry.ReadOriginalValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum2, 6),
CompiledModelTestBase.AFlagsEnum (IInternalEntry entry) => entry.GetCurrentValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum2));
flagsEnum2.SetPropertyIndexes(
index: 6,
originalValueIndex: 6,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
flagsEnum2.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
keyComparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
providerValueComparer: new ValueComparer<CompiledModelTestBase.AFlagsEnum>(
bool (CompiledModelTestBase.AFlagsEnum v1, CompiledModelTestBase.AFlagsEnum v2) => object.Equals(((object)v1), ((object)v2)),
int (CompiledModelTestBase.AFlagsEnum v) => ((object)v).GetHashCode(),
CompiledModelTestBase.AFlagsEnum (CompiledModelTestBase.AFlagsEnum v) => v),
clrType: typeof(CompiledModelTestBase.AFlagsEnum),
jsonValueReaderWriter: JsonSignedEnumReaderWriter<CompiledModelTestBase.AFlagsEnum>.Instance);
var refTypeArray = runtimeEntityType.AddProperty(
"RefTypeArray",
typeof(IPAddress[]),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("RefTypeArray", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<RefTypeArray>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
refTypeArray.SetGetter(
IPAddress[] (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeArray(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeArray(instance) == null);
refTypeArray.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IPAddress[] value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeArray(instance) = value;
return instance;
});
refTypeArray.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IPAddress[] value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeArray(instance) = value;
return instance;
});
refTypeArray.SetAccessors(
IPAddress[] (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeArray(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IPAddress[] (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeArray(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IPAddress[] (IInternalEntry entry) => entry.ReadOriginalValue<IPAddress[]>(refTypeArray, 7),
IPAddress[] (IInternalEntry entry) => entry.GetCurrentValue<IPAddress[]>(refTypeArray));
refTypeArray.SetPropertyIndexes(
index: 7,
originalValueIndex: 7,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
refTypeArray.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfReferenceTypesComparer<IPAddress[], IPAddress>(new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v)),
keyComparer: new ListOfReferenceTypesComparer<IPAddress[], IPAddress>(new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<IPAddress>(new JsonCollectionOfReferencesReaderWriter<IPAddress[], IPAddress>(
new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v))))),
jsonValueReaderWriter: new JsonCollectionOfReferencesReaderWriter<IPAddress[], IPAddress>(
new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)))),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v),
keyComparer: new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)),
jsonValueReaderWriter: new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)))));
var refTypeArrayElementType = refTypeArray.SetElementType(typeof(IPAddress));
refTypeArrayElementType.TypeMapping = refTypeArray.TypeMapping.ElementTypeMapping;
var refTypeEnumerable = runtimeEntityType.AddProperty(
"RefTypeEnumerable",
typeof(IEnumerable<string>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("RefTypeEnumerable", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<RefTypeEnumerable>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
refTypeEnumerable.SetGetter(
IEnumerable<string> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeEnumerable(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeEnumerable(instance) == null);
refTypeEnumerable.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IEnumerable<string> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeEnumerable(instance) = value;
return instance;
});
refTypeEnumerable.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IEnumerable<string> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeEnumerable(instance) = value;
return instance;
});
refTypeEnumerable.SetAccessors(
IEnumerable<string> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeEnumerable(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IEnumerable<string> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeEnumerable(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IEnumerable<string> (IInternalEntry entry) => entry.ReadOriginalValue<IEnumerable<string>>(refTypeEnumerable, 8),
IEnumerable<string> (IInternalEntry entry) => entry.GetCurrentValue<IEnumerable<string>>(refTypeEnumerable));
refTypeEnumerable.SetPropertyIndexes(
index: 8,
originalValueIndex: 8,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
refTypeEnumerable.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfReferenceTypesComparer<List<string>, string>(new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v)),
keyComparer: new ListOfReferenceTypesComparer<List<string>, string>(new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<string>(new JsonCollectionOfReferencesReaderWriter<List<string>, string>(
JsonStringReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfReferencesReaderWriter<List<string>, string>(
JsonStringReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
keyComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
clrType: typeof(string),
jsonValueReaderWriter: JsonStringReaderWriter.Instance));
var refTypeEnumerableElementType = refTypeEnumerable.SetElementType(typeof(string));
refTypeEnumerableElementType.TypeMapping = refTypeEnumerable.TypeMapping.ElementTypeMapping;
var refTypeIList = runtimeEntityType.AddProperty(
"RefTypeIList",
typeof(IList<string>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("RefTypeIList", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<RefTypeIList>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
refTypeIList.SetGetter(
IList<string> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeIList(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeIList(instance) == null);
refTypeIList.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IList<string> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeIList(instance) = value;
return instance;
});
refTypeIList.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IList<string> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeIList(instance) = value;
return instance;
});
refTypeIList.SetAccessors(
IList<string> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeIList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IList<string> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeIList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IList<string> (IInternalEntry entry) => entry.ReadOriginalValue<IList<string>>(refTypeIList, 9),
IList<string> (IInternalEntry entry) => entry.GetCurrentValue<IList<string>>(refTypeIList));
refTypeIList.SetPropertyIndexes(
index: 9,
originalValueIndex: 9,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
refTypeIList.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfReferenceTypesComparer<List<string>, string>(new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v)),
keyComparer: new ListOfReferenceTypesComparer<List<string>, string>(new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<string>(new JsonCollectionOfReferencesReaderWriter<List<string>, string>(
JsonStringReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfReferencesReaderWriter<List<string>, string>(
JsonStringReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
keyComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
clrType: typeof(string),
jsonValueReaderWriter: JsonStringReaderWriter.Instance));
var refTypeIListElementType = refTypeIList.SetElementType(typeof(string));
refTypeIListElementType.TypeMapping = refTypeIList.TypeMapping.ElementTypeMapping;
var refTypeList = runtimeEntityType.AddProperty(
"RefTypeList",
typeof(List<IPAddress>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("RefTypeList", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<RefTypeList>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
refTypeList.SetGetter(
List<IPAddress> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeList(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.RefTypeList(instance) == null);
refTypeList.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, List<IPAddress> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeList(instance) = value;
return instance;
});
refTypeList.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, List<IPAddress> value) =>
{
PrincipalBaseUnsafeAccessors.RefTypeList(instance) = value;
return instance;
});
refTypeList.SetAccessors(
List<IPAddress> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
List<IPAddress> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.RefTypeList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
List<IPAddress> (IInternalEntry entry) => entry.ReadOriginalValue<List<IPAddress>>(refTypeList, 10),
List<IPAddress> (IInternalEntry entry) => entry.GetCurrentValue<List<IPAddress>>(refTypeList));
refTypeList.SetPropertyIndexes(
index: 10,
originalValueIndex: 10,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
refTypeList.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfReferenceTypesComparer<List<IPAddress>, IPAddress>(new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v)),
keyComparer: new ListOfReferenceTypesComparer<List<IPAddress>, IPAddress>(new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<IPAddress>(new JsonCollectionOfReferencesReaderWriter<List<IPAddress>, IPAddress>(
new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v))))),
jsonValueReaderWriter: new JsonCollectionOfReferencesReaderWriter<List<IPAddress>, IPAddress>(
new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)))),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v),
keyComparer: new ValueComparer<IPAddress>(
bool (IPAddress v1, IPAddress v2) => v1 == null && v2 == null || v1 != null && v2 != null && v1.Equals(v2),
int (IPAddress v) => ((object)v).GetHashCode(),
IPAddress (IPAddress v) => v),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)),
jsonValueReaderWriter: new JsonConvertedValueReaderWriter<IPAddress, string>(
JsonStringReaderWriter.Instance,
new ValueConverter<IPAddress, string>(
string (IPAddress v) => ((object)v).ToString(),
IPAddress (string v) => IPAddress.Parse(v)))));
var refTypeListElementType = refTypeList.SetElementType(typeof(IPAddress));
refTypeListElementType.TypeMapping = refTypeList.TypeMapping.ElementTypeMapping;
var valueTypeArray = runtimeEntityType.AddProperty(
"ValueTypeArray",
typeof(DateTime[]),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("ValueTypeArray", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<ValueTypeArray>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
valueTypeArray.SetGetter(
DateTime[] (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeArray(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeArray(instance) == null);
valueTypeArray.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, DateTime[] value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeArray(instance) = value;
return instance;
});
valueTypeArray.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, DateTime[] value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeArray(instance) = value;
return instance;
});
valueTypeArray.SetAccessors(
DateTime[] (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeArray(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
DateTime[] (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeArray(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
DateTime[] (IInternalEntry entry) => entry.ReadOriginalValue<DateTime[]>(valueTypeArray, 11),
DateTime[] (IInternalEntry entry) => entry.GetCurrentValue<DateTime[]>(valueTypeArray));
valueTypeArray.SetPropertyIndexes(
index: 11,
originalValueIndex: 11,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
valueTypeArray.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfValueTypesComparer<DateTime[], DateTime>(new ValueComparer<DateTime>(
bool (DateTime v1, DateTime v2) => v1.Equals(v2),
int (DateTime v) => ((object)v).GetHashCode(),
DateTime (DateTime v) => v)),
keyComparer: new ListOfValueTypesComparer<DateTime[], DateTime>(new ValueComparer<DateTime>(
bool (DateTime v1, DateTime v2) => v1.Equals(v2),
int (DateTime v) => ((object)v).GetHashCode(),
DateTime (DateTime v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<DateTime>(new JsonCollectionOfStructsReaderWriter<DateTime[], DateTime>(
JsonDateTimeReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfStructsReaderWriter<DateTime[], DateTime>(
JsonDateTimeReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<DateTime>(
bool (DateTime v1, DateTime v2) => v1.Equals(v2),
int (DateTime v) => ((object)v).GetHashCode(),
DateTime (DateTime v) => v),
keyComparer: new ValueComparer<DateTime>(
bool (DateTime v1, DateTime v2) => v1.Equals(v2),
int (DateTime v) => ((object)v).GetHashCode(),
DateTime (DateTime v) => v),
providerValueComparer: new ValueComparer<DateTime>(
bool (DateTime v1, DateTime v2) => v1.Equals(v2),
int (DateTime v) => ((object)v).GetHashCode(),
DateTime (DateTime v) => v),
clrType: typeof(DateTime),
jsonValueReaderWriter: JsonDateTimeReaderWriter.Instance));
var valueTypeArrayElementType = valueTypeArray.SetElementType(typeof(DateTime));
valueTypeArrayElementType.TypeMapping = valueTypeArray.TypeMapping.ElementTypeMapping;
var valueTypeEnumerable = runtimeEntityType.AddProperty(
"ValueTypeEnumerable",
typeof(IEnumerable<byte>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("ValueTypeEnumerable", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<ValueTypeEnumerable>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
valueTypeEnumerable.SetGetter(
IEnumerable<byte> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(instance) == null);
valueTypeEnumerable.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IEnumerable<byte> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(instance) = value;
return instance;
});
valueTypeEnumerable.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IEnumerable<byte> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(instance) = value;
return instance;
});
valueTypeEnumerable.SetAccessors(
IEnumerable<byte> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IEnumerable<byte> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeEnumerable(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IEnumerable<byte> (IInternalEntry entry) => entry.ReadOriginalValue<IEnumerable<byte>>(valueTypeEnumerable, 12),
IEnumerable<byte> (IInternalEntry entry) => entry.GetCurrentValue<IEnumerable<byte>>(valueTypeEnumerable));
valueTypeEnumerable.SetPropertyIndexes(
index: 12,
originalValueIndex: 12,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
valueTypeEnumerable.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfValueTypesComparer<List<byte>, byte>(new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v)),
keyComparer: new ListOfValueTypesComparer<List<byte>, byte>(new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<byte>(new JsonCollectionOfStructsReaderWriter<List<byte>, byte>(
JsonByteReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfStructsReaderWriter<List<byte>, byte>(
JsonByteReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
keyComparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
providerValueComparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
clrType: typeof(byte),
jsonValueReaderWriter: JsonByteReaderWriter.Instance));
var valueTypeEnumerableElementType = valueTypeEnumerable.SetElementType(typeof(byte));
valueTypeEnumerableElementType.TypeMapping = valueTypeEnumerable.TypeMapping.ElementTypeMapping;
var valueTypeIList = runtimeEntityType.AddProperty(
"ValueTypeIList",
typeof(IList<byte>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("ValueTypeIList", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<ValueTypeIList>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
valueTypeIList.SetGetter(
IList<byte> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeIList(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeIList(instance) == null);
valueTypeIList.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IList<byte> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeIList(instance) = value;
return instance;
});
valueTypeIList.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, IList<byte> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeIList(instance) = value;
return instance;
});
valueTypeIList.SetAccessors(
IList<byte> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeIList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IList<byte> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeIList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
IList<byte> (IInternalEntry entry) => entry.ReadOriginalValue<IList<byte>>(valueTypeIList, 13),
IList<byte> (IInternalEntry entry) => entry.GetCurrentValue<IList<byte>>(valueTypeIList));
valueTypeIList.SetPropertyIndexes(
index: 13,
originalValueIndex: 13,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
valueTypeIList.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfValueTypesComparer<List<byte>, byte>(new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v)),
keyComparer: new ListOfValueTypesComparer<List<byte>, byte>(new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<byte>(new JsonCollectionOfStructsReaderWriter<List<byte>, byte>(
JsonByteReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfStructsReaderWriter<List<byte>, byte>(
JsonByteReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
keyComparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
providerValueComparer: new ValueComparer<byte>(
bool (byte v1, byte v2) => v1 == v2,
int (byte v) => ((int)v),
byte (byte v) => v),
clrType: typeof(byte),
jsonValueReaderWriter: JsonByteReaderWriter.Instance));
var valueTypeIListElementType = valueTypeIList.SetElementType(typeof(byte));
valueTypeIListElementType.TypeMapping = valueTypeIList.TypeMapping.ElementTypeMapping;
var valueTypeList = runtimeEntityType.AddProperty(
"ValueTypeList",
typeof(List<short>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("ValueTypeList", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<ValueTypeList>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
valueTypeList.SetGetter(
List<short> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeList(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.ValueTypeList(instance) == null);
valueTypeList.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, List<short> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeList(instance) = value;
return instance;
});
valueTypeList.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, List<short> value) =>
{
PrincipalBaseUnsafeAccessors.ValueTypeList(instance) = value;
return instance;
});
valueTypeList.SetAccessors(
List<short> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
List<short> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.ValueTypeList(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
List<short> (IInternalEntry entry) => entry.ReadOriginalValue<List<short>>(valueTypeList, 14),
List<short> (IInternalEntry entry) => entry.GetCurrentValue<List<short>>(valueTypeList));
valueTypeList.SetPropertyIndexes(
index: 14,
originalValueIndex: 14,
shadowIndex: -1,
relationshipIndex: -1,
storeGenerationIndex: -1);
valueTypeList.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ListOfValueTypesComparer<List<short>, short>(new ValueComparer<short>(
bool (short v1, short v2) => v1 == v2,
int (short v) => ((int)v),
short (short v) => v)),
keyComparer: new ListOfValueTypesComparer<List<short>, short>(new ValueComparer<short>(
bool (short v1, short v2) => v1 == v2,
int (short v) => ((int)v),
short (short v) => v)),
providerValueComparer: new ValueComparer<string>(
bool (string v1, string v2) => v1 == v2,
int (string v) => ((object)v).GetHashCode(),
string (string v) => v),
converter: new CollectionToJsonStringConverter<short>(new JsonCollectionOfStructsReaderWriter<List<short>, short>(
JsonInt16ReaderWriter.Instance)),
jsonValueReaderWriter: new JsonCollectionOfStructsReaderWriter<List<short>, short>(
JsonInt16ReaderWriter.Instance),
elementMapping: InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<short>(
bool (short v1, short v2) => v1 == v2,
int (short v) => ((int)v),
short (short v) => v),
keyComparer: new ValueComparer<short>(
bool (short v1, short v2) => v1 == v2,
int (short v) => ((int)v),
short (short v) => v),
providerValueComparer: new ValueComparer<short>(
bool (short v1, short v2) => v1 == v2,
int (short v) => ((int)v),
short (short v) => v),
clrType: typeof(short),
jsonValueReaderWriter: JsonInt16ReaderWriter.Instance));
var valueTypeListElementType = valueTypeList.SetElementType(typeof(short));
valueTypeListElementType.TypeMapping = valueTypeList.TypeMapping.ElementTypeMapping;
var key = runtimeEntityType.AddKey(
new[] { id });
var key0 = runtimeEntityType.AddKey(
new[] { id, alternateId });
runtimeEntityType.SetPrimaryKey(key0);
return runtimeEntityType;
}
public static RuntimeSkipNavigation CreateSkipNavigation1(RuntimeEntityType declaringEntityType, RuntimeEntityType targetEntityType, RuntimeEntityType joinEntityType)
{
var skipNavigation = declaringEntityType.AddSkipNavigation(
"Deriveds",
targetEntityType,
joinEntityType.FindForeignKey(
new[] { joinEntityType.FindProperty("PrincipalsId"), joinEntityType.FindProperty("PrincipalsAlternateId") },
declaringEntityType.FindKey(new[] { declaringEntityType.FindProperty("Id"), declaringEntityType.FindProperty("AlternateId") }),
declaringEntityType),
true,
false,
typeof(ICollection<CompiledModelTestBase.PrincipalBase>),
propertyInfo: typeof(CompiledModelTestBase.PrincipalBase).GetProperty("Deriveds", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.PrincipalBase).GetField("<Deriveds>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
var inverse = targetEntityType.FindSkipNavigation("Principals");
if (inverse != null)
{
skipNavigation.Inverse = inverse;
inverse.Inverse = skipNavigation;
}
skipNavigation.SetGetter(
ICollection<CompiledModelTestBase.PrincipalBase> (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Deriveds(instance),
bool (CompiledModelTestBase.PrincipalBase instance) => PrincipalBaseUnsafeAccessors.Deriveds(instance) == null);
skipNavigation.SetSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, ICollection<CompiledModelTestBase.PrincipalBase> value) =>
{
PrincipalBaseUnsafeAccessors.Deriveds(instance) = value;
return instance;
});
skipNavigation.SetMaterializationSetter(
CompiledModelTestBase.PrincipalBase (CompiledModelTestBase.PrincipalBase instance, ICollection<CompiledModelTestBase.PrincipalBase> value) =>
{
PrincipalBaseUnsafeAccessors.Deriveds(instance) = value;
return instance;
});
skipNavigation.SetAccessors(
ICollection<CompiledModelTestBase.PrincipalBase> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Deriveds(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
ICollection<CompiledModelTestBase.PrincipalBase> (IInternalEntry entry) => PrincipalBaseUnsafeAccessors.Deriveds(((CompiledModelTestBase.PrincipalBase)(entry.Entity))),
null,
ICollection<CompiledModelTestBase.PrincipalBase> (IInternalEntry entry) => entry.GetCurrentValue<ICollection<CompiledModelTestBase.PrincipalBase>>(skipNavigation));
skipNavigation.SetPropertyIndexes(
index: 1,
originalValueIndex: -1,
shadowIndex: -1,
relationshipIndex: 3,
storeGenerationIndex: -1);
skipNavigation.SetCollectionAccessor<CompiledModelTestBase.PrincipalBase, ICollection<CompiledModelTestBase.PrincipalBase>, CompiledModelTestBase.PrincipalBase>(
ICollection<CompiledModelTestBase.PrincipalBase> (CompiledModelTestBase.PrincipalBase entity) => PrincipalBaseUnsafeAccessors.Deriveds(entity),
(CompiledModelTestBase.PrincipalBase entity, ICollection<CompiledModelTestBase.PrincipalBase> collection) => PrincipalBaseUnsafeAccessors.Deriveds(entity) = ((ICollection<CompiledModelTestBase.PrincipalBase>)collection),
(CompiledModelTestBase.PrincipalBase entity, ICollection<CompiledModelTestBase.PrincipalBase> collection) => PrincipalBaseUnsafeAccessors.Deriveds(entity) = ((ICollection<CompiledModelTestBase.PrincipalBase>)collection),
ICollection<CompiledModelTestBase.PrincipalBase> (CompiledModelTestBase.PrincipalBase entity, Action<CompiledModelTestBase.PrincipalBase, ICollection<CompiledModelTestBase.PrincipalBase>> setter) => ClrCollectionAccessorFactory.CreateAndSetHashSet<CompiledModelTestBase.PrincipalBase, ICollection<CompiledModelTestBase.PrincipalBase>, CompiledModelTestBase.PrincipalBase>(entity, setter),
ICollection<CompiledModelTestBase.PrincipalBase> () => ((ICollection<CompiledModelTestBase.PrincipalBase>)(((ICollection<CompiledModelTestBase.PrincipalBase>)(new HashSet<CompiledModelTestBase.PrincipalBase>(ReferenceEqualityComparer.Instance))))));
return skipNavigation;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
var id = runtimeEntityType.FindProperty("Id");
var alternateId = runtimeEntityType.FindProperty("AlternateId");
var discriminator = runtimeEntityType.FindProperty("Discriminator");
var enum1 = runtimeEntityType.FindProperty("Enum1");
var enum2 = runtimeEntityType.FindProperty("Enum2");
var flagsEnum1 = runtimeEntityType.FindProperty("FlagsEnum1");
var flagsEnum2 = runtimeEntityType.FindProperty("FlagsEnum2");
var refTypeArray = runtimeEntityType.FindProperty("RefTypeArray");
var refTypeEnumerable = runtimeEntityType.FindProperty("RefTypeEnumerable");
var refTypeIList = runtimeEntityType.FindProperty("RefTypeIList");
var refTypeList = runtimeEntityType.FindProperty("RefTypeList");
var valueTypeArray = runtimeEntityType.FindProperty("ValueTypeArray");
var valueTypeEnumerable = runtimeEntityType.FindProperty("ValueTypeEnumerable");
var valueTypeIList = runtimeEntityType.FindProperty("ValueTypeIList");
var valueTypeList = runtimeEntityType.FindProperty("ValueTypeList");
var key = runtimeEntityType.FindKey(new[] { id });
key.SetPrincipalKeyValueFactory(KeyValueFactoryFactory.CreateSimpleNullableFactory<long?, long>(key));
key.SetIdentityMapFactory(IdentityMapFactoryFactory.CreateFactory<long?>(key));
var key0 = runtimeEntityType.FindKey(new[] { id, alternateId });
key0.SetPrincipalKeyValueFactory(KeyValueFactoryFactory.CreateCompositeFactory(key0));
key0.SetIdentityMapFactory(IdentityMapFactoryFactory.CreateFactory<IReadOnlyList<object>>(key0));
var owned = runtimeEntityType.FindNavigation("Owned");
var deriveds = runtimeEntityType.FindSkipNavigation("Deriveds");
runtimeEntityType.SetOriginalValuesFactory(
ISnapshot (IInternalEntry source) =>
{
var structuralType8 = ((CompiledModelTestBase.PrincipalBase)(source.Entity));
return ((ISnapshot)(new Snapshot<long?, Guid, string, CompiledModelTestBase.AnEnum, CompiledModelTestBase.AnEnum?, CompiledModelTestBase.AFlagsEnum, CompiledModelTestBase.AFlagsEnum, IPAddress[], IEnumerable<string>, IList<string>, List<IPAddress>, DateTime[], IEnumerable<byte>, IList<byte>, List<short>>((source.GetCurrentValue<long?>(id) == null ? null : ((ValueComparer<long?>)(((IProperty)id).GetValueComparer())).Snapshot(source.GetCurrentValue<long?>(id))), ((ValueComparer<Guid>)(((IProperty)alternateId).GetValueComparer())).Snapshot(source.GetCurrentValue<Guid>(alternateId)), (source.GetCurrentValue<string>(discriminator) == null ? null : ((ValueComparer<string>)(((IProperty)discriminator).GetValueComparer())).Snapshot(source.GetCurrentValue<string>(discriminator))), ((ValueComparer<CompiledModelTestBase.AnEnum>)(((IProperty)enum1).GetValueComparer())).Snapshot(source.GetCurrentValue<CompiledModelTestBase.AnEnum>(enum1)), (source.GetCurrentValue<CompiledModelTestBase.AnEnum?>(enum2) == null ? null : ((ValueComparer<CompiledModelTestBase.AnEnum?>)(((IProperty)enum2).GetValueComparer())).Snapshot(source.GetCurrentValue<CompiledModelTestBase.AnEnum?>(enum2))), ((ValueComparer<CompiledModelTestBase.AFlagsEnum>)(((IProperty)flagsEnum1).GetValueComparer())).Snapshot(source.GetCurrentValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum1)), ((ValueComparer<CompiledModelTestBase.AFlagsEnum>)(((IProperty)flagsEnum2).GetValueComparer())).Snapshot(source.GetCurrentValue<CompiledModelTestBase.AFlagsEnum>(flagsEnum2)), (((object)(source.GetCurrentValue<IPAddress[]>(refTypeArray))) == null ? null : ((IPAddress[])(((ValueComparer<object>)(((IProperty)refTypeArray).GetValueComparer())).Snapshot(((object)(source.GetCurrentValue<IPAddress[]>(refTypeArray))))))), (((object)(source.GetCurrentValue<IEnumerable<string>>(refTypeEnumerable))) == null ? null : ((IEnumerable<string>)(((ValueComparer<object>)(((IProperty)refTypeEnumerable).GetValueComparer())).Snapshot(((object)(source.GetCurrentValue<IEnumerable<string>>(refTypeEnumerable))))))), (((object)(source.GetCurrentValue<IList<string>>(refTypeIList))) == null ? null : ((IList<string>)(((ValueComparer<object>)(((IProperty)refTypeIList).GetValueComparer())).Snapshot(((object)(source.GetCurrentValue<IList<string>>(refTypeIList))))))), (((object)(source.GetCurrentValue<List<IPAddress>>(refTypeList))) == null ? null : ((List<IPAddress>)(((ValueComparer<object>)(((IProperty)refTypeList).GetValueComparer())).Snapshot(((object)(source.GetCurrentValue<List<IPAddress>>(refTypeList))))))), (((IEnumerable<DateTime>)(source.GetCurrentValue<DateTime[]>(valueTypeArray))) == null ? null : ((DateTime[])(((ValueComparer<IEnumerable<DateTime>>)(((IProperty)valueTypeArray).GetValueComparer())).Snapshot(((IEnumerable<DateTime>)(source.GetCurrentValue<DateTime[]>(valueTypeArray))))))), (source.GetCurrentValue<IEnumerable<byte>>(valueTypeEnumerable) == null ? null : ((ValueComparer<IEnumerable<byte>>)(((IProperty)valueTypeEnumerable).GetValueComparer())).Snapshot(source.GetCurrentValue<IEnumerable<byte>>(valueTypeEnumerable))), (((IEnumerable<byte>)(source.GetCurrentValue<IList<byte>>(valueTypeIList))) == null ? null : ((IList<byte>)(((ValueComparer<IEnumerable<byte>>)(((IProperty)valueTypeIList).GetValueComparer())).Snapshot(((IEnumerable<byte>)(source.GetCurrentValue<IList<byte>>(valueTypeIList))))))), (((IEnumerable<short>)(source.GetCurrentValue<List<short>>(valueTypeList))) == null ? null : ((List<short>)(((ValueComparer<IEnumerable<short>>)(((IProperty)valueTypeList).GetValueComparer())).Snapshot(((IEnumerable<short>)(source.GetCurrentValue<List<short>>(valueTypeList))))))))));
});
runtimeEntityType.SetStoreGeneratedValuesFactory(
ISnapshot () => Snapshot.Empty);
runtimeEntityType.SetTemporaryValuesFactory(
ISnapshot (IInternalEntry source) => Snapshot.Empty);
runtimeEntityType.SetShadowValuesFactory(
ISnapshot (IDictionary<string, object> source) => ((ISnapshot)(new Snapshot<string>((source.ContainsKey("Discriminator") ? ((string)(source["Discriminator"])) : null)))));
runtimeEntityType.SetEmptyShadowValuesFactory(
ISnapshot () => ((ISnapshot)(new Snapshot<string>(default(string)))));
runtimeEntityType.SetRelationshipSnapshotFactory(
ISnapshot (IInternalEntry source) =>
{
var structuralType8 = ((CompiledModelTestBase.PrincipalBase)(source.Entity));
return ((ISnapshot)(new Snapshot<long?, Guid, object, object>((source.GetCurrentValue<long?>(id) == null ? null : ((ValueComparer<long?>)(((IProperty)id).GetKeyValueComparer())).Snapshot(source.GetCurrentValue<long?>(id))), ((ValueComparer<Guid>)(((IProperty)alternateId).GetKeyValueComparer())).Snapshot(source.GetCurrentValue<Guid>(alternateId)), source.GetCurrentValue<CompiledModelTestBase.OwnedType>(owned), SnapshotFactoryFactory.SnapshotCollection(source.GetCurrentValue<ICollection<CompiledModelTestBase.PrincipalBase>>(deriveds)))));
});
runtimeEntityType.SetCounts(new PropertyCounts(
propertyCount: 15,
navigationCount: 2,
complexPropertyCount: 0,
complexCollectionCount: 0,
originalValueCount: 15,
shadowCount: 1,
relationshipCount: 4,
storeGeneratedCount: 0));
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
| PrincipalBaseEntityType |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/JsonTypesTestBase.cs | {
"start": 152292,
"end": 153009
} | protected class ____
{
public List<ulong>[] Prop { get; set; } = null!;
}
[ConditionalTheory, InlineData("""{"Prop":[["AAEC","AQ==","TQ=="],[],["Tg=="]]}""")]
public virtual Task Can_read_write_array_of_list_of_binary_JSON_values(string expected)
=> Can_read_and_write_JSON_value<BinaryListArrayType, List<byte[]>[]>(
nameof(BinaryListArrayType.Prop),
[
[
new byte[] { 0, 1, 2 },
new byte[] { 1 },
new byte[] { 77 }
],
[],
[new byte[] { 78 }]
],
expected,
mappedCollection: true);
| ULongListArrayType |
csharp | ChilliCream__graphql-platform | src/HotChocolate/MongoDb/test/Data.MongoDb.Filters.Tests/MongoDbFilterVisitorEnumTests.cs | {
"start": 191,
"end": 9045
} | public class ____
: SchemaCache
, IClassFixture<MongoResource>
{
private static readonly Foo[] s_fooEntities =
[
new() { BarEnum = FooEnum.BAR },
new() { BarEnum = FooEnum.BAZ },
new() { BarEnum = FooEnum.FOO },
new() { BarEnum = FooEnum.QUX }
];
private static readonly FooNullable[] s_fooNullableEntities =
[
new() { BarEnum = FooEnum.BAR },
new() { BarEnum = FooEnum.BAZ },
new() { BarEnum = FooEnum.FOO },
new() { BarEnum = null },
new() { BarEnum = FooEnum.QUX }
];
public MongoDbFilterVisitorEnumTests(MongoResource resource)
{
Init(resource);
}
[Fact]
public async Task Create_EnumEqual_Expression()
{
// arrange
var tester = CreateSchema<Foo, FooFilterType>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: BAR } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: FOO } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: null } }) { barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BAR")
.AddResult(res2, "FOO")
.AddResult(res3, "null")
.MatchAsync();
}
[Fact]
public async Task Create_EnumNotEqual_Expression()
{
// arrange
var tester = CreateSchema<Foo, FooFilterType>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: BAR } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: FOO } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: null } }){ barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BAR")
.AddResult(res2, "FOO")
.AddResult(res3, "null")
.MatchAsync();
}
[Fact]
public async Task Create_EnumIn_Expression()
{
// arrange
var tester = CreateSchema<Foo, FooFilterType>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ BAR FOO ]}}){ barEnum}}")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ FOO ]}}){ barEnum}}")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ null FOO ]}}){ barEnum}}")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BarAndFoo")
.AddResult(res2, "FOO")
.AddResult(res3, "nullAndFoo")
.MatchAsync();
}
[Fact]
public async Task Create_EnumNotIn_Expression()
{
// arrange
var tester = CreateSchema<Foo, FooFilterType>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ BAR FOO ] } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ FOO ] } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ null FOO ] } }) { barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BarAndFoo")
.AddResult(res2, "FOO")
.AddResult(res3, "nullAndFoo")
.MatchAsync();
}
[Fact]
public async Task Create_NullableEnumEqual_Expression()
{
// arrange
var tester = CreateSchema<FooNullable, FooNullableFilterType>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: BAR } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: FOO } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { eq: null } }){ barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BAR")
.AddResult(res2, "FOO")
.AddResult(res3, "null")
.MatchAsync();
}
[Fact]
public async Task Create_NullableEnumNotEqual_Expression()
{
// arrange
var tester = CreateSchema<FooNullable, FooNullableFilterType>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: BAR } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: FOO } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { neq: null } }) { barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BAR")
.AddResult(res2, "FOO")
.AddResult(res3, "null")
.MatchAsync();
}
[Fact]
public async Task Create_NullableEnumIn_Expression()
{
// arrange
var tester = CreateSchema<FooNullable, FooNullableFilterType>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ BAR FOO ] } }) { barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ FOO ] } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { in: [ null FOO ] } }) { barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BarAndFoo")
.AddResult(res2, "FOO")
.AddResult(res3, "nullAndFoo")
.MatchAsync();
}
[Fact]
public async Task Create_NullableEnumNotIn_Expression()
{
// arrange
var tester = CreateSchema<FooNullable, FooNullableFilterType>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ BAR FOO ] } }){ barEnum } }")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ FOO ] } }) { barEnum } }")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ root(where: { barEnum: { nin: [ null FOO ] } }) { barEnum } }")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "BarAndFoo")
.AddResult(res2, "FOO")
.AddResult(res3, "nullAndFoo")
.MatchAsync();
}
| MongoDbFilterVisitorEnumTests |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.Dapper/Dapper-Extensions/DapperImplementor.cs | {
"start": 5334,
"end": 6272
} | public class ____ : IDapperImplementor
{
private static readonly Dictionary<Type, IList<IProjection>> ColsBuffer = new Dictionary<Type, IList<IProjection>>();
public DapperImplementor(ISqlGenerator sqlGenerator)
{
SqlGenerator = sqlGenerator;
}
public ISqlGenerator SqlGenerator { get; }
public string LastExecutedCommand { get; protected set; }
public T Get<T>(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout, IList<IReferenceMap> includedProperties = null)
{
return (T)InternalGet<T>(connection, id, transaction, commandTimeout, null, includedProperties);
}
public TOut GetPartial<TIn, TOut>(IDbConnection connection, Expression<Func<TIn, TOut>> func, dynamic id, IDbTransaction transaction, int? commandTimeout, IList<IReferenceMap> includedProperties = null) where TIn : | DapperImplementor |
csharp | microsoft__PowerToys | src/settings-ui/Settings.UI/ViewModels/GeneralViewModel.cs | {
"start": 1154,
"end": 1219
} | public partial class ____ : Observable
{
| GeneralViewModel |
csharp | microsoft__semantic-kernel | dotnet/src/Agents/UnitTests/OpenAI/OpenAIAssistantAgentTests.cs | {
"start": 691,
"end": 35721
} | public sealed class ____ : IDisposable
{
private readonly HttpMessageHandlerStub _messageHandlerStub;
private readonly HttpClient _httpClient;
private readonly Kernel _emptyKernel;
/// <summary>
/// Verify invocation via <see cref="AgentGroupChat"/>.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentGroupChatAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Single(messages[0].Items);
Assert.IsType<Microsoft.SemanticKernel.TextContent>(messages[0].Items[0]);
// Arrange
this.SetupResponse(HttpStatusCode.OK, OpenAIAssistantResponseContent.DeleteThread);
// Act
await chat.ResetAsync();
// Assert
Assert.Empty(this._messageHandlerStub.ResponseQueue);
}
/// <summary>
/// Verify direct invocation of <see cref="OpenAIAssistantAgent"/> using <see cref="AgentThread"/>.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentInvokeWithThreadAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
AgentResponseItem<ChatMessageContent>[] messages = await agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi")).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Single(messages[0].Message.Items);
Assert.IsType<Microsoft.SemanticKernel.TextContent>(messages[0].Message.Items[0]);
Assert.Equal("Hello, how can I help you?", messages[0].Message.Content);
}
/// <summary>
/// Verify direct invocation of <see cref="OpenAIAssistantAgent"/> using <see cref="AgentThread"/>.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentInvokeMultipleMessagesWithThreadAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hello"),
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage("How can I help you?"));
// Act
AgentResponseItem<ChatMessageContent>[] messages = await agent.InvokeAsync(
[
new ChatMessageContent(AuthorRole.Assistant, "Hello"),
new ChatMessageContent(AuthorRole.User, "Hi")
]).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Single(messages[0].Message.Items);
Assert.IsType<Microsoft.SemanticKernel.TextContent>(messages[0].Message.Items[0]);
Assert.Equal("How can I help you?", messages[0].Message.Content);
}
/// <summary>
/// Verify direct streaming invocation of <see cref="OpenAIAssistantAgent"/> using <see cref="AgentThread"/>.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentInvokeStreamingWithThreadAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Streaming.Response(
[
OpenAIAssistantResponseContent.Streaming.CreateRun("created"),
OpenAIAssistantResponseContent.Streaming.CreateRun("queued"),
OpenAIAssistantResponseContent.Streaming.CreateRun("in_progress"),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("Hello, "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("how can I "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("help you?"),
OpenAIAssistantResponseContent.Streaming.CreateRun("completed"),
OpenAIAssistantResponseContent.Streaming.Done
]),
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
Task OnIntermediateMessage(ChatMessageContent message)
{
// Assert intermediate messages
Assert.NotNull(message);
Assert.Equal("Hello, how can I help you?", message.Content);
return Task.CompletedTask;
}
AgentResponseItem<StreamingChatMessageContent>[] messages = await agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, "Hi"), options: new() { OnIntermediateMessage = OnIntermediateMessage }).ToArrayAsync();
// Assert
Assert.Equal(3, messages.Length);
var combinedMessage = string.Concat(messages.Select(x => x.Message.Content));
Assert.Equal("Hello, how can I help you?", combinedMessage);
}
/// <summary>
/// Verify complex chat interaction across multiple states.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentChatTextMessageWithAnnotationAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessageWithAnnotation);
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Equal(2, messages[0].Items.Count);
Assert.NotNull(messages[0].Items.SingleOrDefault(c => c is Microsoft.SemanticKernel.TextContent));
Assert.NotNull(messages[0].Items.SingleOrDefault(c => c is AnnotationContent));
}
/// <summary>
/// Verify complex chat interaction across multiple states.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentChatImageMessageAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetImageMessage);
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Single(messages[0].Items);
Assert.IsType<FileReferenceContent>(messages[0].Items[0]);
}
/// <summary>
/// Verify complex chat interaction across multiple states.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentGetMessagesAsync()
{
// Arrange: Create agent
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
// Initialize agent channel
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
// Arrange: Setup messages
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.ListMessagesPageMore,
OpenAIAssistantResponseContent.ListMessagesPageMore,
OpenAIAssistantResponseContent.ListMessagesPageFinal);
// Act: Get messages
messages = await chat.GetChatMessagesAsync(agent).ToArrayAsync();
// Assert
Assert.Equal(5, messages.Length);
}
/// <summary>
/// Verify complex chat interaction across multiple states.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentAddMessagesAsync()
{
// Arrange: Create agent
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
// Initialize agent channel
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
// Arrange
chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, "hi"));
// Act
messages = await chat.GetChatMessagesAsync().ToArrayAsync();
// Assert
Assert.Equal(2, messages.Length);
}
/// <summary>
/// Verify ability to list agent definitions.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentWithFunctionCallAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MyPlugin>();
agent.Kernel.Plugins.Add(plugin);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.PendingRun,
OpenAIAssistantResponseContent.Run.ToolSteps,
OpenAIAssistantResponseContent.ToolResponse,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
AgentGroupChat chat = new();
// Act
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
// Assert
Assert.Single(messages);
Assert.Single(messages[0].Items);
Assert.IsType<Microsoft.SemanticKernel.TextContent>(messages[0].Items[0]);
}
/// <summary>
/// Verify that InvalidOperationException is thrown when UseImmutableKernel is false and AIFunctions exist.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentThrowsWhenUseImmutableKernelFalseWithAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = false; // Explicitly set to false
// Initialize agent channel
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread);
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync());
Assert.NotNull(exception);
}
/// <summary>
/// Verify that InvalidOperationException is thrown when UseImmutableKernel is default (false) and AIFunctions exist.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentThrowsWhenUseImmutableKernelDefaultWithAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
// UseImmutableKernel not set, should default to false
// Initialize agent channel
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage());
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread);
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync());
Assert.NotNull(exception);
}
/// <summary>
/// Verify that kernel remains immutable when UseImmutableKernel is true.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentKernelImmutabilityWhenUseImmutableKernelTrueAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = true;
var originalKernel = agent.Kernel;
var originalPluginCount = originalKernel.Plugins.Count;
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
AgentResponseItem<ChatMessageContent>[] result = await agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync();
// Assert
Assert.Single(result);
// Verify original kernel was not modified
Assert.Equal(originalPluginCount, originalKernel.Plugins.Count);
// The kernel should remain unchanged since UseImmutableKernel=true creates a clone
Assert.Same(originalKernel, agent.Kernel);
}
/// <summary>
/// Verify that mutable kernel behavior works when UseImmutableKernel is false and no AIFunctions exist.
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentMutableKernelWhenUseImmutableKernelFalseNoAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = false;
var originalKernel = agent.Kernel;
var originalPluginCount = originalKernel.Plugins.Count;
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [] // Empty AIFunctions list
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Run.CreateRun,
OpenAIAssistantResponseContent.Run.CompletedRun,
OpenAIAssistantResponseContent.Run.MessageSteps,
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
AgentResponseItem<ChatMessageContent>[] result = await agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync();
// Assert
Assert.Single(result);
// Verify the same kernel instance is still being used (mutable behavior)
Assert.Same(originalKernel, agent.Kernel);
}
/// <summary>
/// Verify that InvalidOperationException is thrown when UseImmutableKernel is false and AIFunctions exist (streaming).
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentStreamingThrowsWhenUseImmutableKernelFalseWithAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = false; // Explicitly set to false
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Streaming.Response(
[
OpenAIAssistantResponseContent.Streaming.CreateRun("created"),
OpenAIAssistantResponseContent.Streaming.CreateRun("queued"),
OpenAIAssistantResponseContent.Streaming.CreateRun("in_progress"),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("Hello, "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("how can I "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("help you?"),
OpenAIAssistantResponseContent.Streaming.CreateRun("completed"),
OpenAIAssistantResponseContent.Streaming.Done
]),
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread);
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync());
Assert.NotNull(exception);
}
/// <summary>
/// Verify that InvalidOperationException is thrown when UseImmutableKernel is default (false) and AIFunctions exist (streaming).
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentStreamingThrowsWhenUseImmutableKernelDefaultWithAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
// UseImmutableKernel not set, should default to false
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Streaming.Response(
[
OpenAIAssistantResponseContent.Streaming.CreateRun("created"),
OpenAIAssistantResponseContent.Streaming.CreateRun("queued"),
OpenAIAssistantResponseContent.Streaming.CreateRun("in_progress"),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("Hello, "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("how can I "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("help you?"),
OpenAIAssistantResponseContent.Streaming.CreateRun("completed"),
OpenAIAssistantResponseContent.Streaming.Done
]),
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread);
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync());
Assert.NotNull(exception);
}
/// <summary>
/// Verify that kernel remains immutable when UseImmutableKernel is true (streaming).
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentStreamingKernelImmutabilityWhenUseImmutableKernelTrueAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = true;
var originalKernel = agent.Kernel;
var originalPluginCount = originalKernel.Plugins.Count;
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [new TestAIFunction("TestFunction", "Test function description")]
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Streaming.Response(
[
OpenAIAssistantResponseContent.Streaming.CreateRun("created"),
OpenAIAssistantResponseContent.Streaming.CreateRun("queued"),
OpenAIAssistantResponseContent.Streaming.CreateRun("in_progress"),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("Hello, "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("how can I "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("help you?"),
OpenAIAssistantResponseContent.Streaming.CreateRun("completed"),
OpenAIAssistantResponseContent.Streaming.Done
]),
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
AgentResponseItem<StreamingChatMessageContent>[] result = await agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync();
// Assert
Assert.True(result.Length > 0);
// Verify original kernel was not modified
Assert.Equal(originalPluginCount, originalKernel.Plugins.Count);
// The kernel should remain unchanged since UseImmutableKernel=true creates a clone
Assert.Same(originalKernel, agent.Kernel);
}
/// <summary>
/// Verify that mutable kernel behavior works when UseImmutableKernel is false and no AIFunctions exist (streaming).
/// </summary>
[Fact]
public async Task VerifyOpenAIAssistantAgentStreamingMutableKernelWhenUseImmutableKernelFalseNoAIFunctionsAsync()
{
// Arrange
OpenAIAssistantAgent agent = await this.CreateAgentAsync();
agent.UseImmutableKernel = false;
var originalKernel = agent.Kernel;
var originalPluginCount = originalKernel.Plugins.Count;
var mockAIContextProvider = new Mock<AIContextProvider>();
var aiContext = new AIContext
{
AIFunctions = [] // Empty AIFunctions list
};
mockAIContextProvider.Setup(p => p.ModelInvokingAsync(It.IsAny<ICollection<ChatMessage>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(aiContext);
var thread = new OpenAIAssistantAgentThread(agent.Client);
thread.AIContextProviders.Add(mockAIContextProvider.Object);
this.SetupResponses(
HttpStatusCode.OK,
OpenAIAssistantResponseContent.CreateThread,
// Create message response
OpenAIAssistantResponseContent.GetTextMessage("Hi"),
OpenAIAssistantResponseContent.Streaming.Response(
[
OpenAIAssistantResponseContent.Streaming.CreateRun("created"),
OpenAIAssistantResponseContent.Streaming.CreateRun("queued"),
OpenAIAssistantResponseContent.Streaming.CreateRun("in_progress"),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("Hello, "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("how can I "),
OpenAIAssistantResponseContent.Streaming.DeltaMessage("help you?"),
OpenAIAssistantResponseContent.Streaming.CreateRun("completed"),
OpenAIAssistantResponseContent.Streaming.Done
]),
OpenAIAssistantResponseContent.GetTextMessage("Hello, how can I help you?"));
// Act
AgentResponseItem<StreamingChatMessageContent>[] result = await agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, "Hi"), thread: thread).ToArrayAsync();
// Assert
Assert.True(result.Length > 0);
// Verify the same kernel instance is still being used (mutable behavior)
Assert.Same(originalKernel, agent.Kernel);
}
/// <inheritdoc/>
public void Dispose()
{
this._messageHandlerStub.Dispose();
this._httpClient.Dispose();
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenAIAssistantAgentTests"/> class.
/// </summary>
public OpenAIAssistantAgentTests()
{
this._messageHandlerStub = new HttpMessageHandlerStub();
this._httpClient = new HttpClient(this._messageHandlerStub, disposeHandler: false);
this._emptyKernel = new Kernel();
}
private static void ValidateAgentDefinition(OpenAIAssistantAgent agent, OpenAIAssistantDefinition expectedConfig)
{
ValidateAgent(agent, expectedConfig.Name, expectedConfig.Instructions, expectedConfig.Description, expectedConfig);
}
private static void ValidateAgentDefinition(OpenAIAssistantAgent agent, OpenAIAssistantCapabilities expectedConfig, PromptTemplateConfig templateConfig)
{
ValidateAgent(agent, templateConfig.Name, templateConfig.Template, templateConfig.Description, expectedConfig);
}
private static void ValidateAgent(
OpenAIAssistantAgent agent,
string? expectedName,
string? expectedInstructions,
string? expectedDescription,
OpenAIAssistantCapabilities expectedConfig)
{
// Verify fundamental state
Assert.NotNull(agent);
Assert.NotNull(agent.Id);
Assert.NotNull(agent.Definition);
Assert.Equal(expectedConfig.ModelId, agent.Definition.Model);
// Verify core properties
Assert.Equal(expectedInstructions ?? string.Empty, agent.Instructions);
Assert.Equal(expectedName ?? string.Empty, agent.Name);
Assert.Equal(expectedDescription ?? string.Empty, agent.Description);
// Verify options
Assert.Equal(expectedConfig.Temperature, agent.Definition.Temperature);
Assert.Equal(expectedConfig.TopP, agent.Definition.NucleusSamplingFactor);
// Verify tool definitions
int expectedToolCount = 0;
bool hasCodeInterpreter = false;
if (expectedConfig.EnableCodeInterpreter)
{
hasCodeInterpreter = true;
++expectedToolCount;
}
Assert.Equal(hasCodeInterpreter, agent.Definition.Tools.OfType<CodeInterpreterToolDefinition>().Any());
bool hasFileSearch = false;
if (expectedConfig.EnableFileSearch)
{
hasFileSearch = true;
++expectedToolCount;
}
Assert.Equal(hasFileSearch, agent.Definition.Tools.OfType<FileSearchToolDefinition>().Any());
Assert.Equal(expectedToolCount, agent.Definition.Tools.Count);
// Verify metadata
Assert.NotNull(agent.Definition.Metadata);
if (expectedConfig.ExecutionOptions == null)
{
Assert.Equal(expectedConfig.Metadata ?? new Dictionary<string, string>(), agent.Definition.Metadata);
}
else // Additional metadata present when execution options are defined
{
Assert.Equal((expectedConfig.Metadata?.Count ?? 0) + 1, agent.Definition.Metadata.Count);
if (expectedConfig.Metadata != null)
{
foreach (var (key, value) in expectedConfig.Metadata)
{
string? targetValue = agent.Definition.Metadata[key];
Assert.NotNull(targetValue);
Assert.Equal(value, targetValue);
}
}
}
// Verify detail definition
Assert.Equal(expectedConfig.VectorStoreId, agent.Definition.ToolResources.FileSearch?.VectorStoreIds.SingleOrDefault());
Assert.Equal(expectedConfig.CodeInterpreterFileIds, agent.Definition.ToolResources.CodeInterpreter?.FileIds);
}
private async Task<OpenAIAssistantAgent> CreateAgentAsync()
{
OpenAIAssistantDefinition definition = new("testmodel");
this.SetupResponse(HttpStatusCode.OK, definition);
var clientProvider = this.CreateTestClient();
var assistantClient = clientProvider.Client.GetAssistantClient();
var assistantCreationOptions = new AssistantCreationOptions();
var model = await assistantClient.CreateAssistantAsync("testmodel", assistantCreationOptions);
return new OpenAIAssistantAgent(model, assistantClient)
{
Kernel = this._emptyKernel
};
}
private OpenAIClientProvider CreateTestClient(bool targetAzure = false)
=> targetAzure ?
OpenAIClientProvider.ForAzureOpenAI(apiKey: new ApiKeyCredential("fakekey"), endpoint: new Uri("https://localhost"), this._httpClient) :
OpenAIClientProvider.ForOpenAI(apiKey: new ApiKeyCredential("fakekey"), endpoint: null, this._httpClient);
private void SetupResponse(HttpStatusCode statusCode, string content) =>
this._messageHandlerStub.SetupResponses(statusCode, content);
private void SetupResponse(HttpStatusCode statusCode, OpenAIAssistantDefinition definition) =>
this._messageHandlerStub.SetupResponses(statusCode, OpenAIAssistantResponseContent.AssistantDefinition(definition));
private void SetupResponse(HttpStatusCode statusCode, OpenAIAssistantCapabilities capabilities, PromptTemplateConfig templateConfig) =>
this._messageHandlerStub.SetupResponses(statusCode, OpenAIAssistantResponseContent.AssistantDefinition(capabilities, templateConfig));
private void SetupResponses(HttpStatusCode statusCode, params string[] content) =>
this._messageHandlerStub.SetupResponses(statusCode, content);
| OpenAIAssistantAgentTests |
csharp | dotnet__orleans | test/Orleans.Serialization.UnitTests/BuiltInCodecTests.cs | {
"start": 114447,
"end": 115228
} | public class ____(ITestOutputHelper output) : CopierTester<ConcurrentQueue<int>, ConcurrentQueueCopier<int>>(output)
{
protected override ConcurrentQueue<int> CreateValue()
{
var result = new ConcurrentQueue<int>();
var len = Random.Next(17);
for (var i = 0; i < len + 5; i++)
{
result.Enqueue(Random.Next());
}
return result;
}
protected override bool Equals(ConcurrentQueue<int> left, ConcurrentQueue<int> right) => ReferenceEquals(left, right) || left.SequenceEqual(right);
protected override ConcurrentQueue<int>[] TestValues => [null, new ConcurrentQueue<int>(), CreateValue(), CreateValue(), CreateValue()];
}
| ConcurrentQueueCopierTests |
csharp | dotnet__maui | src/Core/src/Layouts/Flex.cs | {
"start": 4179,
"end": 4803
} | enum ____
{
/// <summary>
/// Whether the item's frame will be determined by the flex rules of the layout system.
/// </summary>
Relative = 0,
/// <summary>
/// Whether the item's frame will be determined by fixed position values (<see cref="P:Microsoft.Maui.Controls.Flex.Item.Left" />, <see cref="P:Microsoft.Maui.Controls.Flex.Item.Right" />, <see cref="P:Microsoft.Maui.Controls.Flex.Item.Top" /> and <see cref="P:Microsoft.Maui.Controls.Flex.Item.Bottom" />).
/// </summary>
Absolute = 1,
}
/// <summary>
/// Values for <see cref="P:Microsoft.Maui.Controls.Flex.Item.Wrap" />.
/// </summary>
| Position |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.RenderTests/Media/StreamGeometryTests.cs | {
"start": 229,
"end": 2288
} | public class ____ : TestBase
{
public StreamGeometryTests()
: base(@"Media\StreamGeometry")
{
}
[Fact]
public async Task PreciseEllipticArc_Produces_Valid_Arcs_In_All_Directions()
{
var grid = new Avalonia.Controls.Primitives.UniformGrid() { Columns = 2, Rows = 4, Width = 320, Height = 400 };
foreach (var sweepDirection in new[] { SweepDirection.Clockwise, SweepDirection.CounterClockwise })
foreach (var isLargeArc in new[] { false, true })
foreach (var isPrecise in new[] { false, true })
{
Point Pt(double x, double y) => new Point(x, y);
Size Sz(double w, double h) => new Size(w, h);
var streamGeometry = new StreamGeometry();
using (var context = streamGeometry.Open())
{
context.BeginFigure(Pt(20, 20), true);
if(isPrecise)
context.PreciseArcTo(Pt(40, 40), Sz(20, 20), 0, isLargeArc, sweepDirection);
else
context.ArcTo(Pt(40, 40), Sz(20, 20), 0, isLargeArc, sweepDirection);
context.LineTo(Pt(40, 20));
context.LineTo(Pt(20, 20));
context.EndFigure(true);
}
var pathShape = new Avalonia.Controls.Shapes.Path();
pathShape.Data = streamGeometry;
pathShape.Stroke = new SolidColorBrush(Colors.CornflowerBlue);
pathShape.Fill = new SolidColorBrush(Colors.Gold);
pathShape.StrokeThickness = 2;
pathShape.Margin = new Thickness(20);
grid.Children.Add(pathShape);
}
await RenderToFile(grid);
}
}
}
| StreamGeometryTests |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/ResultProcessor.cs | {
"start": 66730,
"end": 67269
} | private sealed class ____ : ResultProcessor<double?[]>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (result.Resp2TypeArray == ResultType.Array && !result.IsNull)
{
var arr = result.GetItemsAsDoubles()!;
SetResult(message, arr);
return true;
}
return false;
}
}
| NullableDoubleArrayProcessor |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Payments.PayPalCommerce/Services/Api/Models/Enums/UsagePatternType.cs | {
"start": 148,
"end": 2763
} | public enum ____
{
/// <summary>
/// On-demand instant payments – non-recurring, pre-paid, variable amount, variable frequency.
/// </summary>
IMMEDIATE,
/// <summary>
/// Pay after use, non-recurring post-paid, variable amount, irregular frequency.
/// </summary>
DEFERRED,
/// <summary>
/// Subscription plan where the amount due and the billing frequency are fixed. There is no defined duration for the payment due before the goods or services are delivered.
/// </summary>
SUBSCRIPTION_PREPAID,
/// <summary>
/// Subscription plan where the amount due and the billing frequency are fixed. There is no defined duration for the payment due after the goods or services are delivered.
/// </summary>
SUBSCRIPTION_POSTPAID,
/// <summary>
/// Pay a fixed or variable amount upfront on a fixed date before the goods or services are delivered.
/// </summary>
RECURRING_PREPAID,
/// <summary>
/// Pay on a fixed date based on usage or consumption after the goods or services are delivered.
/// </summary>
RECURRING_POSTPAID,
/// <summary>
/// Unscheduled card-on-file plan where the merchant can bill the payer upfront based on an agreed logic, but the amount due and frequency can vary. This includes automatic reload plans.
/// </summary>
UNSCHEDULED_PREPAID,
/// <summary>
/// Merchant-managed installment plan when the amount to be paid and the billing frequency is fixed, but there is a defined number of payments with the payment due after the goods or services are delivered.
/// </summary>
UNSCHEDULED_POSTPAID,
/// <summary>
/// Merchant-managed installment plan when the amount to be paid and the billing frequency are fixed, but there is a defined number of payments with the payment due before the gods or services are delivered.
/// </summary>
INSTALLMENT_PREPAID,
/// <summary>
/// Merchant-managed installment plan when the amount to be paid and the billing frequency are fixed, but there is a defined number of payments with the payment due after the goods or services are delivered.
/// </summary>
INSTALLMENT_POSTPAID,
/// <summary>
/// Charge payer when the set amount is reached or monthly billing cycle, whichever comes first, before the goods/service is delivered.
/// </summary>
THRESHOLD_PREPAID,
/// <summary>
/// Charge payer when the set amount is reached or monthly billing cycle, whichever comes first, after the goods/service is delivered.
/// </summary>
THRESHOLD_POSTPAID
} | UsagePatternType |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.PaymentMomo/ModuleInitializer.cs | {
"start": 251,
"end": 595
} | public class ____ : IModuleInitializer
{
public void ConfigureServices(IServiceCollection serviceCollection)
{
GlobalConfiguration.RegisterAngularModule("simplAdmin.paymentMomo");
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
}
| ModuleInitializer |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Razor/Html/AntiXsrf/AntiForgeryWorker.cs | {
"start": 385,
"end": 6783
} | internal sealed class ____
{
private readonly IAntiForgeryConfig _config;
private readonly IAntiForgeryTokenSerializer _serializer;
private readonly ITokenStore _tokenStore;
private readonly ITokenValidator _validator;
internal AntiForgeryWorker(IAntiForgeryTokenSerializer serializer, IAntiForgeryConfig config, ITokenStore tokenStore, ITokenValidator validator)
{
_serializer = serializer;
_config = config;
_tokenStore = tokenStore;
_validator = validator;
}
private void CheckSSLConfig(HttpContextBase httpContext)
{
if (_config.RequireSSL && !httpContext.Request.IsSecureConnection) {
throw new InvalidOperationException(MvcResources.AntiForgeryWorker_RequireSSL);
}
}
private AntiForgeryToken DeserializeToken(string serializedToken)
{
return (!String.IsNullOrEmpty(serializedToken))
? _serializer.Deserialize(serializedToken)
: null;
}
private AntiForgeryToken DeserializeTokenNoThrow(string serializedToken)
{
try {
return DeserializeToken(serializedToken);
} catch {
// ignore failures since we'll just generate a new token
return null;
}
}
private static IIdentity ExtractIdentity(HttpContextBase httpContext)
{
if (httpContext != null) {
IPrincipal user = httpContext.User;
if (user != null) {
return user.Identity;
}
}
return null;
}
private AntiForgeryToken GetCookieTokenNoThrow(HttpContextBase httpContext)
{
try {
return _tokenStore.GetCookieToken(httpContext);
} catch {
// ignore failures since we'll just generate a new token
return null;
}
}
// [ ENTRY POINT ]
// Generates an anti-XSRF token pair for the current user. The return
// value is the hidden input form element that should be rendered in
// the <form>. This method has a side effect: it may set a response
// cookie.
public TagBuilder GetFormInputElement(HttpContextBase httpContext)
{
CheckSSLConfig(httpContext);
AntiForgeryToken oldCookieToken = GetCookieTokenNoThrow(httpContext);
AntiForgeryToken newCookieToken, formToken;
GetTokens(httpContext, oldCookieToken, out newCookieToken, out formToken);
if (newCookieToken != null) {
// If a new cookie was generated, persist it.
_tokenStore.SaveCookieToken(httpContext, newCookieToken);
}
// <input type="hidden" name="__AntiForgeryToken" value="..." />
TagBuilder retVal = new TagBuilder("input");
retVal.Attributes["type"] = "hidden";
retVal.Attributes["name"] = _config.FormFieldName;
retVal.Attributes["value"] = _serializer.Serialize(formToken);
return retVal;
}
// [ ENTRY POINT ]
// Generates a (cookie, form) serialized token pair for the current user.
// The caller may specify an existing cookie value if one exists. If the
// 'new cookie value' out param is non-null, the caller *must* persist
// the new value to cookie storage since the original value was null or
// invalid. This method is side-effect free.
public void GetTokens(HttpContextBase httpContext, string serializedOldCookieToken, out string serializedNewCookieToken, out string serializedFormToken)
{
CheckSSLConfig(httpContext);
AntiForgeryToken oldCookieToken = DeserializeTokenNoThrow(serializedOldCookieToken);
AntiForgeryToken newCookieToken, formToken;
GetTokens(httpContext, oldCookieToken, out newCookieToken, out formToken);
serializedNewCookieToken = Serialize(newCookieToken);
serializedFormToken = Serialize(formToken);
}
private void GetTokens(HttpContextBase httpContext, AntiForgeryToken oldCookieToken, out AntiForgeryToken newCookieToken, out AntiForgeryToken formToken)
{
newCookieToken = null;
if (!_validator.IsCookieTokenValid(oldCookieToken)) {
// Need to make sure we're always operating with a good cookie token.
oldCookieToken = newCookieToken = _validator.GenerateCookieToken();
}
#if NET_4_0
Contract.Assert(_validator.IsCookieTokenValid(oldCookieToken));
#endif
formToken = _validator.GenerateFormToken(httpContext, ExtractIdentity(httpContext), oldCookieToken);
}
private string Serialize(AntiForgeryToken token)
{
return (token != null) ? _serializer.Serialize(token) : null;
}
// [ ENTRY POINT ]
// Given an HttpContext, validates that the anti-XSRF tokens contained
// in the cookies & form are OK for this request.
public void Validate(HttpContextBase httpContext)
{
CheckSSLConfig(httpContext);
// Extract cookie & form tokens
AntiForgeryToken cookieToken = _tokenStore.GetCookieToken(httpContext);
AntiForgeryToken formToken = _tokenStore.GetFormToken(httpContext);
// Validate
_validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), cookieToken, formToken);
}
// [ ENTRY POINT ]
// Given the serialized string representations of a cookie & form token,
// validates that the pair is OK for this request.
public void Validate(HttpContextBase httpContext, string cookieToken, string formToken)
{
CheckSSLConfig(httpContext);
// Extract cookie & form tokens
AntiForgeryToken deserializedCookieToken = DeserializeToken(cookieToken);
AntiForgeryToken deserializedFormToken = DeserializeToken(formToken);
// Validate
_validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), deserializedCookieToken, deserializedFormToken);
}
}
}
#endif
| AntiForgeryWorker |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.UrlRewriting.Abstractions/IRewriteRulesManager.cs | {
"start": 107,
"end": 583
} | public interface ____
{
Task<RewriteRule> NewAsync(string source, JsonNode data = null);
Task<RewriteValidateResult> ValidateAsync(RewriteRule rule);
Task<RewriteRule> FindByIdAsync(string id);
Task SaveAsync(RewriteRule rule);
Task DeleteAsync(RewriteRule rule);
Task UpdateAsync(RewriteRule rule, JsonNode data = null);
Task ResortOrderAsync(int oldOrder, int newOrder);
Task<IEnumerable<RewriteRule>> GetAllAsync();
}
| IRewriteRulesManager |
csharp | bitwarden__server | src/Core/Settings/IDomainVerificationSettings.cs | {
"start": 31,
"end": 176
} | public interface ____
{
public int VerificationInterval { get; set; }
public int ExpirationPeriod { get; set; }
}
| IDomainVerificationSettings |
csharp | mysql-net__MySqlConnector | src/MySqlConnector/MySqlDataReader.cs | {
"start": 410,
"end": 467
} | public sealed class ____ : DbDataReader
#else
| MySqlDataReader |
csharp | EventStore__EventStore | src/KurrentDB.Common/Configuration/MetricsConfiguration.cs | {
"start": 1257,
"end": 1312
} | public enum ____ {
Read = 1,
Written,
}
| EventTracker |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Configuration/IReceiveConnector.cs | {
"start": 1189,
"end": 2268
} | public interface ____ :
IEndpointConfigurationObserverConnector
{
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="definition">
/// An endpoint definition, which abstracts specific endpoint behaviors from the transport
/// </param>
/// <param name="endpointNameFormatter"></param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter? endpointNameFormatter = null,
Action<IReceiveEndpointConfigurator>? configureEndpoint = null);
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="queueName">The queue name for the receive endpoint</param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IReceiveEndpointConfigurator>? configureEndpoint = null);
}
}
| IReceiveConnector |
csharp | dotnet__efcore | test/EFCore.SqlServer.Tests/Metadata/SqlServerMetadataExtensionsTest.cs | {
"start": 230,
"end": 16184
} | public class ____
{
[ConditionalFact]
public void Can_get_and_set_MaxSize()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder
.Model;
Assert.Null(model.GetDatabaseMaxSize());
Assert.Null(((IConventionModel)model).GetDatabaseMaxSizeConfigurationSource());
((IConventionModel)model).SetDatabaseMaxSize("1 GB", fromDataAnnotation: true);
Assert.Equal("1 GB", model.GetDatabaseMaxSize());
Assert.Equal(ConfigurationSource.DataAnnotation, ((IConventionModel)model).GetDatabaseMaxSizeConfigurationSource());
model.SetDatabaseMaxSize("10 GB");
Assert.Equal("10 GB", model.GetDatabaseMaxSize());
Assert.Equal(ConfigurationSource.Explicit, ((IConventionModel)model).GetDatabaseMaxSizeConfigurationSource());
model.SetDatabaseMaxSize(null);
Assert.Null(model.GetDatabaseMaxSize());
Assert.Null(((IConventionModel)model).GetDatabaseMaxSizeConfigurationSource());
}
[ConditionalFact]
public void Can_get_and_set_ServiceTier()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder
.Model;
Assert.Null(model.GetServiceTierSql());
Assert.Null(((IConventionModel)model).GetDatabaseMaxSizeConfigurationSource());
((IConventionModel)model).SetServiceTierSql("basic", fromDataAnnotation: true);
Assert.Equal("basic", model.GetServiceTierSql());
Assert.Equal(ConfigurationSource.DataAnnotation, ((IConventionModel)model).GetServiceTierSqlConfigurationSource());
model.SetServiceTierSql("standard");
Assert.Equal("standard", model.GetServiceTierSql());
Assert.Equal(ConfigurationSource.Explicit, ((IConventionModel)model).GetServiceTierSqlConfigurationSource());
model.SetServiceTierSql(null);
Assert.Null(model.GetServiceTierSql());
Assert.Null(((IConventionModel)model).GetServiceTierSqlConfigurationSource());
}
[ConditionalFact]
public void Can_get_and_set_PerformanceLevel()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder
.Model;
Assert.Null(model.GetPerformanceLevelSql());
Assert.Null(((IConventionModel)model).GetPerformanceLevelSqlConfigurationSource());
((IConventionModel)model).SetPerformanceLevelSql("S0", fromDataAnnotation: true);
Assert.Equal("S0", model.GetPerformanceLevelSql());
Assert.Equal(ConfigurationSource.DataAnnotation, ((IConventionModel)model).GetPerformanceLevelSqlConfigurationSource());
model.SetPerformanceLevelSql("ELASTIC_POOL (name = elastic_pool)");
Assert.Equal("ELASTIC_POOL (name = elastic_pool)", model.GetPerformanceLevelSql());
Assert.Equal(ConfigurationSource.Explicit, ((IConventionModel)model).GetPerformanceLevelSqlConfigurationSource());
model.SetPerformanceLevelSql(null);
Assert.Null(model.GetPerformanceLevelSql());
Assert.Null(((IConventionModel)model).GetPerformanceLevelSqlConfigurationSource());
}
[ConditionalFact]
public void Can_get_and_set_column_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal("Name", property.GetColumnName());
Assert.Null(((IConventionProperty)property).GetColumnNameConfigurationSource());
((IConventionProperty)property).SetColumnName("Eman", fromDataAnnotation: true);
Assert.Equal("Eman", property.GetColumnName());
Assert.Equal(ConfigurationSource.DataAnnotation, ((IConventionProperty)property).GetColumnNameConfigurationSource());
property.SetColumnName("MyNameIs");
Assert.Equal("Name", property.Name);
Assert.Equal("MyNameIs", property.GetColumnName());
Assert.Equal(ConfigurationSource.Explicit, ((IConventionProperty)property).GetColumnNameConfigurationSource());
property.SetColumnName(null);
Assert.Equal("Name", property.GetColumnName());
Assert.Null(((IConventionProperty)property).GetColumnNameConfigurationSource());
}
[ConditionalFact]
public void Can_get_and_set_key_name()
{
var modelBuilder = GetModelBuilder();
var key = modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.Metadata;
Assert.Equal("PK_Customer", key.GetName());
key.SetName("PrimaryKey");
Assert.Equal("PrimaryKey", key.GetName());
key.SetName("PrimarySchool");
Assert.Equal("PrimarySchool", key.GetName());
key.SetName(null);
Assert.Equal("PK_Customer", key.GetName());
}
[ConditionalFact]
public void Can_get_and_set_index_clustering()
{
var modelBuilder = GetModelBuilder();
var index = modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.Metadata;
Assert.Null(index.IsClustered());
index.SetIsClustered(true);
Assert.True(index.IsClustered().Value);
index.SetIsClustered(null);
Assert.Null(index.IsClustered());
}
[ConditionalFact]
public void Can_get_and_set_key_clustering()
{
var modelBuilder = GetModelBuilder();
var key = modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.Metadata;
Assert.Null(key.IsClustered());
key.SetIsClustered(true);
Assert.True(key.IsClustered().Value);
key.SetIsClustered(null);
Assert.Null(key.IsClustered());
}
[ConditionalFact]
public void Can_get_and_set_value_generation_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Equal(SqlServerValueGenerationStrategy.IdentityColumn, model.GetValueGenerationStrategy());
model.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal(SqlServerValueGenerationStrategy.SequenceHiLo, model.GetValueGenerationStrategy());
model.SetValueGenerationStrategy(null);
Assert.Null(model.GetValueGenerationStrategy());
}
[ConditionalFact]
public void Can_get_and_set_default_sequence_name_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
model.SetHiLoSequenceName("Tasty.Snook");
Assert.Equal("Tasty.Snook", model.GetHiLoSequenceName());
model.SetHiLoSequenceName(null);
Assert.Equal(SqlServerModelExtensions.DefaultHiLoSequenceName, model.GetHiLoSequenceName());
}
[ConditionalFact]
public void Can_get_and_set_default_sequence_schema_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Null(model.GetHiLoSequenceSchema());
model.SetHiLoSequenceSchema("Tasty.Snook");
Assert.Equal("Tasty.Snook", model.GetHiLoSequenceSchema());
model.SetHiLoSequenceSchema(null);
Assert.Null(model.GetHiLoSequenceSchema());
}
[ConditionalFact]
public void Can_get_and_set_value_generation_on_property()
{
var modelBuilder = GetModelBuilder();
modelBuilder.Model.SetValueGenerationStrategy(null);
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Equal(SqlServerValueGenerationStrategy.None, property.GetValueGenerationStrategy());
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal(SqlServerValueGenerationStrategy.SequenceHiLo, property.GetValueGenerationStrategy());
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
property.SetValueGenerationStrategy(null);
Assert.Equal(SqlServerValueGenerationStrategy.None, property.GetValueGenerationStrategy());
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
}
[ConditionalFact]
public void Can_get_and_set_value_generation_on_nullable_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.NullableInt).ValueGeneratedOnAdd()
.Metadata;
Assert.Equal(SqlServerValueGenerationStrategy.IdentityColumn, property.GetValueGenerationStrategy());
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal(SqlServerValueGenerationStrategy.SequenceHiLo, property.GetValueGenerationStrategy());
property.SetValueGenerationStrategy(null);
Assert.Equal(SqlServerValueGenerationStrategy.IdentityColumn, property.GetValueGenerationStrategy());
}
[ConditionalFact]
public void Can_get_and_set_sequence_name_on_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.GetHiLoSequenceName());
Assert.Null(property.GetHiLoSequenceName());
property.SetHiLoSequenceName("Snook");
Assert.Equal("Snook", property.GetHiLoSequenceName());
property.SetHiLoSequenceName(null);
Assert.Null(property.GetHiLoSequenceName());
}
[ConditionalFact]
public void Can_get_and_set_sequence_schema_on_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.GetHiLoSequenceSchema());
property.SetHiLoSequenceSchema("Tasty");
Assert.Equal("Tasty", property.GetHiLoSequenceSchema());
property.SetHiLoSequenceSchema(null);
Assert.Null(property.GetHiLoSequenceSchema());
}
[ConditionalFact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw");
property.SetHiLoSequenceName("DaneelOlivaw");
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
}
[ConditionalFact]
public void TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw");
modelBuilder.Model.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
property.SetHiLoSequenceName("DaneelOlivaw");
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
}
[ConditionalFact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw");
modelBuilder.Model.SetHiLoSequenceName("DaneelOlivaw");
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
}
[ConditionalFact]
public void
TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw");
modelBuilder.Model.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
modelBuilder.Model.SetHiLoSequenceName("DaneelOlivaw");
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
}
[ConditionalFact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw", "R");
property.SetHiLoSequenceName("DaneelOlivaw");
property.SetHiLoSequenceSchema("R");
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
Assert.Equal("R", property.FindHiLoSequence().Schema);
}
[ConditionalFact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw", "R");
modelBuilder.Model.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
property.SetHiLoSequenceName("DaneelOlivaw");
property.SetHiLoSequenceSchema("R");
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
Assert.Equal("R", property.FindHiLoSequence().Schema);
}
[ConditionalFact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw", "R");
modelBuilder.Model.SetHiLoSequenceName("DaneelOlivaw");
modelBuilder.Model.SetHiLoSequenceSchema("R");
property.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
Assert.Equal("R", property.FindHiLoSequence().Schema);
}
[ConditionalFact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.AddSequence("DaneelOlivaw", "R");
modelBuilder.Model.SetValueGenerationStrategy(SqlServerValueGenerationStrategy.SequenceHiLo);
modelBuilder.Model.SetHiLoSequenceName("DaneelOlivaw");
modelBuilder.Model.SetHiLoSequenceSchema("R");
Assert.Equal("DaneelOlivaw", property.FindHiLoSequence().Name);
Assert.Equal("R", property.FindHiLoSequence().Schema);
}
private static ModelBuilder GetModelBuilder()
=> SqlServerTestHelpers.Instance.CreateConventionBuilder();
// ReSharper disable once ClassNeverInstantiated.Local
| SqlServerMetadataExtensionsTest |
csharp | moq__moq4 | src/Moq.Tests/ExtensionsFixture.cs | {
"start": 6821,
"end": 6951
} | public interface ____
{
#region Public Methods
object Execute(string ping);
#endregion
}
}
| IFooReset |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Users/Permissions.cs | {
"start": 71,
"end": 1988
} | public sealed class ____ : IPermissionProvider
{
public static readonly Permission ManageUsers = UsersPermissions.ManageUsers;
public static readonly Permission ViewUsers = UsersPermissions.ViewUsers;
public static readonly Permission ManageOwnUserInformation = UsersPermissions.EditOwnUser;
public static readonly Permission EditOwnUser = UsersPermissions.EditOwnUser;
public static readonly Permission ListUsers = UsersPermissions.ListUsers;
public static readonly Permission EditUsers = UsersPermissions.EditUsers;
public static readonly Permission DeleteUsers = UsersPermissions.DeleteUsers;
private readonly IEnumerable<Permission> _allPermissions =
[
ManageUsers,
ViewUsers,
EditOwnUser,
ListUsers,
EditUsers,
DeleteUsers,
];
private readonly IEnumerable<Permission> _generalPermissions =
[
EditOwnUser,
];
public Task<IEnumerable<Permission>> GetPermissionsAsync()
=> Task.FromResult(_allPermissions);
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
[
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Administrator,
Permissions = _allPermissions,
},
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Editor,
Permissions = _generalPermissions,
},
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Moderator,
Permissions = _generalPermissions,
},
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Contributor,
Permissions = _generalPermissions,
},
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Author,
Permissions = _generalPermissions,
}
];
}
| Permissions |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/Slider/SliderKeyProcess.cs | {
"start": 270,
"end": 1983
} | internal static class ____
{
internal static void KeyDown(VirtualKey key, Slider control, out bool handled)
{
handled = false;
var orientation = control.Orientation;
var flowDirection = control.FlowDirection;
var shouldReverse = control.IsDirectionReversed;
var shouldInvert = (flowDirection == FlowDirection.RightToLeft) ^ shouldReverse;
if (key == VirtualKey.Left ||
(orientation == Orientation.Horizontal &&
(key == VirtualKey.GamepadDPadLeft ||
key == VirtualKey.GamepadLeftThumbstickLeft)))
{
control.Step(true, shouldInvert);
handled = true;
}
else if (key == VirtualKey.Right ||
(orientation == Orientation.Horizontal &&
(key == VirtualKey.GamepadDPadRight ||
key == VirtualKey.GamepadLeftThumbstickRight)))
{
control.Step(true, !shouldInvert);
handled = true;
}
else if (key == VirtualKey.Up ||
(orientation == Orientation.Vertical &&
(key == VirtualKey.GamepadDPadUp ||
key == VirtualKey.GamepadLeftThumbstickUp)))
{
control.Step(true, !shouldReverse);
handled = true;
}
else if (key == VirtualKey.Down ||
(orientation == Orientation.Vertical &&
(key == VirtualKey.GamepadDPadDown ||
key == VirtualKey.GamepadLeftThumbstickDown)))
{
control.Step(true, shouldReverse);
handled = true;
}
else if (key == VirtualKey.Home || key == VirtualKey.GamepadLeftShoulder)
{
var delta = control.Minimum;
control.Value = delta;
handled = true;
}
else if (key == VirtualKey.End || key == VirtualKey.GamepadRightShoulder)
{
var delta = control.Maximum;
control.Value = delta;
handled = true;
}
}
}
}
| KeyProcess |
csharp | Cysharp__ZLogger | src/ZLogger/Internal/EnumDictionary.cs | {
"start": 236,
"end": 6627
} | class ____<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>
{
static object dictionary;
public static readonly delegate* managed<T, string?> GetStringName;
public static readonly delegate* managed<T, ReadOnlySpan<byte>> GetUtf8Name; // be careful, zero is not found.
public static readonly delegate* managed<T, JsonEncodedText?> GetJsonEncodedName;
[UnconditionalSuppressMessage("Trimming", "IL3050:RequiresDynamicCode")]
[UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode")]
static EnumDictionary()
{
var type = typeof(T);
var source = new List<(T, EnumName)>();
foreach (var key in Enum.GetValues(type))
{
var name = Enum.GetName(type, key);
var utf8Name = Encoding.UTF8.GetBytes(name!);
var jsonName = JsonEncodedText.Encode(utf8Name);
if (name != null)
{
source.Add(((T)key, new EnumName(name, utf8Name, jsonName)));
}
}
var e = Enum.GetUnderlyingType(type);
var code = Type.GetTypeCode(e);
switch (code)
{
case TypeCode.SByte:
dictionary = source.Select(x => (Unsafe.As<T, SByte>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<SByte>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<SByte>;
GetUtf8Name = &GetUtf8NameCore<SByte>;
GetJsonEncodedName = &GetJsonEncodedTextCore<SByte>;
break;
case TypeCode.Byte:
dictionary = source.Select(x => (Unsafe.As<T, Byte>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<Byte>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<Byte>;
GetUtf8Name = &GetUtf8NameCore<Byte>;
GetJsonEncodedName = &GetJsonEncodedTextCore<Byte>;
break;
case TypeCode.Int16:
dictionary = source.Select(x => (Unsafe.As<T, Int16>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<Int16>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<Int16>;
GetUtf8Name = &GetUtf8NameCore<Int16>;
GetJsonEncodedName = &GetJsonEncodedTextCore<Int16>;
break;
case TypeCode.UInt16:
dictionary = source.Select(x => (Unsafe.As<T, UInt16>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<UInt16>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<UInt16>;
GetUtf8Name = &GetUtf8NameCore<UInt16>;
GetJsonEncodedName = &GetJsonEncodedTextCore<UInt16>;
break;
case TypeCode.Int32:
dictionary = source.Select(x => (Unsafe.As<T, Int32>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<Int32>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<Int32>;
GetUtf8Name = &GetUtf8NameCore<Int32>;
GetJsonEncodedName = &GetJsonEncodedTextCore<Int32>;
break;
case TypeCode.UInt32:
dictionary = source.Select(x => (Unsafe.As<T, UInt32>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<UInt32>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<UInt32>;
GetUtf8Name = &GetUtf8NameCore<UInt32>;
GetJsonEncodedName = &GetJsonEncodedTextCore<UInt32>;
break;
case TypeCode.Int64:
dictionary = source.Select(x => (Unsafe.As<T, Int64>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<Int64>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<Int64>;
GetUtf8Name = &GetUtf8NameCore<Int64>;
GetJsonEncodedName = &GetJsonEncodedTextCore<Int64>;
break;
case TypeCode.UInt64:
dictionary = source.Select(x => (Unsafe.As<T, UInt64>(ref x.Item1), x.Item2)).Distinct(new DistinctEqualityComparer<UInt64>()).ToFrozenDictionary(x => x.Item1, x => x.Item2);
GetStringName = &GetStringNameCore<UInt64>;
GetUtf8Name = &GetUtf8NameCore<UInt64>;
GetJsonEncodedName = &GetJsonEncodedTextCore<UInt64>;
break;
default:
throw new ArgumentException();
}
}
static string? GetStringNameCore<TUnderlying>(T value)
where TUnderlying : notnull
{
#if NET8_0_OR_GREATER
if (Unsafe.As<object, FrozenDictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#else
if (Unsafe.As<object, Dictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#endif
{
return entry.Name;
}
else
{
return null;
}
}
static ReadOnlySpan<byte> GetUtf8NameCore<TUnderlying>(T value)
where TUnderlying : notnull
{
#if NET8_0_OR_GREATER
if (Unsafe.As<object, FrozenDictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#else
if (Unsafe.As<object, Dictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#endif
{
return entry.Utf8Name;
}
else
{
return null;
}
}
static JsonEncodedText? GetJsonEncodedTextCore<TUnderlying>(T value)
where TUnderlying : notnull
{
#if NET8_0_OR_GREATER
if (Unsafe.As<object, FrozenDictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#else
if (Unsafe.As<object, Dictionary<TUnderlying, EnumName>>(ref dictionary).TryGetValue(Unsafe.As<T, TUnderlying>(ref value), out var entry))
#endif
{
return entry.JsonEncoded;
}
else
{
return null;
}
}
}
file | EnumDictionary |
csharp | MassTransit__MassTransit | src/MassTransit/InMemoryTransport/InMemoryTransport/InMemoryReceiveTransport.cs | {
"start": 2911,
"end": 6195
} | class ____ :
ConsumerAgent<long>,
ReceiveTransportHandle,
IMessageReceiver<InMemoryTransportMessage>
{
readonly InMemoryReceiveEndpointContext _context;
readonly TaskExecutor _executor;
readonly IMessageQueue<InMemoryTransportContext, InMemoryTransportMessage> _queue;
TopologyHandle _topologyHandle;
public ReceiveTransportAgent(InMemoryReceiveEndpointContext context, IMessageQueue<InMemoryTransportContext, InMemoryTransportMessage> queue)
: base(context)
{
_context = context;
_queue = queue;
_executor = new TaskExecutor(context.ConcurrentMessageLimit ?? context.PrefetchCount);
Task.Run(() => Startup());
}
public Task Deliver(InMemoryTransportMessage message, CancellationToken cancellationToken)
{
if (IsStopping)
return Task.CompletedTask;
return _executor.Push(async () =>
{
LogContext.Current = _context.LogContext;
var context = new InMemoryReceiveContext(message, _context);
try
{
await Dispatch(message.SequenceNumber, context, NoLockReceiveContext.Instance).ConfigureAwait(false);
}
catch (Exception exception)
{
message.DeliveryCount++;
context.LogTransportFaulted(exception);
}
finally
{
context.Dispose();
}
}, cancellationToken);
}
public void Probe(ProbeContext context)
{
context.CreateScope("inMemory");
}
Task ReceiveTransportHandle.Stop(CancellationToken cancellationToken)
{
return this.Stop("Stop Receive Transport", cancellationToken);
}
async Task Startup()
{
try
{
await _context.DependenciesReady.OrCanceled(Stopping).ConfigureAwait(false);
_topologyHandle = _queue.ConnectMessageReceiver(_context.TransportContext, this);
await _context.TransportObservers.NotifyReady(_context.InputAddress).ConfigureAwait(false);
SetReady();
}
catch (Exception exception)
{
SetNotReady(exception);
}
}
protected override async Task ActiveAndActualAgentsCompleted(StopContext context)
{
_topologyHandle?.Disconnect();
await base.ActiveAndActualAgentsCompleted(context).ConfigureAwait(false);
await _executor.DisposeAsync().ConfigureAwait(false);
await _context.TransportObservers.NotifyCompleted(_context.InputAddress, this).ConfigureAwait(false);
_context.LogConsumerCompleted(DeliveryCount, ConcurrentDeliveryCount);
}
}
}
}
| ReceiveTransportAgent |
csharp | xunit__xunit | src/xunit.v3.core.tests/Acceptance/Xunit3AcceptanceTests.cs | {
"start": 43765,
"end": 44557
} | public class ____ : AcceptanceTestV3
{
[Fact]
public async ValueTask AsyncVoidTestsAreFastFailed()
{
var results = await RunAsync(typeof(ClassWithAsyncVoidTest));
var failedMessage = Assert.Single(results.OfType<ITestFailed>());
var failedStarting = Assert.Single(results.OfType<ITestStarting>(), s => s.TestUniqueID == failedMessage.TestUniqueID);
Assert.Equal("Xunit3AcceptanceTests+AsyncVoid+ClassWithAsyncVoidTest.TestMethod", failedStarting.TestDisplayName);
var message = Assert.Single(failedMessage.Messages);
Assert.Equal("Tests marked as 'async void' are no longer supported. Please convert to 'async Task' or 'async ValueTask'.", message);
}
#pragma warning disable xUnit1049 // Do not use 'async void' for test methods as it is no longer supported | AsyncVoid |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/TopologyCorrelationId_Specs.cs | {
"start": 2317,
"end": 2470
} | public class ____
{
public Guid TransactionId { get; set; }
}
}
[TestFixture]
[Category("Flaky")]
| LegacyMessage |
csharp | ardalis__SmartEnum | test/SmartEnum.EFCore.IntegrationTests/TestEnum.cs | {
"start": 1230,
"end": 1712
} | public class ____ : SmartEnum<TestStringEnum, string>
{
public static readonly TestStringEnum One = new TestStringEnum(nameof(One), nameof(One));
public static readonly TestStringEnum Two = new TestStringEnum(nameof(Two), nameof(Two));
public static readonly TestStringEnum Three = new TestStringEnum(nameof(Three), nameof(Three));
protected TestStringEnum(string name, string value) : base(name, value)
{
}
}
| TestStringEnum |
csharp | microsoft__semantic-kernel | dotnet/src/InternalUtilities/process/Abstractions/DeclarativeConditionEvaluation.cs | {
"start": 4600,
"end": 7813
} | internal static class ____
{
public static bool EvaluateCondition(object? data, ConditionExpression expression)
{
if (data == null || expression == null)
{
return false;
}
// Get the property value using reflection
var propertyValue = GetPropertyValue(data, expression.Path);
// If property doesn't exist, the condition is false
if (propertyValue == null)
{
return false;
}
// Convert the target value to the same type as the property
var typedValue = ConvertValue(expression.Value, propertyValue.GetType());
// Evaluate based on the operator
return EvaluateWithOperator(propertyValue, expression.Operator, typedValue);
}
private static object? GetPropertyValue(object data, string path)
{
// Handle nested properties with dot notation (e.g., "User.Address.City")
var properties = path.Split('.');
object? current = data;
foreach (var property in properties)
{
if (current == null)
{
return null;
}
// Get property info using reflection
var propertyInfo = current.GetType().GetProperty(property);
if (propertyInfo == null)
{
return null;
}
// Get the value
current = propertyInfo.GetValue(current);
}
return current;
}
private static object? ConvertValue(object value, Type targetType)
{
if (value == null)
{
return null;
}
// Handle numeric conversions which are common in comparison operations
if (targetType.IsNumeric() && value is IConvertible)
{
return Convert.ChangeType(value, targetType);
}
return value;
}
private static bool EvaluateWithOperator(object left, ConditionOperator op, object? right)
{
// Special case for null values
if (left == null && right == null)
{
return op == ConditionOperator.Equal;
}
if (left == null || right == null)
{
return op == ConditionOperator.NotEqual;
}
// If both values are comparable
if (left is IComparable comparable)
{
int comparisonResult = comparable.CompareTo(right);
switch (op)
{
case ConditionOperator.Equal: return comparisonResult == 0;
case ConditionOperator.NotEqual: return comparisonResult != 0;
case ConditionOperator.GreaterThan: return comparisonResult > 0;
case ConditionOperator.GreaterThanOrEqual: return comparisonResult >= 0;
case ConditionOperator.LessThan: return comparisonResult < 0;
case ConditionOperator.LessThanOrEqual: return comparisonResult <= 0;
default: throw new NotSupportedException($"Operator {op} is not supported.");
}
}
// Fallback to simple equality
return left.Equals(right);
}
}
// Extension method to check if a type is numeric
| ConditionEvaluator |
csharp | npgsql__npgsql | src/Npgsql/Replication/PgOutput/Messages/StreamPrepareMessage.cs | {
"start": 169,
"end": 1207
} | public sealed class ____ : PrepareMessageBase
{
/// <summary>
/// Flags for the prepare; currently unused.
/// </summary>
public StreamPrepareFlags Flags { get; private set; }
internal StreamPrepareMessage() {}
internal StreamPrepareMessage Populate(
NpgsqlLogSequenceNumber walStart, NpgsqlLogSequenceNumber walEnd, DateTime serverClock, StreamPrepareFlags flags,
NpgsqlLogSequenceNumber prepareLsn, NpgsqlLogSequenceNumber prepareEndLsn, DateTime transactionPrepareTimestamp,
uint transactionXid, string transactionGid)
{
base.Populate(walStart, walEnd, serverClock,
prepareLsn: prepareLsn,
prepareEndLsn: prepareEndLsn,
transactionPrepareTimestamp: transactionPrepareTimestamp,
transactionXid: transactionXid,
transactionGid: transactionGid);
Flags = flags;
return this;
}
/// <summary>
/// Flags for the prepare; currently unused.
/// </summary>
[Flags]
| StreamPrepareMessage |
csharp | bitwarden__server | util/MySqlMigrations/Migrations/20220608191914_DeactivatedUserStatus.cs | {
"start": 93,
"end": 813
} | public partial class ____ : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<short>(
name: "Status",
table: "OrganizationUser",
type: "smallint",
nullable: false,
oldClrType: typeof(byte),
oldType: "tinyint unsigned");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<byte>(
name: "Status",
table: "OrganizationUser",
type: "tinyint unsigned",
nullable: false,
oldClrType: typeof(short),
oldType: "smallint");
}
}
| DeactivatedUserStatus |
csharp | Testably__Testably.Abstractions | Tests/Testably.Abstractions.Testing.Tests/Statistics/FileSystem/PathStatisticsTests.cs | {
"start": 225,
"end": 18665
} | public class ____
{
[Fact]
public async Task Method_ChangeExtension_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
string extension = "foo";
sut.Path.ChangeExtension(path, extension);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.ChangeExtension),
path, extension);
}
#if FEATURE_PATH_SPAN
[Fact]
public async Task Method_Combine_ReadOnlySpanString_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<string> paths = new();
sut.Path.Combine(paths);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Combine),
paths);
}
#endif
[Fact]
public async Task Method_Combine_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
sut.Path.Combine(path1, path2);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Combine),
path1, path2);
}
[Fact]
public async Task Method_Combine_String_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
string path3 = "foo";
sut.Path.Combine(path1, path2, path3);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Combine),
path1, path2, path3);
}
[Fact]
public async Task Method_Combine_String_String_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
string path3 = "foo";
string path4 = "foo";
sut.Path.Combine(path1, path2, path3, path4);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Combine),
path1, path2, path3, path4);
}
[Fact]
public async Task Method_Combine_StringArray_ShouldRegisterCall()
{
MockFileSystem sut = new();
string[] paths = ["foo", "bar"];
sut.Path.Combine(paths);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Combine),
paths);
}
#if FEATURE_PATH_ADVANCED
[Fact]
public async Task Method_EndsInDirectorySeparator_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.EndsInDirectorySeparator(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.EndsInDirectorySeparator),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_ADVANCED
[Fact]
public async Task Method_EndsInDirectorySeparator_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.EndsInDirectorySeparator(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.EndsInDirectorySeparator),
path);
}
#endif
#if FEATURE_FILESYSTEM_NET_7_OR_GREATER
[Fact]
public async Task Method_Exists_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.Exists(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Exists),
path);
}
#endif
#if FEATURE_SPAN
[Fact]
public async Task Method_GetDirectoryName_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.GetDirectoryName(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetDirectoryName),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_GetDirectoryName_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetDirectoryName(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetDirectoryName),
path);
}
#if FEATURE_SPAN
[Fact]
public async Task Method_GetExtension_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.GetExtension(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetExtension),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_GetExtension_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetExtension(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetExtension),
path);
}
#if FEATURE_SPAN
[Fact]
public async Task Method_GetFileName_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.GetFileName(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetFileName),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_GetFileName_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetFileName(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetFileName),
path);
}
#if FEATURE_SPAN
[Fact]
public async Task Method_GetFileNameWithoutExtension_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.GetFileNameWithoutExtension(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetFileNameWithoutExtension),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_GetFileNameWithoutExtension_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetFileNameWithoutExtension(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(
nameof(IPath.GetFileNameWithoutExtension),
path);
}
[Fact]
public async Task Method_GetFullPath_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetFullPath(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetFullPath),
path);
}
#if FEATURE_PATH_RELATIVE
[Fact]
public async Task Method_GetFullPath_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
string basePath = Path.GetFullPath("bar");
sut.Path.GetFullPath(path, basePath);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetFullPath),
path, basePath);
}
#endif
[Fact]
public async Task Method_GetInvalidFileNameChars_ShouldRegisterCall()
{
MockFileSystem sut = new();
sut.Path.GetInvalidFileNameChars();
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path)
.OnlyContainsMethodCall(nameof(IPath.GetInvalidFileNameChars));
}
[Fact]
public async Task Method_GetInvalidPathChars_ShouldRegisterCall()
{
MockFileSystem sut = new();
sut.Path.GetInvalidPathChars();
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetInvalidPathChars));
}
#if FEATURE_SPAN
[Fact]
public async Task Method_GetPathRoot_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.GetPathRoot(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetPathRoot),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_GetPathRoot_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.GetPathRoot(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetPathRoot),
path);
}
[Fact]
public async Task Method_GetRandomFileName_ShouldRegisterCall()
{
MockFileSystem sut = new();
sut.Path.GetRandomFileName();
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetRandomFileName));
}
#if FEATURE_PATH_RELATIVE
[Fact]
public async Task Method_GetRelativePath_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string relativeTo = "foo";
string path = "foo";
sut.Path.GetRelativePath(relativeTo, path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetRelativePath),
relativeTo, path);
}
#endif
[Fact]
public async Task Method_GetTempFileName_ShouldRegisterCall()
{
MockFileSystem sut = new();
#pragma warning disable CS0618
sut.Path.GetTempFileName();
#pragma warning restore CS0618
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetTempFileName));
}
[Fact]
public async Task Method_GetTempPath_ShouldRegisterCall()
{
MockFileSystem sut = new();
sut.Path.GetTempPath();
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.GetTempPath));
}
#if FEATURE_SPAN
[Fact]
public async Task Method_HasExtension_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.HasExtension(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.HasExtension),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_HasExtension_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.HasExtension(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.HasExtension),
path);
}
#if FEATURE_SPAN
[Fact]
public async Task Method_IsPathFullyQualified_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.IsPathFullyQualified(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.IsPathFullyQualified),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_RELATIVE
[Fact]
public async Task Method_IsPathFullyQualified_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.IsPathFullyQualified(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.IsPathFullyQualified),
path);
}
#endif
#if FEATURE_SPAN
[Fact]
public async Task Method_IsPathRooted_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.IsPathRooted(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.IsPathRooted),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Method_IsPathRooted_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.IsPathRooted(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.IsPathRooted),
path);
}
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_ReadOnlySpanChar_ReadOnlySpanChar_ReadOnlySpanChar_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path1 = new();
ReadOnlySpan<char> path2 = new();
ReadOnlySpan<char> path3 = new();
ReadOnlySpan<char> path4 = new();
sut.Path.Join(path1, path2, path3, path4);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2, path3, path4);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_ReadOnlySpanChar_ReadOnlySpanChar_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path1 = new();
ReadOnlySpan<char> path2 = new();
ReadOnlySpan<char> path3 = new();
sut.Path.Join(path1, path2, path3);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2, path3);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_ReadOnlySpanChar_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path1 = new();
ReadOnlySpan<char> path2 = new();
sut.Path.Join(path1, path2);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_SPAN
[Fact]
public async Task Method_Join_ReadOnlySpanString_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<string?> paths = new();
sut.Path.Join(paths);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
paths);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
sut.Path.Join(path1, path2);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_String_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
string path3 = "foo";
sut.Path.Join(path1, path2, path3);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2, path3);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_String_String_String_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path1 = "foo";
string path2 = "foo";
string path3 = "foo";
string path4 = "foo";
sut.Path.Join(path1, path2, path3, path4);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
path1, path2, path3, path4);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_Join_StringArray_ShouldRegisterCall()
{
MockFileSystem sut = new();
string[] paths = ["foo", "bar"];
sut.Path.Join(paths);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.Join),
paths);
}
#endif
#if FEATURE_PATH_ADVANCED
[Fact]
public async Task Method_TrimEndingDirectorySeparator_ReadOnlySpanChar_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path = new();
sut.Path.TrimEndingDirectorySeparator(path);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.TrimEndingDirectorySeparator),
path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_ADVANCED
[Fact]
public async Task Method_TrimEndingDirectorySeparator_String_ShouldRegisterCall()
{
MockFileSystem sut = new();
string path = "foo";
sut.Path.TrimEndingDirectorySeparator(path);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.TrimEndingDirectorySeparator),
path);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_TryJoin_ReadOnlySpanChar_ReadOnlySpanChar_ReadOnlySpanChar_SpanChar_OutInt_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path1 = new();
ReadOnlySpan<char> path2 = new();
ReadOnlySpan<char> path3 = new();
Span<char> destination = new();
sut.Path.TryJoin(path1, path2, path3, destination, out int charsWritten);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.TryJoin),
path1, path2, path3, destination, charsWritten);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
#if FEATURE_PATH_JOIN
[Fact]
public async Task Method_TryJoin_ReadOnlySpanChar_ReadOnlySpanChar_SpanChar_OutInt_ShouldRegisterCall()
{
MockFileSystem sut = new();
ReadOnlySpan<char> path1 = new();
ReadOnlySpan<char> path2 = new();
Span<char> destination = new();
sut.Path.TryJoin(path1, path2, destination, out int charsWritten);
await That(sut.Statistics.Path).OnlyContainsMethodCall(nameof(IPath.TryJoin),
path1, path2, destination, charsWritten);
await That(sut.Statistics.TotalCount).IsEqualTo(1);
}
#endif
[Fact]
public async Task Property_AltDirectorySeparatorChar_Get_ShouldRegisterPropertyAccess()
{
MockFileSystem sut = new();
_ = sut.Path.AltDirectorySeparatorChar;
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsPropertyGetAccess(
nameof(IPath.AltDirectorySeparatorChar));
}
[Fact]
public async Task Property_DirectorySeparatorChar_Get_ShouldRegisterPropertyAccess()
{
MockFileSystem sut = new();
_ = sut.Path.DirectorySeparatorChar;
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsPropertyGetAccess(
nameof(IPath.DirectorySeparatorChar));
}
[Fact]
public async Task Property_PathSeparator_Get_ShouldRegisterPropertyAccess()
{
MockFileSystem sut = new();
_ = sut.Path.PathSeparator;
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path).OnlyContainsPropertyGetAccess(nameof(IPath.PathSeparator));
}
[Fact]
public async Task Property_VolumeSeparatorChar_Get_ShouldRegisterPropertyAccess()
{
MockFileSystem sut = new();
_ = sut.Path.VolumeSeparatorChar;
await That(sut.Statistics.TotalCount).IsEqualTo(1);
await That(sut.Statistics.Path)
.OnlyContainsPropertyGetAccess(nameof(IPath.VolumeSeparatorChar));
}
[Fact]
public async Task ToString_ShouldBePath()
{
IStatistics sut = new MockFileSystem().Statistics.Path;
string? result = sut.ToString();
await That(result).IsEqualTo("Path");
}
}
| PathStatisticsTests |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternAnalyzerTests.cs | {
"start": 11315,
"end": 11844
} | public class ____
{
public int PageNumber { get; set; }
public int PageIndex { get; set; }
}
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MapGet_AsParameter_Extra_ReportedDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
| PageData |
csharp | bitwarden__server | src/Core/AdminConsole/Enums/Provider/ProviderUserStatusType.cs | {
"start": 50,
"end": 150
} | public enum ____ : byte
{
Invited = 0,
Accepted = 1,
Confirmed = 2,
}
| ProviderUserStatusType |
csharp | dotnet__orleans | src/api/Orleans.Core/Orleans.Core.cs | {
"start": 42546,
"end": 43021
} | public partial interface ____
{
System.Threading.Tasks.ValueTask<RebalancingReport> GetRebalancingReport(bool force = false);
System.Threading.Tasks.Task ResumeRebalancing();
void SubscribeToReports(IActivationRebalancerReportListener listener);
System.Threading.Tasks.Task SuspendRebalancing(System.TimeSpan? duration = null);
void UnsubscribeFromReports(IActivationRebalancerReportListener listener);
}
| IActivationRebalancer |
csharp | microsoft__semantic-kernel | dotnet/test/VectorData/SqlServer.ConformanceTests/SqlServerIndexKindTests.cs | {
"start": 224,
"end": 401
} | public class ____(SqlServerIndexKindTests.Fixture fixture)
: IndexKindTests<int>(fixture), IClassFixture<SqlServerIndexKindTests.Fixture>
{
public new | SqlServerIndexKindTests |
csharp | dotnetcore__Util | src/Util.Ui/Razor/RazorOptions.cs | {
"start": 69,
"end": 1606
} | public class ____ {
/// <summary>
/// Razor文件根路径,默认值: /ClientApp
/// </summary>
public string RazorRootDirectory { get; set; } = "/ClientApp";
/// <summary>
/// Spa静态文件根路径,默认值: ClientApp
/// </summary>
public string RootPath { get; set; } = "ClientApp";
/// <summary>
/// 是否在Razor页面运行时自动生成html文件
/// </summary>
public bool IsGenerateHtml { get; set; }
/// <summary>
/// Razor生成Html文件的目录名称,默认值:html
/// </summary>
public string GenerateHtmlFolder { get; set; } = "html";
/// <summary>
/// 是否启用Razor监视服务,默认值: true
/// </summary>
public bool EnableWatchRazor { get; set; } = true;
/// <summary>
/// Razor监听服务启动初始化的延迟时间,单位: 毫秒, 默认值:1000, 注意: 需要等待Web服务启动完成才能开始初始化
/// </summary>
public int StartInitDelay { get; set; } = 1000;
/// <summary>
/// 修改Razor页面生成Html文件的延迟时间,单位: 毫秒, 默认值:300 ,注意: 延迟太短可能导致生成异常
/// </summary>
public int HtmlRenderDelayOnRazorChange { get; set; } = 300;
/// <summary>
/// 启动Razor监视服务时是否预热,默认值: true
/// </summary>
public bool EnablePreheat { get; set; } = true;
/// <summary>
/// 启用Razor生成覆盖已存在的html文件,默认值: true
/// </summary>
public bool EnableOverrideHtml { get; set; } = true;
/// <summary>
/// 启动Razor监视服务时, 是否重新生成全部html文件,默认值: false
/// </summary>
public bool EnableGenerateAllHtml { get; set; }
/// <summary>
/// 启动超时间隔,默认值: 300 秒
/// </summary>
public TimeSpan StartupTimeout { get; set; } = TimeSpan.FromSeconds( 300 );
} | RazorOptions |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Services/Common/SearchTermService.cs | {
"start": 149,
"end": 559
} | public partial class ____ : ISearchTermService
{
#region Fields
protected readonly IRepository<SearchTerm> _searchTermRepository;
#endregion
#region Ctor
public SearchTermService(IRepository<SearchTerm> searchTermRepository)
{
_searchTermRepository = searchTermRepository;
}
#endregion
#region Methods
/// <summary>
/// Gets a search term | SearchTermService |
csharp | MassTransit__MassTransit | src/MassTransit/Util/Scanning/TypeQuery.cs | {
"start": 124,
"end": 627
} | public class ____
{
readonly TypeClassification _classification;
public readonly Func<Type, bool> Filter;
public TypeQuery(TypeClassification classification, Func<Type, bool> filter = null)
{
Filter = filter ?? (t => true);
_classification = classification;
}
public IEnumerable<Type> Find(AssemblyScanTypeInfo assembly)
{
return assembly.FindTypes(_classification).Where(Filter);
}
}
}
| TypeQuery |
csharp | dotnet__reactive | Ix.NET/Source/FasterLinq/Program.cs | {
"start": 6911,
"end": 7853
} | internal abstract class ____<T> : IEnumerable<T>, IEnumerator<T>
{
private readonly int _threadId;
internal int _state;
protected T _current;
protected Iterator()
{
_threadId = Environment.CurrentManagedThreadId;
}
public abstract Iterator<T> Clone();
public virtual void Dispose()
{
_state = -1;
}
public IEnumerator<T> GetEnumerator()
{
Iterator<T> enumerator = _state == 0 && _threadId == Environment.CurrentManagedThreadId ? this : Clone();
enumerator._state = 1;
return enumerator;
}
public abstract bool MoveNext();
public T Current => _current;
object IEnumerator.Current => _current;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void Reset() => throw new NotSupportedException();
}
| Iterator |
csharp | xunit__xunit | src/xunit.v3.assert.tests/Asserts/RangeAssertsTests.cs | {
"start": 2425,
"end": 3791
} | public class ____
{
[Fact]
public void DoubleNotWithinRange()
{
Assert.NotInRange(1.50, .75, 1.25);
}
[Fact]
public void DoubleWithinRange()
{
var ex = Record.Exception(() => Assert.NotInRange(1.0, .75, 1.25));
Assert.IsType<NotInRangeException>(ex);
Assert.Equal(
"Assert.NotInRange() Failure: Value in range" + Environment.NewLine +
"Range: (0.75 - 1.25)" + Environment.NewLine +
"Actual: 1",
ex.Message
);
}
[Fact]
public void IntNotWithinRange()
{
Assert.NotInRange(1, 2, 3);
}
[Fact]
public void IntWithinRange()
{
var ex = Record.Exception(() => Assert.NotInRange(2, 1, 3));
Assert.IsType<NotInRangeException>(ex);
Assert.Equal(
"Assert.NotInRange() Failure: Value in range" + Environment.NewLine +
"Range: (1 - 3)" + Environment.NewLine +
"Actual: 2",
ex.Message
);
}
[Fact]
public void StringNotWithNotInRange()
{
Assert.NotInRange("adam", "bob", "scott");
}
[Fact]
public void StringWithNotInRange()
{
var ex = Record.Exception(() => Assert.NotInRange("bob", "adam", "scott"));
Assert.IsType<NotInRangeException>(ex);
Assert.Equal(
"Assert.NotInRange() Failure: Value in range" + Environment.NewLine +
"Range: (\"adam\" - \"scott\")" + Environment.NewLine +
"Actual: \"bob\"",
ex.Message
);
}
}
| NotInRange |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Bugs/NullArguments.cs | {
"start": 3119,
"end": 3278
} | public class ____
{
public int? Id { get; set; }
public string Foo { get; set; }
public NullInputSubChildClass Bar { get; set; }
}
| NullInputChildClass |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs | {
"start": 1619,
"end": 2606
} | internal sealed class ____<TStateMachine> : IStateMachineRunner, ITaskPoolNode<AsyncUniTaskVoid<TStateMachine>>, IUniTaskSource
where TStateMachine : IAsyncStateMachine
{
static TaskPool<AsyncUniTaskVoid<TStateMachine>> pool;
#if ENABLE_IL2CPP
public Action ReturnAction { get; }
#endif
TStateMachine stateMachine;
public Action MoveNext { get; }
public AsyncUniTaskVoid()
{
MoveNext = Run;
#if ENABLE_IL2CPP
ReturnAction = Return;
#endif
}
public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunner runnerFieldRef)
{
if (!pool.TryPop(out var result))
{
result = new AsyncUniTaskVoid<TStateMachine>();
}
TaskTracker.TrackActiveTask(result, 3);
runnerFieldRef = result; // set runner before copied.
result.stateMachine = stateMachine; // copy | AsyncUniTaskVoid |
csharp | ChilliCream__graphql-platform | src/HotChocolate/AspNetCore/src/AspNetCore.Authorization.Opa/OpaOptions.cs | {
"start": 205,
"end": 267
} | class ____ OPA configuration options.
/// </summary>
| representing |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs | {
"start": 12045,
"end": 12209
} | public class ____
{
#if ROSLYN
public int this[int i] => 2;
#else
public int this[int i] {
get {
return 2;
}
}
#endif
}
| T31_A_HideIndexerDiffAccessor |
csharp | files-community__Files | src/Files.App/Data/Commands/Manager/CommandManager.cs | {
"start": 252,
"end": 5425
} | partial class ____ : ICommandManager
{
// Dependency injections
private IActionsSettingsService ActionsSettingsService { get; } = Ioc.Default.GetRequiredService<IActionsSettingsService>();
// Fields
private ImmutableDictionary<HotKey, IRichCommand> _allKeyBindings = new Dictionary<HotKey, IRichCommand>().ToImmutableDictionary();
public IRichCommand this[CommandCodes code] => commands.TryGetValue(code, out var command) ? command : None;
public IRichCommand this[string code]
{
get
{
try
{
return commands[Enum.Parse<CommandCodes>(code, true)];
}
catch
{
return None;
}
}
}
public IRichCommand this[HotKey hotKey]
=> _allKeyBindings.TryGetValue(hotKey with { IsVisible = true }, out var command) ? command
: _allKeyBindings.TryGetValue(hotKey with { IsVisible = false }, out command) ? command
: None;
public CommandManager()
{
commands = CreateActions()
.Select(action => new ActionCommand(this, action.Key, action.Value))
.Cast<IRichCommand>()
.Append(new NoneCommand())
.ToFrozenDictionary(command => command.Code);
ActionsSettingsService.PropertyChanged += (s, e) => { OverwriteKeyBindings(); };
OverwriteKeyBindings();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<IRichCommand> GetEnumerator() =>
(commands.Values as IEnumerable<IRichCommand>).GetEnumerator();
/// <summary>
/// Replaces default key binding collection with customized one(s) if exists.
/// </summary>
private void OverwriteKeyBindings()
{
var allCommands = commands.Values.OfType<ActionCommand>();
if (ActionsSettingsService.ActionsV2 is null)
{
allCommands.ForEach(x => x.RestoreKeyBindings());
}
else
{
foreach (var command in allCommands)
{
var customizedKeyBindings = ActionsSettingsService.ActionsV2.FindAll(x => x.CommandCode == command.Code.ToString());
if (customizedKeyBindings.IsEmpty())
{
// Could not find customized key bindings for the command
command.RestoreKeyBindings();
}
else if (customizedKeyBindings.Count == 1 && customizedKeyBindings[0].KeyBinding == string.Empty)
{
// Do not assign any key binding even though there're default keys pre-defined
command.OverwriteKeyBindings(HotKeyCollection.Empty);
}
else
{
var keyBindings = new HotKeyCollection(customizedKeyBindings.Select(x => HotKey.Parse(x.KeyBinding, false)));
command.OverwriteKeyBindings(keyBindings);
}
}
}
try
{
// Set collection of a set of command code and key bindings to dictionary
_allKeyBindings = commands.Values
.SelectMany(command => command.HotKeys, (command, hotKey) => (Command: command, HotKey: hotKey))
.ToImmutableDictionary(item => item.HotKey, item => item.Command);
}
catch (ArgumentException ex)
{
// The keys are not necessarily all different because they can be set manually in text editor
// ISSUE: https://github.com/files-community/Files/issues/15331
var flat = commands.Values.SelectMany(x => x.HotKeys).Select(x => x.LocalizedLabel);
var duplicates = flat.GroupBy(x => x).Where(x => x.Count() > 1).Select(group => group.Key);
foreach (var item in duplicates)
{
if (!string.IsNullOrEmpty(item))
{
var occurrences = allCommands.Where(x => x.HotKeys.Select(x => x.LocalizedLabel).Contains(item));
// Restore the defaults for all occurrences in our cache
occurrences.ForEach(x => x.RestoreKeyBindings());
// Get all customized key bindings from user settings json
var actions =
ActionsSettingsService.ActionsV2 is not null
? new List<ActionWithParameterItem>(ActionsSettingsService.ActionsV2)
: [];
// Remove the duplicated key binding from user settings JSON file
actions.RemoveAll(x => x.KeyBinding.Contains(item));
// Reset
ActionsSettingsService.ActionsV2 = actions;
}
}
// Set collection of a set of command code and key bindings to dictionary
_allKeyBindings = commands.Values
.SelectMany(command => command.HotKeys, (command, hotKey) => (Command: command, HotKey: hotKey))
.ToImmutableDictionary(item => item.HotKey, item => item.Command);
App.Logger.LogInformation(ex, "The app found some keys in different commands are duplicated and are using default key bindings for those commands.");
}
catch (Exception ex)
{
allCommands.ForEach(x => x.RestoreKeyBindings());
// Set collection of a set of command code and key bindings to dictionary
_allKeyBindings = commands.Values
.SelectMany(command => command.HotKeys, (command, hotKey) => (Command: command, HotKey: hotKey))
.ToImmutableDictionary(item => item.HotKey, item => item.Command);
App.Logger.LogWarning(ex, "The app is temporarily using default key bindings for all because of a serious error of assigning custom keys.");
}
}
public static HotKeyCollection GetDefaultKeyBindings(IAction action)
{
return new(action.HotKey, action.SecondHotKey, action.ThirdHotKey, action.MediaHotKey);
}
}
}
| CommandManager |
csharp | MassTransit__MassTransit | tests/MassTransit.Abstractions.Tests/NewId/LongTerm_Specs.cs | {
"start": 171,
"end": 1055
} | public class ____
{
[Test]
public void Should_keep_them_ordered_for_sql_server()
{
var generator = new NewIdGenerator(new TimeLapseTickProvider(), new NetworkAddressWorkerIdProvider());
generator.Next();
var limit = 1024;
var ids = new NewId[limit];
for (var i = 0; i < limit; i++)
ids[i] = generator.Next();
for (var i = 0; i < limit - 1; i++)
{
Assert.That(ids[i + 1], Is.Not.EqualTo(ids[i]));
SqlGuid left = ids[i].ToGuid();
SqlGuid right = ids[i + 1].ToGuid();
Assert.That(left, Is.LessThan(right));
if (i % 128 == 0)
Console.WriteLine("Normal: {0} Sql: {1}", left, ids[i].ToSequentialGuid());
}
}
| Generating_ids_over_time |
csharp | nuke-build__nuke | source/Nuke.Utilities/IO/AbsolutePath.Delete.cs | {
"start": 257,
"end": 1441
} | partial class ____
{
/// <summary>
/// Deletes the file when existent.
/// </summary>
public static void DeleteFile(this AbsolutePath path)
{
if (!path.FileExists())
return;
File.SetAttributes(path, FileAttributes.Normal);
File.Delete(path);
}
/// <summary>
/// Deletes the directory recursively when existent.
/// </summary>
public static void DeleteDirectory(this AbsolutePath path)
{
if (!path.DirectoryExists())
return;
Directory.GetFiles(path, "*", SearchOption.AllDirectories).ForEach(x => File.SetAttributes(x, FileAttributes.Normal));
Directory.Delete(path, recursive: true);
}
/// <summary>
/// Deletes directories recursively when existent.
/// </summary>
public static void DeleteFiles(this IEnumerable<AbsolutePath> paths)
{
paths.ForEach(x => x.DeleteFile());
}
/// <summary>
/// Deletes directories recursively when existent.
/// </summary>
public static void DeleteDirectories(this IEnumerable<AbsolutePath> paths)
{
paths.ForEach(x => x.DeleteDirectory());
}
}
| AbsolutePathExtensions |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/Messaging/Permissions.Messaging.cs | {
"start": 156,
"end": 583
} | public static class ____
{
public const string Self = "promotion.campaign";
public const string Read = "promotion.campaign.read";
public const string Update = "promotion.campaign.update";
public const string Create = "promotion.campaign.create";
public const string Delete = "promotion.campaign.delete";
}
| Campaign |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/test/Data.Projections.Tests/IntegrationTests.cs | {
"start": 14359,
"end": 14516
} | public class ____
{
[UseProjection]
public IQueryable<Foo> Foos
=> new Foo[] { new() { Bar = "A" }, new() { Bar = "B" } }.AsQueryable();
}
| Query |
csharp | duplicati__duplicati | Duplicati/Library/Interface/ICommandLineArgument.cs | {
"start": 1262,
"end": 1336
} | interface ____ to describe a commandline argument
/// </summary>
| used |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Oracle.Tests/OracleParamTests.cs | {
"start": 16182,
"end": 16448
} | public class ____ : Param<ParamDecimal>
{
public int Decimal { get; set; }
public override void SetValue(int value) { Decimal = value; }
public override ParamDecimal GetObject() { return this; }
}
| ParamDecimal |
csharp | dotnet__efcore | test/EFCore.Design.Tests/Query/CSharpToLinqTranslatorTest.cs | {
"start": 17251,
"end": 17322
} | public enum ____
{
One = 1,
Two = 2
}
| SomeEnum |
csharp | dotnet__efcore | test/EFCore.Sqlite.FunctionalTests/SqliteComplianceTest.cs | {
"start": 753,
"end": 1376
} | internal class ____ added
typeof(StoredProcedureUpdateTestBase), // SQLite doesn't support stored procedures
// All tests in the following test suites currently fail because of #26708
// (Stop generating composite keys for owned collections on SQLite)
typeof(OwnedNavigationsProjectionTestBase<>),
typeof(OwnedNavigationsProjectionRelationalTestBase<>),
typeof(OwnedJsonProjectionRelationalTestBase<>),
typeof(OwnedTableSplittingProjectionRelationalTestBase<>)
};
protected override Assembly TargetAssembly { get; } = typeof(SqliteComplianceTest).Assembly;
}
| is |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Facebook/PixelPermissionProvider.cs | {
"start": 74,
"end": 732
} | public sealed class ____ : IPermissionProvider
{
public static readonly Permission ManageFacebookPixelPermission = FacebookConstants.ManageFacebookPixelPermission;
private readonly IEnumerable<Permission> _allPermissions =
[
ManageFacebookPixelPermission,
];
public Task<IEnumerable<Permission>> GetPermissionsAsync()
=> Task.FromResult(_allPermissions);
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
[
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Administrator,
Permissions = _allPermissions,
},
];
}
| PixelPermissionProvider |
csharp | dotnet__aspnetcore | src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs | {
"start": 141438,
"end": 141916
} | private class ____ : IResult, IEndpointMetadataProvider
{
public static void PopulateMetadata(MethodInfo method, EndpointBuilder builder)
{
if (builder.ApplicationServices.GetRequiredService<MetadataService>() is { } metadataService)
{
builder.Metadata.Add(metadataService);
}
}
public Task ExecuteAsync(HttpContext httpContext) => Task.CompletedTask;
}
| AccessesServicesMetadataResult |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3109578,
"end": 3109971
} | public partial interface ____ : IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Deployment_Errors_1, IInvalidGraphQLSchemaError
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Deployment_Errors_InvalidGraphQLSchemaError |
csharp | grandnode__grandnode2 | src/Modules/Grand.Module.Api/DTOs/Shipping/PickupPointDto.cs | {
"start": 76,
"end": 422
} | public class ____ : BaseApiEntityModel
{
public string Name { get; set; }
public string Description { get; set; }
public string AdminComment { get; set; }
public string WarehouseId { get; set; }
public string StoreId { get; set; }
public double PickupFee { get; set; }
public int DisplayOrder { get; set; }
} | PickupPointDto |
csharp | nunit__nunit | src/NUnitFramework/framework/Constraints/CollectionTally.cs | {
"start": 635,
"end": 1070
} | public sealed class ____
{
/// <summary>Items that were not in the expected collection.</summary>
public List<object> ExtraItems { get; }
/// <summary>Items that were not accounted for in the expected collection.</summary>
public List<object> MissingItems { get; }
/// <summary>Initializes a new instance of the <see cref="CollectionTallyResult"/> | CollectionTallyResult |
csharp | NSubstitute__NSubstitute | tests/NSubstitute.Specs/Arguments/ParamsArgumentSpecificationFactorySpecs.cs | {
"start": 244,
"end": 1006
} | public class ____
{
//If default value
//If no argument specs and none for that type then just match literal value
//If no argument specs and has some for that type throw ambiguous
//If one argument spec that matches array type of parameter then return argument spec
//If one argument spec that doesn't match array type of parameter then throw ambiguous
//If more than one argument spec then throw ambiguous
//else
//If argument specs not all for array element type then throw ambiguous
//Call NonParamsArgSpecFactory with each child element then create ArrayContentsArgSpec
//If no argument specs then match literal values in array
| ParamsArgumentSpecificationFactorySpecs |
csharp | reactiveui__Akavache | src/Samples/CacheInvalidationPatterns.cs | {
"start": 18891,
"end": 19023
} | public class ____
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
| UserData |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 260277,
"end": 260497
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1197 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1199> ChildEntities { get; set; }
}
| RelatedEntity1198 |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 283817,
"end": 284037
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1304 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1306> ChildEntities { get; set; }
}
| RelatedEntity1305 |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Factories/IProductModelFactory.cs | {
"start": 155,
"end": 210
} | interface ____ the product model factory
/// </summary>
| of |
csharp | MassTransit__MassTransit | src/MassTransit/Configuration/Configuration/BindConfigurator.cs | {
"start": 63,
"end": 734
} | public class ____<TLeft> :
IBindConfigurator<TLeft>
where TLeft : class, PipeContext
{
readonly IPipeConfigurator<TLeft> _configurator;
public BindConfigurator(IPipeConfigurator<TLeft> configurator)
{
_configurator = configurator;
}
void IBindConfigurator<TLeft>.Source<T>(IPipeContextSource<T, TLeft> source, Action<IBindConfigurator<TLeft, T>> configureTarget)
{
var specification = new BindPipeSpecification<TLeft, T>(source);
configureTarget?.Invoke(specification);
_configurator.AddPipeSpecification(specification);
}
}
}
| BindConfigurator |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Execution/Nodes/IntrospectionExecutionNode.cs | {
"start": 136,
"end": 5586
} | public sealed class ____ : ExecutionNode
{
private readonly Selection[] _selections;
private readonly string[] _responseNames;
private readonly ExecutionNodeCondition[] _conditions;
public IntrospectionExecutionNode(
int id,
Selection[] selections,
ExecutionNodeCondition[] conditions)
{
ArgumentNullException.ThrowIfNull(selections);
if (selections.Length == 0)
{
throw new ArgumentException(
"There must be at least one introspection selection.",
nameof(selections));
}
Id = id;
_selections = selections;
_responseNames = selections.Select(t => t.ResponseName).ToArray();
_conditions = conditions;
}
/// <inheritdoc />
public override int Id { get; }
/// <inheritdoc />
public override ExecutionNodeType Type => ExecutionNodeType.Introspection;
/// <inheritdoc />
public override ReadOnlySpan<ExecutionNodeCondition> Conditions => _conditions;
/// <summary>
/// The introspection selections.
/// </summary>
public ReadOnlySpan<Selection> Selections => _selections;
protected override ValueTask<ExecutionStatus> OnExecuteAsync(
OperationPlanContext context,
CancellationToken cancellationToken = default)
{
var backlog = new Stack<(object? Parent, Selection Selection, SourceResultElementBuilder Result)>();
var resultBuilder = new SourceResultDocumentBuilder(context.OperationPlan.Operation, context.IncludeFlags);
var root = resultBuilder.Root;
var index = 0;
foreach (var selection in _selections)
{
if (selection.Resolver is null
|| !selection.Field.IsIntrospectionField
|| !selection.IsIncluded(context.IncludeFlags))
{
continue;
}
var property = root.CreateProperty(selection, index++);
backlog.Push((null, selection, property));
}
ExecuteSelections(context, backlog);
context.AddPartialResults(resultBuilder.Build(), _responseNames);
return new ValueTask<ExecutionStatus>(ExecutionStatus.Success);
}
protected override IDisposable CreateScope(OperationPlanContext context)
=> context.DiagnosticEvents.ExecuteIntrospectionNode(context, this);
private static void ExecuteSelections(
OperationPlanContext context,
Stack<(object? Parent, Selection Selection, SourceResultElementBuilder Result)> backlog)
{
var operation = context.OperationPlan.Operation;
var fieldContext = new ReusableFieldContext(
context.Schema,
context.Variables,
context.IncludeFlags,
context.CreateRentedBuffer());
while (backlog.TryPop(out var current))
{
var (parent, selection, result) = current;
fieldContext.Initialize(parent, selection, result);
selection.Resolver?.Invoke(fieldContext);
if (!selection.IsLeaf)
{
if (result.ValueKind is JsonValueKind.Object && selection.Type.IsObjectType())
{
var objectType = selection.Type.NamedType<IObjectTypeDefinition>();
var selectionSet = operation.GetSelectionSet(selection, objectType);
var j = 0;
for (var i = 0; i < selectionSet.Selections.Length; i++)
{
var childSelection = selectionSet.Selections[i];
if (!childSelection.IsIncluded(context.IncludeFlags))
{
continue;
}
var property = result.CreateProperty(childSelection, j++);
backlog.Push((fieldContext.RuntimeResults[0], childSelection, property));
}
}
else if (result.ValueKind is JsonValueKind.Array
&& selection.Type.IsListType()
&& selection.Type.NamedType().IsObjectType())
{
var objectType = selection.Type.NamedType<IObjectTypeDefinition>();
var selectionSet = operation.GetSelectionSet(selection, objectType);
var i = 0;
foreach (var element in result.EnumerateArray())
{
var runtimeResult = fieldContext.RuntimeResults[i++];
if (element.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
{
continue;
}
var k = 0;
for (var j = 0; j < selectionSet.Selections.Length; j++)
{
var childSelection = selectionSet.Selections[j];
if (!childSelection.IsIncluded(context.IncludeFlags))
{
continue;
}
var property = element.CreateProperty(childSelection, k++);
backlog.Push((runtimeResult, childSelection, property));
}
}
}
}
}
}
}
| IntrospectionExecutionNode |
csharp | dotnet__efcore | src/EFCore.Relational/Query/Internal/Translators/LikeTranslator.cs | {
"start": 744,
"end": 2910
} | public class ____ : IMethodCallTranslator
{
private static readonly MethodInfo MethodInfo
= typeof(DbFunctionsExtensions).GetRuntimeMethod(
nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)])!;
private static readonly MethodInfo MethodInfoWithEscape
= typeof(DbFunctionsExtensions).GetRuntimeMethod(
nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string), typeof(string)])!;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public LikeTranslator(ISqlExpressionFactory sqlExpressionFactory)
=> _sqlExpressionFactory = sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (Equals(method, MethodInfo))
{
return _sqlExpressionFactory.Like(arguments[1], arguments[2]);
}
return Equals(method, MethodInfoWithEscape)
? _sqlExpressionFactory.Like(arguments[1], arguments[2], arguments[3])
: null;
}
}
| LikeTranslator |
csharp | dotnet__aspnetcore | src/DataProtection/samples/KeyManagementSimulator/Program.cs | {
"start": 10775,
"end": 11455
} | sealed class ____ : IAuthenticatedEncryptor
{
byte[] IAuthenticatedEncryptor.Decrypt(ArraySegment<byte> ciphertext, ArraySegment<byte> _additionalAuthenticatedData) => ciphertext.ToArray();
byte[] IAuthenticatedEncryptor.Encrypt(ArraySegment<byte> plaintext, ArraySegment<byte> _additionalAuthenticatedData) => plaintext.ToArray();
}
/// <summary>
/// An almost trivial mock authenticated encryptor factory that always returns the same encryptor,
/// but not before ensuring that the key descriptor can be retrieved. This causes realistic failures
/// during default key resolution.
/// </summary>
/// <param name="authenticatedEncryptor"></param>
| MockAuthenticatedEncryptor |
csharp | bitwarden__server | src/Core/AdminConsole/Utilities/Commands/CommandResult.cs | {
"start": 169,
"end": 210
} | public abstract class ____<T>;
| CommandResult |
csharp | dotnetcore__FreeSql | Examples/base_entity/AspNetRoleClaims/AspNetUserLogins.cs | {
"start": 268,
"end": 1077
} | public partial class ____
{
[DisplayName("外联登录")]
[JsonProperty, Column(StringLength = -2, IsPrimary = true, IsNullable = false)]
public string LoginProvider { get; set; }
[DisplayName("用户ID")]
[JsonProperty, Column(StringLength = -2, IsNullable = false)]
public string UserId { get; set; }
[DisplayName("外联Key")]
[JsonProperty, Column(StringLength = -2, IsNullable = false)]
public string ProviderKey { get; set; }
[DisplayName("外联名称")]
[JsonProperty, Column(StringLength = -2)]
public string ProviderDisplayName { get; set; }
/// <summary>
/// 用户
/// </summary>
[Navigate(nameof(UserId))]
public virtual AspNetUsers AspNetUsers { get; set; }
}
} | AspNetUserLogins |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ApplicationModels/AuthorizationApplicationModelProviderTest.cs | {
"start": 456,
"end": 8632
} | public class ____
{
private readonly IOptions<MvcOptions> OptionsWithoutEndpointRouting = Options.Create(new MvcOptions { EnableEndpointRouting = false });
[Fact]
public void OnProvidersExecuting_AuthorizeAttribute_DoesNothing_WhenEnableRoutingIsEnabled()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
Options.Create(new MvcOptions()));
var controllerType = typeof(AccountController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
}
[Fact]
public void OnProvidersExecuting_AllowAnonymousAttribute_DoesNothing_WhenEnableRoutingIsEnabled()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
Options.Create(new MvcOptions()));
var controllerType = typeof(AnonymousController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
}
[Fact]
public void CreateControllerModel_AuthorizeAttributeAddsAuthorizeFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var controllerType = typeof(AccountController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Single(controller.Filters, f => f is AuthorizeFilter);
}
[Fact]
public void BuildActionModels_BaseAuthorizeFiltersAreStillValidWhenOverriden()
{
// Arrange
var options = Options.Create(new AuthorizationOptions());
options.Value.AddPolicy("Base", policy => policy.RequireClaim("Basic").RequireClaim("Basic2"));
options.Value.AddPolicy("Derived", policy => policy.RequireClaim("Derived"));
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(options),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(DerivedController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
var action = Assert.Single(controller.Actions);
Assert.Equal("Authorize", action.ActionName);
var attributeRoutes = action.Selectors.Where(sm => sm.AttributeRouteModel != null);
Assert.Empty(attributeRoutes);
var authorizeFilters = action.Filters.OfType<AuthorizeFilter>();
Assert.Single(authorizeFilters);
Assert.NotNull(authorizeFilters.First().Policy);
Assert.Equal(3, authorizeFilters.First().Policy.Requirements.Count()); // Basic + Basic2 + Derived authorize
}
[Fact]
public void CreateControllerModelAndActionModel_AllowAnonymousAttributeAddsAllowAnonymousFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(AnonymousController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Single(controller.Filters, f => f is AllowAnonymousFilter);
var action = Assert.Single(controller.Actions);
Assert.Single(action.Filters, f => f is AllowAnonymousFilter);
}
[Fact]
public void OnProvidersExecuting_DefaultPolicyProvider_NoAuthorizationData_NoFilterCreated()
{
// Arrange
var requirements = new IAuthorizationRequirement[]
{
new AssertionRequirement((con) => { return true; })
};
var authorizationPolicy = new AuthorizationPolicy(requirements, new string[] { "dingos" });
var authOptions = Options.Create(new AuthorizationOptions());
authOptions.Value.AddPolicy("Base", authorizationPolicy);
var policyProvider = new DefaultAuthorizationPolicyProvider(authOptions);
var provider = new AuthorizationApplicationModelProvider(policyProvider, OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(BaseController));
// Act
var action = GetBaseControllerActionModel(provider);
// Assert
var authorizationFilter = Assert.IsType<AuthorizeFilter>(Assert.Single(action.Filters));
Assert.NotNull(authorizationFilter.Policy);
Assert.Null(authorizationFilter.AuthorizeData);
Assert.Null(authorizationFilter.PolicyProvider);
}
[Fact]
public void OnProvidersExecuting_NonDefaultPolicyProvider_HasNoPolicy_HasPolicyProviderAndAuthorizeData()
{
// Arrange
var requirements = new IAuthorizationRequirement[]
{
new AssertionRequirement((con) => { return true; })
};
var authorizationPolicy = new AuthorizationPolicy(requirements, new string[] { "dingos" });
var authorizationPolicyProviderMock = new Mock<IAuthorizationPolicyProvider>();
authorizationPolicyProviderMock
.Setup(s => s.GetPolicyAsync(It.IsAny<string>()))
.Returns(Task.FromResult(authorizationPolicy))
.Verifiable();
var provider = new AuthorizationApplicationModelProvider(authorizationPolicyProviderMock.Object, OptionsWithoutEndpointRouting);
// Act
var action = GetBaseControllerActionModel(provider);
// Assert
var actionFilter = Assert.IsType<AuthorizeFilter>(Assert.Single(action.Filters));
Assert.Null(actionFilter.Policy);
Assert.NotNull(actionFilter.AuthorizeData);
Assert.NotNull(actionFilter.PolicyProvider);
}
[Fact]
public void CreateControllerModelAndActionModel_NoAuthNoFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(NoAuthController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
var action = Assert.Single(controller.Actions);
Assert.Empty(action.Filters);
}
private ActionModel GetBaseControllerActionModel(AuthorizationApplicationModelProvider authorizationApplicationModelProvider)
{
var context = CreateProviderContext(typeof(BaseController));
authorizationApplicationModelProvider.OnProvidersExecuting(context);
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
var action = Assert.Single(controller.Actions);
return action;
}
private static ApplicationModelProviderContext CreateProviderContext(Type controllerType)
{
var defaultProvider = new DefaultApplicationModelProvider(
Options.Create(new MvcOptions()),
new EmptyModelMetadataProvider());
var context = new ApplicationModelProviderContext(new[] { controllerType.GetTypeInfo() });
defaultProvider.OnProvidersExecuting(context);
return context;
}
| AuthorizationApplicationModelProviderTest |
csharp | dotnet__orleans | test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestGrainWithDifferentKeyTypes.verified.cs | {
"start": 26768,
"end": 27915
} | public sealed class ____ : global::Orleans.Serialization.Cloning.IDeepCopier<OrleansCodeGen.TestProject.Invokable_IMyGrainWithStringKey_GrainReference_43570316>
{
[global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public OrleansCodeGen.TestProject.Invokable_IMyGrainWithStringKey_GrainReference_43570316 DeepCopy(OrleansCodeGen.TestProject.Invokable_IMyGrainWithStringKey_GrainReference_43570316 original, global::Orleans.Serialization.Cloning.CopyContext context)
{
if (original is null)
return null;
var result = new OrleansCodeGen.TestProject.Invokable_IMyGrainWithStringKey_GrainReference_43570316();
return result;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("OrleansCodeGen", "10.0.0.0"), global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
| Copier_Invokable_IMyGrainWithStringKey_GrainReference_43570316 |
csharp | microsoft__garnet | libs/server/Resp/RespCommandKeySpecification.cs | {
"start": 3956,
"end": 4304
} | public abstract class ____ : IRespSerializable
{
/// <summary>
/// Name of the key specification method
/// </summary>
public abstract string MethodName { get; }
/// <inheritdoc />
public abstract void ToRespFormat(ref RespMemoryWriter writer);
}
/// <summary>
/// Base | KeySpecMethodBase |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Bson/Serialization/BsonCreatorMap.cs | {
"start": 2543,
"end": 11946
} | class ____ that this creator map belongs to.
/// </summary>
public BsonClassMap ClassMap
{
get { return _classMap; }
}
/// <summary>
/// Gets the delegeate
/// </summary>
public Delegate Delegate
{
get { return _delegate; }
}
/// <summary>
/// Gets the element names.
/// </summary>
public IEnumerable<string> ElementNames
{
get
{
if (!_isFrozen) { ThrowNotFrozenException(); }
return _elementNames;
}
}
/// <summary>
/// Gets the member info (null if none).
/// </summary>
public MemberInfo MemberInfo
{
get { return _memberInfo; }
}
// public methods
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null)) { return false; }
if (object.ReferenceEquals(this, obj)) { return true; }
// note: we can't compare _classMap(s) because that would result in infinite recursion
// note: if _memberInfo(s) are Equal we have to ignore the _delegate(s)
// so this is the best implementation we can have
return
GetType().Equals(obj.GetType()) &&
obj is BsonCreatorMap other &&
(_memberInfo != null && object.Equals(_memberInfo, other._memberInfo) || object.Equals(_delegate, other._delegate));
}
/// <summary>
/// Freezes the creator map.
/// </summary>
public void Freeze()
{
if (!_isFrozen)
{
var allMemberMaps = _classMap.AllMemberMaps;
var elementNames = new List<string>();
var defaultValues = new Dictionary<string, object>();
var expectedArgumentsCount = GetExpectedArgumentsCount();
if (_arguments != null)
{
if (_arguments.Count != expectedArgumentsCount)
{
throw new BsonSerializationException($"Creator map for class {_classMap.ClassType.FullName} has {expectedArgumentsCount} arguments, not {_arguments.Count}.");
}
foreach (var argument in _arguments)
{
var memberMap = allMemberMaps.FirstOrDefault(m => IsSameMember(m.MemberInfo, argument));
if (memberMap == null)
{
var message = string.Format("Member '{0}' is not mapped.", argument.Name);
throw new BsonSerializationException(message);
}
elementNames.Add(memberMap.ElementName);
if (memberMap.IsDefaultValueSpecified)
{
defaultValues.Add(memberMap.ElementName, memberMap.DefaultValue);
}
}
}
else
{
if (expectedArgumentsCount != 0)
{
throw new BsonSerializationException($"Creator map for class {_classMap.ClassType.FullName} has {expectedArgumentsCount} arguments, but none are configured.");
}
}
_elementNames = elementNames;
_defaultValues = defaultValues;
_isFrozen = true;
}
}
/// <inheritdoc/>
public override int GetHashCode() => 0;
/// <summary>
/// Gets whether there is a default value for a missing element.
/// </summary>
/// <param name="elementName">The element name.</param>
/// <returns>True if there is a default value for element name; otherwise, false.</returns>
public bool HasDefaultValue(string elementName)
{
if (!_isFrozen) { ThrowNotFrozenException(); }
return _defaultValues.ContainsKey(elementName);
}
/// <summary>
/// Sets the arguments for the creator map.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns>The creator map.</returns>
public BsonCreatorMap SetArguments(IEnumerable<MemberInfo> arguments)
{
if (arguments == null)
{
throw new ArgumentNullException("arguments");
}
if (_isFrozen) { ThrowFrozenException(); }
var argumentsList = arguments.ToList(); // only enumerate once
var expectedArgumentsCount = GetExpectedArgumentsCount();
if (argumentsList.Count != expectedArgumentsCount)
{
throw new ArgumentException($"Creator map for class {_classMap.ClassType.FullName} has {expectedArgumentsCount} arguments, not {argumentsList.Count}.", nameof(arguments));
}
_arguments = argumentsList;
return this;
}
/// <summary>
/// Sets the arguments for the creator map.
/// </summary>
/// <param name="argumentNames">The argument names.</param>
/// <returns>The creator map.</returns>
public BsonCreatorMap SetArguments(IEnumerable<string> argumentNames)
{
if (argumentNames == null)
{
throw new ArgumentNullException("argumentNames");
}
if (_isFrozen) { ThrowFrozenException(); }
var classTypeInfo = _classMap.ClassType.GetTypeInfo();
var arguments = new List<MemberInfo>();
foreach (var argumentName in argumentNames)
{
var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var memberInfos = classTypeInfo.GetMembers(bindingFlags)
.Where(m => m.Name == argumentName && (m is FieldInfo || m is PropertyInfo))
.ToArray();
if (memberInfos.Length == 0)
{
var message = string.Format("Class '{0}' does not have a member named '{1}'.", _classMap.ClassType.FullName, argumentName);
throw new BsonSerializationException(message);
}
else if (memberInfos.Length > 1)
{
var message = string.Format("Class '{0}' has more than one member named '{1}'.", _classMap.ClassType.FullName, argumentName);
throw new BsonSerializationException(message);
}
arguments.Add(memberInfos[0]);
}
SetArguments(arguments);
return this;
}
// internal methods
internal object CreateInstance(Dictionary<string, object> values)
{
var arguments = new List<object>();
// get the values for the arguments to be passed to the creator delegate
foreach (var elementName in _elementNames)
{
object argument;
if (values.TryGetValue(elementName, out argument))
{
values.Remove(elementName);
}
else if (!_defaultValues.TryGetValue(elementName, out argument))
{
// shouldn't happen unless there is a bug in ChooseBestCreator
throw new BsonInternalException();
}
arguments.Add(argument);
}
return _delegate.DynamicInvoke(arguments.ToArray());
}
// private methods
private int GetExpectedArgumentsCount()
{
var constructorInfo = _memberInfo as ConstructorInfo;
if (constructorInfo != null)
{
return constructorInfo.GetParameters().Length;
}
var methodInfo = _memberInfo as MethodInfo;
if (methodInfo != null)
{
return methodInfo.GetParameters().Length;
}
var delegateParameters = _delegate.GetMethodInfo().GetParameters();
if (delegateParameters.Length == 0)
{
return 0;
}
else
{
// check if delegate is closed over its first parameter
if (_delegate.Target != null && _delegate.Target.GetType() == delegateParameters[0].ParameterType)
{
return delegateParameters.Length - 1;
}
else
{
return delegateParameters.Length;
}
}
}
private bool IsSameMember(MemberInfo a, MemberInfo b)
{
// two MemberInfos refer to the same member if the Module and MetadataToken are equal
return a.Module == b.Module && a.MetadataToken == b.MetadataToken;
}
private void ThrowFrozenException()
{
throw new InvalidOperationException("BsonCreatorMap is frozen.");
}
private void ThrowNotFrozenException()
{
throw new InvalidOperationException("BsonCreatorMap is not frozen.");
}
}
}
| map |
csharp | App-vNext__Polly | src/Polly/RateLimit/RateLimitPolicy.cs | {
"start": 1004,
"end": 1874
} | public class ____<TResult> : Policy<TResult>, IRateLimitPolicy<TResult>
{
private readonly IRateLimiter _rateLimiter;
private readonly Func<TimeSpan, Context, TResult>? _retryAfterFactory;
internal RateLimitPolicy(
IRateLimiter rateLimiter,
Func<TimeSpan, Context, TResult>? retryAfterFactory)
{
_rateLimiter = rateLimiter;
_retryAfterFactory = retryAfterFactory;
}
/// <inheritdoc/>
[DebuggerStepThrough]
protected override TResult Implementation(Func<Context, CancellationToken, TResult> action, Context context, CancellationToken cancellationToken)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return RateLimitEngine.Implementation(_rateLimiter, _retryAfterFactory, action, context, cancellationToken);
}
}
| RateLimitPolicy |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/RoutingWebSite/Controllers/BanksController.cs | {
"start": 198,
"end": 1292
} | public class ____ : Controller
{
private readonly TestResponseGenerator _generator;
public BanksController(TestResponseGenerator generator)
{
_generator = generator;
}
[HttpGet("Banks/[action]/{id}")]
[HttpGet("Bank/[action]/{id}")]
public ActionResult Get(int id)
{
return _generator.Generate(
Url.Action(),
Url.RouteUrl(new { }));
}
[AcceptVerbs("PUT", Route = "Bank")]
[HttpPatch("Bank")]
[AcceptVerbs("PUT", Route = "Bank/Update")]
[HttpPatch("Bank/Update")]
public ActionResult UpdateBank()
{
return _generator.Generate(
Url.Action(),
Url.RouteUrl(new { }));
}
[AcceptVerbs("PUT", "POST")]
[Route("Bank/Deposit")]
[Route("Bank/Deposit/{amount}")]
public ActionResult Deposit()
{
return _generator.Generate("/Bank/Deposit", "/Bank/Deposit/5");
}
[HttpPost]
[Route("Bank/Withdraw/{id}")]
public ActionResult Withdraw(int id)
{
return _generator.Generate("/Bank/Withdraw/5");
}
}
| BanksController |
csharp | unoplatform__uno | src/Uno.Foundation/IAsyncAction.cs | {
"start": 241,
"end": 549
} | public partial interface ____ : IAsyncInfo
{
/// <summary>
/// Gets or sets the method that handles the action completed notification.
/// </summary>
AsyncActionCompletedHandler Completed { get; set; }
/// <summary>
/// Returns the results of the action.
/// </summary>
void GetResults();
}
| IAsyncAction |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Composition/Extensions/GroupingExtensions.cs | {
"start": 43,
"end": 329
} | internal static class ____
{
extension<TKey, TElement>(IGrouping<TKey, TElement> grouping)
{
public void Deconstruct(out TKey key, out IEnumerable<TElement> values)
{
key = grouping.Key;
values = grouping;
}
}
}
| GroupingExtensions |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/RelativePanelTests/RelativePanel_Simple.xaml.cs | {
"start": 172,
"end": 289
} | partial class ____ : Page
{
public RelativePanel_Simple()
{
InitializeComponent();
}
}
}
| RelativePanel_Simple |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs | {
"start": 59431,
"end": 59564
} | private class ____
{
[HttpGet("stub/[ActIon]")]
public void ThisIsAnAction() { }
}
| CaseInsensitiveController |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutorouteContentHandler.cs | {
"start": 208,
"end": 1369
} | public class ____ : ContentHandlerBase
{
private readonly IAutorouteEntries _autorouteEntries;
public AutorouteContentHandler(IAutorouteEntries autorouteEntries)
{
_autorouteEntries = autorouteEntries;
}
public override Task GetContentItemAspectAsync(ContentItemAspectContext context)
{
return context.ForAsync<ContentItemMetadata>(async metadata =>
{
// When a content item is contained we provide different route values when generating urls.
(var found, var entry) = await _autorouteEntries.TryGetEntryByContentItemIdAsync(context.ContentItem.ContentItemId);
if (found && !string.IsNullOrEmpty(entry.ContainedContentItemId))
{
metadata.DisplayRouteValues = new RouteValueDictionary {
{ "Area", "OrchardCore.Contents" },
{ "Controller", "Item" },
{ "Action", "Display" },
{ "ContentItemId", entry.ContentItemId},
{ "ContainedContentItemId", entry.ContainedContentItemId },
};
}
});
}
}
| AutorouteContentHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.