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
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/Storage/Scavenge/ScavengeLogManager/when_initialising.cs
{ "start": 4779, "end": 6677 }
public class ____<TLogFormat, TStreamId> : TestFixtureWithExistingEvents<TLogFormat, TStreamId> { private const string _nodeEndpoint = "localhost:2113"; private Guid _scavengeId = Guid.NewGuid(); private TFChunkScavengerLogManager _logManager; private TaskCompletionSource<ClientMessage.WriteEvents> _eventWritten = new(); private string _scavengeStreamId; protected override void Given1() { NoOtherStreams(); AllWritesSucceed(); _scavengeStreamId = ScavengerLogHelper.ScavengeStreamId(_scavengeId); _bus.Subscribe(new AdHocHandler<ClientMessage.WriteEvents>(m => { if (m.EventStreamIds.Single == _scavengeStreamId && m.Events.Single.EventType == SystemEventTypes.ScavengeCompleted) { _eventWritten.SetResult(m); } })); // Create the existing scavenge var scavengeHistoryMaxAge = TimeSpan.FromMinutes(5); ExistingStreamMetadata(SystemStreams.ScavengesStream, ScavengerLogHelper.CreateScavengeMetadata(scavengeHistoryMaxAge).ToJsonString()); var startedData = ScavengerLogHelper.CreateScavengeStarted(_scavengeId, _nodeEndpoint); // This should be a linkTo event pointing to the scavenge stream ExistingEvent(SystemStreams.ScavengesStream, SystemEventTypes.ScavengeStarted, "", startedData.ToJson(), true); _logManager = new TFChunkScavengerLogManager(_nodeEndpoint, scavengeHistoryMaxAge, _ioDispatcher); _logManager.Initialise(); } [Test] public async Task should_complete_the_scavenge_as_faulted() { var evnt = await _eventWritten.Task.WithTimeout(); var expectedData = ScavengerLogHelper.CreateScavengeInterruptedByRestart(_scavengeId, _nodeEndpoint, TimeSpan.Zero); Assert.AreEqual(expectedData.ToJson(), Encoding.UTF8.GetString(evnt.Events.Single.Data)); } } [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))]
when_previous_scavenge_was_interrupted_but_scavenge_stream_not_written
csharp
xunit__xunit
src/xunit.v3.common/Abstractions/Messages/Metadata/ITestCollectionMetadata.cs
{ "start": 135, "end": 1414 }
public interface ____ { /// <summary> /// Gets the type that the test collection was defined with, if available; may be <c>null</c> /// if the test collection didn't have a definition type. /// </summary> string? TestCollectionClassName { get; } /// <summary> /// Gets the display name of the test collection. /// </summary> string TestCollectionDisplayName { get; } /// <summary> /// Gets the trait values associated with this test collection (and the test assembly). /// If there are none, or the framework does not support traits, this returns an empty /// dictionary (not <c>null</c>). /// </summary> IReadOnlyDictionary<string, IReadOnlyCollection<string>> Traits { get; } /// <summary> /// Gets the unique ID for this test collection. /// </summary> /// <remarks> /// The unique identifier for a test collection should be able to discriminate among test collections /// in the same test assembly. This identifier should remain stable until such time as the developer /// changes some fundamental part of the identity (the test assembly, the collection definition /// class, or the collection name). Recompilation of the test assembly is reasonable as a stability /// changing event. /// </remarks> string UniqueID { get; } }
ITestCollectionMetadata
csharp
SixLabors__Fonts
tests/SixLabors.Fonts.Tests/Issues/Issues_363.cs
{ "start": 119, "end": 509 }
public class ____ { [Fact] public void GSubFormat2NUllReferenceException() { Font font = new FontCollection().Add(TestFonts.BNazaninFile).CreateFont(12); TextOptions textOptions = new(font); string text = "تست فونت 1234"; FontRectangle rect = TextMeasurer.MeasureAdvance(text, textOptions); Assert.NotEqual(default, rect); } }
Issues_363
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Administration/Application/MeetingGroupProposals/MeetingGroupProposedIntegrationEventHandler.cs
{ "start": 393, "end": 1336 }
internal class ____ : INotificationHandler<MeetingGroupProposedIntegrationEvent> { private readonly ICommandsScheduler _commandsScheduler; internal MeetingGroupProposedIntegrationEventHandler(ICommandsScheduler commandsScheduler) { _commandsScheduler = commandsScheduler; } public async Task Handle(MeetingGroupProposedIntegrationEvent notification, CancellationToken cancellationToken) { await _commandsScheduler.EnqueueAsync( new RequestMeetingGroupProposalVerificationCommand( Guid.NewGuid(), notification.MeetingGroupProposalId, notification.Name, notification.Description, notification.LocationCity, notification.LocationCountryCode, notification.ProposalUserId, notification.ProposalDate)); } } }
MeetingGroupProposedIntegrationEventHandler
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Specs/Routing/Handlers/ReturnResultForTypeHandlerSpecs.cs
{ "start": 1594, "end": 2181 }
public class ____ : When_handling_call { readonly Type _returnType = typeof(object); [Test] public void Should_continue_route() { Assert.That(_result, Is.SameAs(RouteAction.Continue())); } public override void Context() { base.Context(); _resultsForType.stub(x => x.HasResultFor(_call)).Return(false); _call.stub(x => x.GetReturnType()).Return(_returnType); } } } }
When_handling_call_without_configured_result
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Acceptance.Specs/Infrastructure/ISomethingWithGenericMethods.cs
{ "start": 56, "end": 183 }
public interface ____ { void Log<TState>(int level, TState state); string Format<T>(T state); }
ISomethingWithGenericMethods
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs
{ "start": 19682, "end": 20218 }
private class ____ : DbContext { protected NorthwindContextBase() { } protected NorthwindContextBase(DbContextOptions options) : base(options) { } public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Customer>(b => { b.HasKey(c => c.CustomerID); b.ToTable("Customers"); }); }
NorthwindContextBase
csharp
icsharpcode__ILSpy
ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs
{ "start": 1270, "end": 3367 }
internal static class ____ { public static bool IsPossibleReferenceTo(EntityHandle member, MetadataFile module, IMethod analyzedMethod) { if (member.IsNil) return false; MetadataReader metadata = module.Metadata; switch (member.Kind) { case HandleKind.MethodDefinition: return member == analyzedMethod.MetadataToken && module == analyzedMethod.ParentModule?.MetadataFile; case HandleKind.MemberReference: var mr = metadata.GetMemberReference((MemberReferenceHandle)member); if (mr.GetKind() != MemberReferenceKind.Method) return false; return metadata.StringComparer.Equals(mr.Name, analyzedMethod.Name); case HandleKind.MethodSpecification: var ms = metadata.GetMethodSpecification((MethodSpecificationHandle)member); return IsPossibleReferenceTo(ms.Method, module, analyzedMethod); default: return false; } } public static ISymbol? GetParentEntity(DecompilerTypeSystem ts, CustomAttribute customAttribute) { var metadata = ts.MainModule.MetadataFile.Metadata; switch (customAttribute.Parent.Kind) { case HandleKind.MethodDefinition: IMethod parent = (IMethod)ts.MainModule.ResolveEntity(customAttribute.Parent); return parent?.AccessorOwner ?? parent; case HandleKind.FieldDefinition: case HandleKind.PropertyDefinition: case HandleKind.EventDefinition: case HandleKind.TypeDefinition: return ts.MainModule.ResolveEntity(customAttribute.Parent); case HandleKind.AssemblyDefinition: case HandleKind.ModuleDefinition: return ts.MainModule; case HandleKind.GenericParameterConstraint: var gpc = metadata.GetGenericParameterConstraint((GenericParameterConstraintHandle)customAttribute.Parent); var gp = metadata.GetGenericParameter(gpc.Parameter); return ts.MainModule.ResolveEntity(gp.Parent); case HandleKind.GenericParameter: gp = metadata.GetGenericParameter((GenericParameterHandle)customAttribute.Parent); return ts.MainModule.ResolveEntity(gp.Parent); default: return null; } } } }
AnalyzerHelpers
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs
{ "start": 79674, "end": 80036 }
private class ____ : NotifyingBase { private ChildViewModel _child; public ChildViewModel Child { get { return _child; } set { _child = value; RaisePropertyChanged(); } } }
MasterViewModel
csharp
smartstore__Smartstore
src/Smartstore.Core/Checkout/Orders/Extensions/IOrderCalculationServiceExtensions.cs
{ "start": 223, "end": 3045 }
partial class ____ { /// <summary> /// Gets the discount amount and applied discount for a shipping total. /// </summary> /// <param name="orderCalculationService">Order calculation service.</param> /// <param name="shippingTotal">Shipping total amount.</param> /// <param name="customer">Customer.</param> /// <returns>The discount amount and applied discount.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Task<(Money Amount, Discount AppliedDiscount)> GetShippingDiscountAsync( this IOrderCalculationService orderCalculationService, Money shippingTotal, Customer customer) { Guard.NotNull(orderCalculationService, nameof(orderCalculationService)); return orderCalculationService.GetDiscountAmountAsync(shippingTotal, DiscountType.AssignedToShipping, customer); } /// <summary> /// Gets the discount amount and applied discount for an subtotal total. /// </summary> /// <param name="orderCalculationService">Order calculation service.</param> /// <param name="orderSubTotal">Order subtotal.</param> /// <param name="customer">Customer.</param> /// <returns>The discount amount and applied discount.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Task<(Money Amount, Discount AppliedDiscount)> GetOrderSubtotalDiscountAsync( this IOrderCalculationService orderCalculationService, Money orderSubTotal, Customer customer) { Guard.NotNull(orderCalculationService, nameof(orderCalculationService)); return orderCalculationService.GetDiscountAmountAsync(orderSubTotal, DiscountType.AssignedToOrderSubTotal, customer); } /// <summary> /// Gets the discount amount and applied discount for an order total. /// </summary> /// <param name="orderCalculationService">Order calculation service.</param> /// <param name="orderTotal">Order total.</param> /// <param name="customer">Customer.</param> /// <returns>The discount amount and applied discount.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Task<(Money Amount, Discount AppliedDiscount)> GetOrderTotalDiscountAsync( this IOrderCalculationService orderCalculationService, Money orderTotal, Customer customer) { Guard.NotNull(orderCalculationService, nameof(orderCalculationService)); return orderCalculationService.GetDiscountAmountAsync(orderTotal, DiscountType.AssignedToOrderTotal, customer); } } }
IOrderCalculationServiceExtensions
csharp
dotnet__aspnetcore
src/Mvc/test/WebSites/RoutingWebSite/ControllerRouteTokenTransformerConvention.cs
{ "start": 217, "end": 778 }
public class ____ : RouteTokenTransformerConvention { private readonly Type _controllerType; public ControllerRouteTokenTransformerConvention(Type controllerType, IOutboundParameterTransformer parameterTransformer) : base(parameterTransformer) { ArgumentNullException.ThrowIfNull(parameterTransformer); _controllerType = controllerType; } protected override bool ShouldApply(ActionModel action) { return action.Controller.ControllerType == _controllerType; } }
ControllerRouteTokenTransformerConvention
csharp
dotnet__aspire
src/Shared/StringUtils.cs
{ "start": 229, "end": 1247 }
internal static class ____ { public static bool TryGetUriFromDelimitedString([NotNullWhen(true)] string? input, string delimiter, [NotNullWhen(true)] out Uri? uri) { if (!string.IsNullOrEmpty(input) && input.Split(delimiter) is { Length: > 0 } splitInput && Uri.TryCreate(splitInput[0], UriKind.Absolute, out uri)) { return true; } else { uri = null; return false; } } public static string Escape(string value) { return HttpUtility.UrlEncode(value); } public static string Unescape(string value) { return HttpUtility.UrlDecode(value); } public static string RemoveSuffix(this string value, string suffix) { ArgumentNullException.ThrowIfNull(value); ArgumentNullException.ThrowIfNull(suffix); return value.EndsWith(suffix, StringComparison.Ordinal) ? value[..^suffix.Length] : value; } }
StringUtils
csharp
abpframework__abp
modules/docs/src/Volo.Docs.Application/Volo/Docs/DocsApplicationMappers.cs
{ "start": 1312, "end": 1604 }
public partial class ____ : MapperBase<Project, ProjectDto> { public override partial ProjectDto Map(Project source); public override partial void Map(Project source, ProjectDto destination); } [Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
ProjectToProjectDtoMapper
csharp
DuendeSoftware__IdentityServer
bff/src/Bff.Yarp/Internal/ProxyBffPluginLoader.cs
{ "start": 474, "end": 3089 }
internal sealed class ____( // This line has been commented out for issue: https://github.com/dotnet/runtime/issues/119883 //IOptionsMonitor<ProxyConfiguration> proxyConfigMonitor // Instead, we read directly from IConfiguration, which is updated when the config file changes. [FromKeyedServices(ServiceProviderKeys.ProxyConfigurationKey)] IConfiguration? config = null ) : IBffPluginLoader { //private ProxyConfiguration Current => proxyConfigMonitor.CurrentValue; private ProxyConfiguration Current => config?.Get<ProxyConfiguration>() ?? new ProxyConfiguration(); public IBffPlugin? LoadExtension(BffFrontendName name) { if (!Current.Frontends.TryGetValue(name, out var config)) { return null; } return new ProxyBffPlugin() { RemoteApis = config.RemoteApis.Select(MapFrom).ToArray() }; } private static RemoteApi MapFrom(RemoteApiConfiguration config) { Type? type = null; if (config.TokenRetrieverTypeName != null) { type = Type.GetType(config.TokenRetrieverTypeName); if (type == null) { throw new InvalidOperationException($"Type {config.TokenRetrieverTypeName} not found."); } if (!typeof(IAccessTokenRetriever).IsAssignableFrom(type)) { throw new InvalidOperationException($"Type {config.TokenRetrieverTypeName} must implement IAccessTokenRetriever."); } } var api = new RemoteApi { PathMatch = config.PathMatch ?? throw new InvalidOperationException($"{nameof(config.PathMatch)} cannot be empty"), TargetUri = config.TargetUri ?? throw new InvalidOperationException($"{nameof(config.TargetUri)} cannot be empty"), RequiredTokenType = config.RequiredTokenType, AccessTokenRetrieverType = type, ActivityTimeout = config.ActivityTimeout, AllowResponseBuffering = config.AllowResponseBuffering, Parameters = Map(config.UserAccessTokenParameters) }; return api; } private static BffUserAccessTokenParameters? Map(UserAccessTokenParameters? config) { if (config == null) { return null; } return new BffUserAccessTokenParameters { SignInScheme = config.SignInScheme, ChallengeScheme = config.ChallengeScheme, ForceRenewal = config.ForceRenewal, Resource = config.Resource }; } }
ProxyBffPluginLoader
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.UI/Middleware/UIApiRequestLimitingMiddleware.cs
{ "start": 181, "end": 1802 }
internal sealed class ____ : IDisposable { private readonly RequestDelegate _next; private readonly IOptions<Settings> _settings; private readonly ILogger<UIApiEndpointMiddleware> _logger; private readonly SemaphoreSlim _semaphore; private bool _disposed; public UIApiRequestLimitingMiddleware(RequestDelegate next, IOptions<Settings> settings, ILogger<UIApiEndpointMiddleware> logger) { _next = Guard.ThrowIfNull(next); _settings = Guard.ThrowIfNull(settings); _logger = Guard.ThrowIfNull(logger); var maxActiveRequests = _settings.Value.ApiMaxActiveRequests; if (maxActiveRequests <= 0) { throw new ArgumentOutOfRangeException(nameof(maxActiveRequests)); } _semaphore = new SemaphoreSlim(maxActiveRequests, maxActiveRequests); } public async Task InvokeAsync(HttpContext context) { if (!await _semaphore.WaitAsync(TimeSpan.Zero).ConfigureAwait(false)) { context.Response.StatusCode = StatusCodes.Status429TooManyRequests; return; } try { _logger.LogDebug("Executing api middleware for client {client}, remaining slots: {slots}", context.Connection.RemoteIpAddress, _semaphore.CurrentCount); await _next(context).ConfigureAwait(false); } finally { _semaphore.Release(); } } public void Dispose() { if (_disposed) { return; } _semaphore.Dispose(); _disposed = true; } }
UIApiRequestLimitingMiddleware
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/GridView/GridViewScrollIntoViewTest.xaml.cs
{ "start": 655, "end": 796 }
partial class ____ : UserControl { public GridViewScrollIntoViewTest() { this.InitializeComponent(); } } }
GridViewScrollIntoViewTest
csharp
MaterialDesignInXAML__MaterialDesignInXamlToolkit
tests/MaterialDesignThemes.UITests/TestBase.cs
{ "start": 852, "end": 2516 }
public abstract class ____() { protected bool AttachedDebuggerToRemoteProcess { get; set; } = true; protected static TextWriter Output => TestContext.Current?.OutputWriter ?? throw new InvalidOperationException("Could not find output writer"); [NotNull] protected IApp? App { get; set; } protected async Task<Color> GetThemeColor(string name) { IResource resource = await App.GetResource(name); return resource.GetAs<Color?>() ?? throw new Exception($"Failed to convert resource '{name}' to color"); } protected async Task<IVisualElement<T>> LoadXaml<T>(string xaml, params (string namespacePrefix, Type type)[] additionalNamespaceDeclarations) { await App.InitializeWithMaterialDesign(); return await App.CreateWindowWith<T>(xaml, additionalNamespaceDeclarations); } protected Task<IVisualElement> LoadUserControl<TControl>() where TControl : UserControl => LoadUserControl(typeof(TControl)); protected async Task<IVisualElement> LoadUserControl(Type userControlType) { await App.InitializeWithMaterialDesign(); return await App.CreateWindowWithUserControl(userControlType); } [Before(Test)] public async ValueTask InitializeAsync() => App = await XamlTest.App.StartRemote(new AppOptions { #if !DEBUG MinimizeOtherWindows = !System.Diagnostics.Debugger.IsAttached, #endif AllowVisualStudioDebuggerAttach = AttachedDebuggerToRemoteProcess, LogMessage = Output.WriteLine }); [After(Test)] public async ValueTask DisposeAsync() => await App.DisposeAsync(); }
TestBase
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Composition/Events/SchemaEvents.cs
{ "start": 560, "end": 751 }
internal record ____( MutableInputFieldDefinition Argument, MutableOutputFieldDefinition Field, ITypeDefinition Type, MutableSchemaDefinition Schema) : IEvent;
FieldArgumentEvent
csharp
microsoft__garnet
libs/server/OperationError.cs
{ "start": 173, "end": 566 }
public enum ____ : byte { /// <summary> /// Operation on data type succeeded /// </summary> SUCCESS, /// <summary> /// Operation failed due to incompatible type /// </summary> INVALID_TYPE, /// <summary> /// Operation failed due to NaN/infinity /// </summary> NAN_OR_INFINITY } }
OperationError
csharp
xunit__xunit
src/xunit.v3.assert.tests/Asserts/EqualityAssertsTests.cs
{ "start": 15639, "end": 20063 }
public class ____ { [Fact] public void Equal() { var obj1 = new SpyEquatable(); var obj2 = new SpyEquatable(); Assert.Equal(obj1, obj2); Assert.True(obj1.Equals__Called); Assert.Same(obj2, obj1.Equals_Other); } [Fact] public void NotEqual() { var obj1 = new SpyEquatable(false); var obj2 = new SpyEquatable(); var ex = Record.Exception(() => Assert.Equal(obj1, obj2)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: SpyEquatable { Equals__Called = True, Equals_Other = SpyEquatable { Equals__Called = False, Equals_Other = null } }" + Environment.NewLine + "Actual: SpyEquatable { Equals__Called = False, Equals_Other = null }", ex.Message ); } [Fact] public void SubClass_SubClass_Equal() { var expected = new EquatableSubClassA(1); var actual = new EquatableSubClassB(1); Assert.Equal<EquatableBaseClass>(expected, actual); } [Fact] public void SubClass_SubClass_NotEqual() { var expected = new EquatableSubClassA(1); var actual = new EquatableSubClassB(2); var ex = Record.Exception(() => Assert.Equal<EquatableBaseClass>(expected, actual)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: EquatableSubClassA { Value = 1 }" + Environment.NewLine + "Actual: EquatableSubClassB { Value = 2 }", ex.Message ); } [Fact] public void BaseClass_SubClass_Equal() { var expected = new EquatableBaseClass(1); var actual = new EquatableSubClassA(1); Assert.Equal(expected, actual); } [Fact] public void BaseClass_SubClass_NotEqual() { var expected = new EquatableBaseClass(1); var actual = new EquatableSubClassA(2); var ex = Record.Exception(() => Assert.Equal(expected, actual)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: EquatableBaseClass { Value = 1 }" + Environment.NewLine + "Actual: EquatableSubClassA { Value = 2 }", ex.Message ); } [Fact] public void SubClass_BaseClass_Equal() { var expected = new EquatableSubClassA(1); var actual = new EquatableBaseClass(1); Assert.Equal(expected, actual); } [Fact] public void SubClass_BaseClass_NotEqual() { var expected = new EquatableSubClassA(1); var actual = new EquatableBaseClass(2); var ex = Record.Exception(() => Assert.Equal(expected, actual)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: EquatableSubClassA { Value = 1 }" + Environment.NewLine + "Actual: EquatableBaseClass { Value = 2 }", ex.Message ); } [Fact] public void DifferentTypes_ImplicitImplementation_Equal() { object expected = new ImplicitIEquatableExpected(1); object actual = new IntWrapper(1); Assert.Equal(expected, actual); } [Fact] public void DifferentTypes_ImplicitImplementation_NotEqual() { object expected = new ImplicitIEquatableExpected(1); object actual = new IntWrapper(2); var ex = Record.Exception(() => Assert.Equal(expected, actual)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: ImplicitIEquatableExpected { Value = 1 }" + Environment.NewLine + "Actual: IntWrapper { Value = 2 }", ex.Message ); } [Fact] public void DifferentTypes_ExplicitImplementation_Equal() { object expected = new ExplicitIEquatableExpected(1); object actual = new IntWrapper(1); Assert.Equal(expected, actual); } [Fact] public void DifferentTypes_ExplicitImplementation_NotEqual() { object expected = new ExplicitIEquatableExpected(1); object actual = new IntWrapper(2); var ex = Record.Exception(() => Assert.Equal(expected, actual)); Assert.IsType<EqualException>(ex); Assert.Equal( "Assert.Equal() Failure: Values differ" + Environment.NewLine + "Expected: ExplicitIEquatableExpected { Value = 1 }" + Environment.NewLine + "Actual: IntWrapper { Value = 2 }", ex.Message ); } }
Equatable
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.AspNetCore.OpenApi/OpenApiTypeFormat.cs
{ "start": 44, "end": 506 }
public static class ____ { public const string Array = "int32"; public const string Byte = "byte"; public const string Binary = "binary"; public const string Date = "date"; public const string DateTime = "date-time"; public const string Double = "double"; public const string Float = "float"; public const string Int = "int32"; public const string Long = "int64"; public const string Password = "password"; }
OpenApiTypeFormat
csharp
neuecc__MessagePack-CSharp
sandbox/SharedData/Class1.cs
{ "start": 16223, "end": 16724 }
public struct ____ { [Key(0)] public float x; [Key(1)] public float y; [Key(2)] public float z; [SerializationConstructor] public Vector3Like(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public static Vector3Like operator *(Vector3Like a, float d) { return new Vector3Like(a.x * d, a.y * d, a.z * d); } }
Vector3Like
csharp
dotnet__aspire
src/Aspire.Hosting.Azure.EventHubs/ConfigFileAnnotation.cs
{ "start": 312, "end": 571 }
internal sealed class ____ : IResourceAnnotation { public ConfigFileAnnotation(string sourcePath) { SourcePath = sourcePath ?? throw new ArgumentNullException(nameof(sourcePath)); } public string SourcePath { get; } }
ConfigFileAnnotation
csharp
RicoSuter__NSwag
src/NSwagStudio/Controls/AvalonEditBehavior.cs
{ "start": 126, "end": 2021 }
public sealed class ____ : Behavior<TextEditor> { public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(AvalonEditBehavior), new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PropertyChangedCallback)); public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } protected override void OnAttached() { base.OnAttached(); if (AssociatedObject != null) AssociatedObject.TextChanged += AssociatedObjectOnTextChanged; } protected override void OnDetaching() { base.OnDetaching(); if (AssociatedObject != null) AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged; } private void AssociatedObjectOnTextChanged(object sender, EventArgs eventArgs) { var textEditor = sender as TextEditor; if (textEditor?.Document != null) Text = textEditor.Document.Text; } private static void PropertyChangedCallback( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var behavior = dependencyObject as AvalonEditBehavior; var editor = behavior?.AssociatedObject; if (editor?.Document != null) { var caretOffset = editor.CaretOffset; editor.Document.Text = dependencyPropertyChangedEventArgs.NewValue?.ToString() ?? string.Empty; if (editor.Document.Text.Length > caretOffset) editor.CaretOffset = caretOffset; } } } }
AvalonEditBehavior
csharp
DapperLib__Dapper
benchmarks/Dapper.Tests.Performance/PetaPoco/PetaPoco.cs
{ "start": 37031, "end": 40091 }
internal class ____ { public static PocoData ForType(Type t) { lock (m_PocoData) { if (!m_PocoData.TryGetValue(t, out PocoData pd)) { pd = new PocoData(t); m_PocoData.Add(t, pd); } return pd; } } public PocoData(Type t) { // Get the table name var a = t.GetCustomAttributes(typeof(TableName), true); var tempTableName = a.Length == 0 ? t.Name : (a[0] as TableName).Value; // Get the primary key a = t.GetCustomAttributes(typeof(PrimaryKey), true); var tempPrimaryKey = a.Length == 0 ? "ID" : (a[0] as PrimaryKey).Value; // Call column mapper Database.Mapper?.GetTableInfo(t, ref tempTableName, ref tempPrimaryKey); TableName = tempTableName; PrimaryKey = tempPrimaryKey; // Work out bound properties bool ExplicitColumns = t.GetCustomAttributes(typeof(ExplicitColumns), true).Length > 0; Columns = new Dictionary<string, PocoColumn>(StringComparer.OrdinalIgnoreCase); foreach (var pi in t.GetProperties()) { // Work out if properties is to be included var ColAttrs = pi.GetCustomAttributes(typeof(Column), true); if (ExplicitColumns) { if (ColAttrs.Length == 0) continue; } else { if (pi.GetCustomAttributes(typeof(Ignore), true).Length != 0) continue; } var pc = new PocoColumn() { PropertyInfo = pi }; // Work out the DB column name if (ColAttrs.Length > 0) { var colattr = (Column)ColAttrs[0]; pc.ColumnName = colattr.Name; if (colattr is ResultColumn) pc.ResultColumn = true; } if (pc.ColumnName == null) { pc.ColumnName = pi.Name; if (Mapper?.MapPropertyToColumn(pi, ref pc.ColumnName, ref pc.ResultColumn) == false) continue; } // Store it Columns.Add(pc.ColumnName, pc); } // Build column list for automatic select QueryColumns = string.Join(", ", (from c in Columns where !c.Value.ResultColumn select c.Key).ToArray()); } // Create factory function that can convert a IDataReader
PocoData
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs
{ "start": 1354, "end": 1551 }
interface ____ { bar: BarInterface } type Foo implements FooInterface { bar: Bar }
FooInterface
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs
{ "start": 35517, "end": 35773 }
public class ____ { public ObjectWithoutPublicCtor(string param) { Test1 = param; } public string Test1 { get; set; } public string Test2 { get; set; } }
ObjectWithoutPublicCtor
csharp
dotnet__aspnetcore
src/Http/Routing/test/testassets/RoutingSandbox/UseRouterStartup.cs
{ "start": 252, "end": 1569 }
public class ____ { private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(10); public void ConfigureServices(IServiceCollection services) { services.AddRouting(); } public void Configure(IApplicationBuilder app) { app.UseRouter(routes => { routes.DefaultHandler = new RouteHandler((httpContext) => { var request = httpContext.Request; return httpContext.Response.WriteAsync($"Verb = {request.Method.ToUpperInvariant()} - Path = {request.Path} - Route values - {string.Join(", ", httpContext.GetRouteData().Values)}"); }); routes.MapGet("api/get/{id}", (request, response, routeData) => response.WriteAsync($"API Get {routeData.Values["id"]}")) .MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Run(httpContext => httpContext.Response.WriteAsync("Middleware!"))) .MapRoute( name: "AllVerbs", template: "api/all/{name}/{lastName?}", defaults: new { lastName = "Doe" }, constraints: new { lastName = new RegexRouteConstraint(new Regex("[a-zA-Z]{3}", RegexOptions.CultureInvariant, RegexMatchTimeout)) }); }); } }
UseRouterStartup
csharp
DapperLib__Dapper
Dapper/SqlMapper.Async.cs
{ "start": 297, "end": 36373 }
partial class ____ { /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<IEnumerable<dynamic>> QueryAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryAsync<dynamic>(cnn, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default)); /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<IEnumerable<dynamic>> QueryAsync(this IDbConnection cnn, CommandDefinition command) => QueryAsync<dynamic>(cnn, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QueryFirstAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.First, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic?> QueryFirstOrDefaultAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic?>(cnn, Row.FirstOrDefault, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QuerySingleAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.Single, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic?> QuerySingleOrDefaultAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic?>(cnn, Row.SingleOrDefault, typeof(DapperRow), command); /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <typeparam name="T">The type of results to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <returns> /// A sequence of data of <typeparamref name="T"/>; if a basic type (int, string, etc) is queried then the data from the first column is assumed, otherwise an instance is /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive). /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryAsync<T>(cnn, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<T> QueryFirstAsync<T>(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.First, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<T?> QueryFirstOrDefaultAsync<T>(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T?>(cnn, Row.FirstOrDefault, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<T> QuerySingleAsync<T>(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.Single, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<T?> QuerySingleOrDefaultAsync<T>(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T?>(cnn, Row.SingleOrDefault, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<dynamic> QueryFirstAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.First, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<dynamic?> QueryFirstOrDefaultAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic?>(cnn, Row.FirstOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<dynamic> QuerySingleAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.Single, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<dynamic?> QuerySingleOrDefaultAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic?>(cnn, Row.SingleOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, Type type, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type is null) throw new ArgumentNullException(nameof(type)); return QueryAsync<object>(cnn, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default)); } /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<object> QueryFirstAsync(this IDbConnection cnn, Type type, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type is null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.First, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); } /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<object?> QueryFirstOrDefaultAsync(this IDbConnection cnn, Type type, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type is null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object?>(cnn, Row.FirstOrDefault, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); } /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<object> QuerySingleAsync(this IDbConnection cnn, Type type, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type is null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.Single, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); } /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Task<object?> QuerySingleOrDefaultAsync(this IDbConnection cnn, Type type, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type is null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object?>(cnn, Row.SingleOrDefault, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default)); } /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <returns> /// A sequence of data of <typeparamref name="T"/>; if a basic type (int, string, etc) is queried then the data from the first column is assumed, otherwise an instance is /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive). /// </returns> public static Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryAsync<T>(cnn, typeof(T), command); /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryAsync<object>(cnn, type, command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QueryFirstAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.First, type, command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QueryFirstAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.First, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object?> QueryFirstOrDefaultAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object?>(cnn, Row.FirstOrDefault, type, command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T?> QueryFirstOrDefaultAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T?>(cnn, Row.FirstOrDefault, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QuerySingleAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.Single, type, command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QuerySingleAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.Single, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object?> QuerySingleOrDefaultAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object?>(cnn, Row.SingleOrDefault, type, command); /// <summary> /// Execute a single-row query asynchronously using Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T?> QuerySingleOrDefaultAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T?>(cnn, Row.SingleOrDefault, typeof(T), command); private static Task<DbDataReader> ExecuteReaderWithFlagsFallbackAsync(DbCommand cmd, bool wasClosed, CommandBehavior behavior, CancellationToken cancellationToken) { var task = cmd.ExecuteReaderAsync(GetBehavior(wasClosed, behavior), cancellationToken); if (task.Status == TaskStatus.Faulted && Settings.DisableCommandBehaviorOptimizations(behavior, task.Exception!.InnerException!)) { // we can retry; this time it will have different flags return cmd.ExecuteReaderAsync(GetBehavior(wasClosed, behavior), cancellationToken); } return task; } /// <summary> /// Attempts to open a connection asynchronously, with a better error message for unsupported usages. /// </summary> private static Task TryOpenAsync(this IDbConnection cnn, CancellationToken cancel) { if (cnn is DbConnection dbConn) { return dbConn.OpenAsync(cancel); } else { throw new InvalidOperationException("Async operations require use of a DbConnection or an already-open IDbConnection"); } } /// <summary> /// Attempts setup a <see cref="DbCommand"/> on a <see cref="DbConnection"/>, with a better error message for unsupported usages. /// </summary> private static DbCommand TrySetupAsyncCommand(this CommandDefinition command, IDbConnection cnn, Action<IDbCommand, object?>? paramReader) { if (command.SetupCommand(cnn, paramReader) is DbCommand dbCommand) { return dbCommand; } else { throw new InvalidOperationException("Async operations require use of a DbConnection or an IDbConnection where .CreateCommand() returns a DbCommand"); } } private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command) { object? param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandTypeDirect, cnn, effectiveType, param?.GetType()); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; var cancel = command.CancellationToken; using var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader); DbDataReader? reader = null; try { if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false); reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, cancel).ConfigureAwait(false); var tuple = info.Deserializer; int hash = GetColumnHash(reader); if (tuple.Func is null || tuple.Hash != hash) { if (reader.FieldCount == 0) return Enumerable.Empty<T>(); tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false)); if (command.AddToCache) SetQueryCache(identity, info); } var func = tuple.Func; if (command.Buffered) { var buffer = new List<T>(); var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType; while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { object val = func(reader); buffer.Add(GetValue<T>(reader, effectiveType, val)); } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ } command.OnCompleted(); return buffer; } else { // can't use ReadAsync / cancellation; but this will have to do wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior var deferred = ExecuteReaderSync<T>(reader, func, command.Parameters); reader = null; // to prevent it being disposed before the caller gets to see it return deferred; } } finally { using (reader) { /* dispose if non-null */ } if (wasClosed) cnn.Close(); } } private static async Task<T> QueryRowAsync<T>(this IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) { object? param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandTypeDirect, cnn, effectiveType, param?.GetType()); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; var cancel = command.CancellationToken; using var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader); DbDataReader? reader = null; try { if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false); reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, (row & Row.Single) != 0 ? CommandBehavior.SequentialAccess | CommandBehavior.SingleResult // need to allow multiple rows, to check fail condition : CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow, cancel).ConfigureAwait(false); T result = default!; if (await reader.ReadAsync(cancel).ConfigureAwait(false) && reader.FieldCount != 0) { result = ReadRow<T>(info, identity, ref command, effectiveType, reader); if ((row & Row.Single) != 0 && await reader.ReadAsync(cancel).ConfigureAwait(false)) ThrowMultipleRows(row); while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { /* ignore rows after the first */ } } else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one { ThrowZeroRows(row); } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore result sets after the first */ } command.OnCompleted(); return result; } finally { using (reader) { /* dispose if non-null */ } if (wasClosed) cnn.Close(); } } /// <summary> /// Execute a command asynchronously using Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>The number of rows affected.</returns> public static Task<int> ExecuteAsync(this IDbConnection cnn, string sql, object? param = null, IDbTransaction? transaction = null, int? commandTimeout = null, CommandType? commandType = null) => ExecuteAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default)); /// <summary> /// Execute a command asynchronously using Task. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute on this connection.</param> /// <returns>The number of rows affected.</returns> public static Task<int> ExecuteAsync(this IDbConnection cnn, CommandDefinition command) { object? param = command.Parameters; IEnumerable? multiExec = GetMultiExec(param); if (multiExec is not null) { return ExecuteMultiImplAsync(cnn, command, multiExec); } else { return ExecuteImplAsync(cnn, command, param); } } private readonly
SqlMapper
csharp
dotnet__aspnetcore
src/SignalR/server/StackExchangeRedis/src/Internal/RedisCompletion.cs
{ "start": 247, "end": 564 }
struct ____ { public ReadOnlySequence<byte> CompletionMessage { get; } public string ProtocolName { get; } public RedisCompletion(string protocolName, ReadOnlySequence<byte> completionMessage) { ProtocolName = protocolName; CompletionMessage = completionMessage; } }
RedisCompletion
csharp
dotnet__machinelearning
docs/samples/Microsoft.ML.AutoML.Samples/Sweepable/SearchSpaceExample.cs
{ "start": 1740, "end": 2310 }
public class ____ { [Range((int)-10, 10, 0, false)] public int IntOption { get; set; } [Range(1f, 10f, 1f, true)] public float SingleOption { get; set; } [Range(-10, 10, false)] public double DoubleOption { get; set; } [BooleanChoice] public bool BoolOption { get; set; } [Choice("a", "b", "c")] public string StrOption { get; set; } [NestOption] public NestParameter Nest { get; set; } }
MyParameter
csharp
cake-build__cake
src/Cake.Common.Tests/Fixtures/Build/BambooFixture.cs
{ "start": 323, "end": 985 }
internal sealed class ____ { public ICakeEnvironment Environment { get; set; } public BambooFixture() { Environment = Substitute.For<ICakeEnvironment>(); Environment.WorkingDirectory.Returns("C:\\build\\CAKE-CAKE-JOB1"); Environment.GetEnvironmentVariable("bamboo_buildNumber").Returns((string)null); } public void IsRunningOnBamboo() { Environment.GetEnvironmentVariable("bamboo_buildNumber").Returns("28"); } public BambooProvider CreateBambooService() { return new BambooProvider(Environment); } } }
BambooFixture
csharp
restsharp__RestSharp
src/RestSharp/RestClient.cs
{ "start": 1276, "end": 13652 }
public partial class ____ : IRestClient { /// <summary> /// Content types that will be sent in the Accept header. The list is populated from the known serializers. /// If you need to send something else by default, set this property to a different value. /// </summary> public string[] AcceptedContentTypes { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } internal HttpClient HttpClient { get; } /// <inheritdoc />> public ReadOnlyRestClientOptions Options { get; } /// <inheritdoc />> public RestSerializers Serializers { get; private set; } /// <inheritdoc/> public DefaultParameters DefaultParameters { get; } /// <summary> /// Creates an instance of RestClient using the provided <see cref="RestClientOptions"/> /// </summary> /// <param name="options">Client options</param> /// <param name="configureDefaultHeaders">Delegate to add default headers to the wrapped HttpClient instance</param> /// <param name="configureSerialization">Delegate to configure serialization</param> /// <param name="useClientFactory">Set to true if you wish to reuse the <seealso cref="HttpClient"/> instance</param> public RestClient( RestClientOptions options, ConfigureHeaders? configureDefaultHeaders = null, ConfigureSerialization? configureSerialization = null, bool useClientFactory = false ) { if (useClientFactory && options.BaseUrl == null) { throw new ArgumentException("BaseUrl must be set when using a client factory"); } ConfigureSerializers(configureSerialization); Options = new(options); DefaultParameters = new(Options); if (useClientFactory) { _disposeHttpClient = false; HttpClient = SimpleClientFactory.GetClient(options.BaseUrl!, GetClient); } else { _disposeHttpClient = true; HttpClient = GetClient(); } return; HttpClient GetClient() { var handler = new HttpClientHandler(); ConfigureHttpMessageHandler(handler, options); var finalHandler = options.ConfigureMessageHandler?.Invoke(handler) ?? handler; var httpClient = new HttpClient(finalHandler); ConfigureHttpClient(httpClient, options); // We will use Options.Timeout in ExecuteAsInternalAsync method httpClient.Timeout = Timeout.InfiniteTimeSpan; ConfigureDefaultParameters(options); configureDefaultHeaders?.Invoke(httpClient.DefaultRequestHeaders); return httpClient; } } static RestClientOptions ConfigureOptions(RestClientOptions options, ConfigureRestClient? configureRestClient) { configureRestClient?.Invoke(options); return options; } /// <summary> /// Creates an instance of RestClient using the default <see cref="RestClientOptions"/> /// </summary> /// <param name="configureRestClient">Delegate to configure the client options</param> /// <param name="configureDefaultHeaders">Delegate to add default headers to the wrapped HttpClient instance</param> /// <param name="configureSerialization">Delegate to configure serialization</param> /// <param name="useClientFactory">Set to true if you wish to reuse the <seealso cref="HttpClient"/> instance</param> public RestClient( ConfigureRestClient? configureRestClient = null, ConfigureHeaders? configureDefaultHeaders = null, ConfigureSerialization? configureSerialization = null, bool useClientFactory = false ) : this(ConfigureOptions(new(), configureRestClient), configureDefaultHeaders, configureSerialization, useClientFactory) { } /// <inheritdoc /> /// <summary> /// Creates an instance of RestClient using a specific BaseUrl for requests made by this client instance /// </summary> /// <param name="baseUrl">Base URI for the new client</param> /// <param name="configureRestClient">Delegate to configure the client options</param> /// <param name="configureDefaultHeaders">Delegate to add default headers to the wrapped HttpClient instance</param> /// <param name="configureSerialization">Delegate to configure serialization</param> /// <param name="useClientFactory">Set to true if you wish to reuse the <seealso cref="HttpClient"/> instance</param> public RestClient( Uri baseUrl, ConfigureRestClient? configureRestClient = null, ConfigureHeaders? configureDefaultHeaders = null, ConfigureSerialization? configureSerialization = null, bool useClientFactory = false ) : this( ConfigureOptions(new() { BaseUrl = baseUrl }, configureRestClient), configureDefaultHeaders, configureSerialization, useClientFactory ) { } /// <summary> /// Creates an instance of RestClient using a specific BaseUrl for requests made by this client instance /// </summary> /// <param name="baseUrl">Base URI for this new client as a string</param> /// <param name="configureRestClient">Delegate to configure the client options</param> /// <param name="configureDefaultHeaders">Delegate to add default headers to the wrapped HttpClient instance</param> /// <param name="configureSerialization">Delegate to configure serialization</param> public RestClient( string baseUrl, ConfigureRestClient? configureRestClient = null, ConfigureHeaders? configureDefaultHeaders = null, ConfigureSerialization? configureSerialization = null ) : this(new Uri(Ensure.NotEmptyString(baseUrl, nameof(baseUrl))), configureRestClient, configureDefaultHeaders, configureSerialization) { } /// <summary> /// Creates an instance of RestClient using a shared HttpClient and specific RestClientOptions and does not allocate one internally. /// </summary> /// <param name="httpClient">HttpClient to use</param> /// <param name="options">RestClient options to use</param> /// <param name="disposeHttpClient">True to dispose of the client, false to assume the caller does (defaults to false)</param> /// <param name="configureSerialization">Delegate to configure serialization</param> public RestClient( HttpClient httpClient, RestClientOptions? options, bool disposeHttpClient = false, ConfigureSerialization? configureSerialization = null ) { ConfigureSerializers(configureSerialization); HttpClient = httpClient; _disposeHttpClient = disposeHttpClient; if (httpClient.BaseAddress != null && options != null && options.BaseUrl == null) { options.BaseUrl = httpClient.BaseAddress; } var opt = options ?? new RestClientOptions(); Options = new(opt); DefaultParameters = new(Options); if (options != null) { ConfigureHttpClient(httpClient, options); ConfigureDefaultParameters(options); } } /// <summary> /// Creates an instance of RestClient using a shared HttpClient and does not allocate one internally. /// </summary> /// <param name="httpClient">HttpClient to use</param> /// <param name="disposeHttpClient">True to dispose of the client, false to assume the caller does (defaults to false)</param> /// <param name="configureRestClient">Delegate to configure the client options</param> /// <param name="configureSerialization">Delegate to configure serialization</param> public RestClient( HttpClient httpClient, bool disposeHttpClient = false, ConfigureRestClient? configureRestClient = null, ConfigureSerialization? configureSerialization = null ) : this(httpClient, ConfigureOptions(new(), configureRestClient), disposeHttpClient, configureSerialization) { } /// <summary> /// Creates a new instance of RestSharp using the message handler provided. By default, HttpClient disposes the provided handler /// when the client itself is disposed. If you want to keep the handler not disposed, set disposeHandler argument to false. /// </summary> /// <param name="handler">Message handler instance to use for HttpClient</param> /// <param name="disposeHandler">Dispose the handler when disposing RestClient, true by default</param> /// <param name="configureRestClient">Delegate to configure the client options</param> /// <param name="configureSerialization">Delegate to configure serialization</param> public RestClient( HttpMessageHandler handler, bool disposeHandler = true, ConfigureRestClient? configureRestClient = null, ConfigureSerialization? configureSerialization = null ) : this(new HttpClient(handler, disposeHandler), true, configureRestClient, configureSerialization) { } internal static void ConfigureHttpClient(HttpClient httpClient, RestClientOptions options) { if (options.Expect100Continue != null) httpClient.DefaultRequestHeaders.ExpectContinue = options.Expect100Continue; } // ReSharper disable once CognitiveComplexity internal static void ConfigureHttpMessageHandler(HttpClientHandler handler, RestClientOptions options) { #if NET if (!OperatingSystem.IsBrowser()) { #endif handler.UseCookies = false; handler.Credentials = options.Credentials; handler.UseDefaultCredentials = options.UseDefaultCredentials; handler.AutomaticDecompression = options.AutomaticDecompression; handler.PreAuthenticate = options.PreAuthenticate; if (options.MaxRedirects.HasValue) handler.MaxAutomaticRedirections = options.MaxRedirects.Value; if (options.RemoteCertificateValidationCallback != null) handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => options.RemoteCertificateValidationCallback(request, cert, chain, errors); if (options.ClientCertificates != null) { handler.ClientCertificates.AddRange(options.ClientCertificates); handler.ClientCertificateOptions = ClientCertificateOption.Manual; } #if NET } #endif handler.AllowAutoRedirect = options.FollowRedirects; #if NET // ReSharper disable once InvertIf if (!OperatingSystem.IsBrowser() && !OperatingSystem.IsIOS() && !OperatingSystem.IsTvOS()) { #endif if (handler.SupportsProxy) handler.Proxy = options.Proxy; #if NET } #endif } [MemberNotNull(nameof(Serializers))] [MemberNotNull(nameof(AcceptedContentTypes))] void ConfigureSerializers(ConfigureSerialization? configureSerialization) { var serializerConfig = new SerializerConfig(); serializerConfig.UseDefaultSerializers(); configureSerialization?.Invoke(serializerConfig); Serializers = new(serializerConfig); AcceptedContentTypes = Serializers.GetAcceptedContentTypes(); } void ConfigureDefaultParameters(RestClientOptions options) { if (options.UserAgent == null) return; if (!options.AllowMultipleDefaultParametersWithSameName && DefaultParameters.Any(parameter => parameter is { Type: ParameterType.HttpHeader, Name: KnownHeaders.UserAgent })) DefaultParameters.RemoveParameter(KnownHeaders.UserAgent, ParameterType.HttpHeader); DefaultParameters.AddParameter(Parameter.CreateParameter(KnownHeaders.UserAgent, options.UserAgent, ParameterType.HttpHeader)); } readonly bool _disposeHttpClient; bool _disposed; protected virtual void Dispose(bool disposing) { if (!disposing || _disposed) return; _disposed = true; if (_disposeHttpClient) HttpClient.Dispose(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } }
RestClient
csharp
dotnet__orleans
src/Orleans.Serialization/ISerializableSerializer/SerializationCallbacksFactory.cs
{ "start": 5149, "end": 6977 }
public sealed class ____<TDelegate> { /// <summary> /// Initializes a new instance of the <see cref="SerializationCallbacks{TDelegate}"/> class. /// </summary> /// <param name="onDeserializing">The callback invoked during deserialization.</param> /// <param name="onDeserialized">The callback invoked once a value is deserialized.</param> /// <param name="onSerializing">The callback invoked during serialization.</param> /// <param name="onSerialized">The callback invoked once a value is serialized.</param> public SerializationCallbacks( TDelegate onDeserializing, TDelegate onDeserialized, TDelegate onSerializing, TDelegate onSerialized) { OnDeserializing = onDeserializing; OnDeserialized = onDeserialized; OnSerializing = onSerializing; OnSerialized = onSerialized; } /// <summary> /// Gets the callback invoked while deserializing. /// </summary> public readonly TDelegate OnDeserializing; /// <summary> /// Gets the callback invoked once a value has been deserialized. /// </summary> public readonly TDelegate OnDeserialized; /// <summary> /// Gets the callback invoked during serialization. /// </summary> /// <value>The on serializing.</value> public readonly TDelegate OnSerializing; /// <summary> /// Gets the callback invoked once a value has been serialized. /// </summary> public readonly TDelegate OnSerialized; } } }
SerializationCallbacks
csharp
MassTransit__MassTransit
src/MassTransit/DependencyInjection/Configuration/DependencyInjectionEndpointRegistrationExtensions.cs
{ "start": 987, "end": 2105 }
class ____ TDefinition : class, IEndpointDefinition<T> { return new EndpointRegistrar<TDefinition, T>(registration).Register(registrar, settings); } public static IEndpointRegistration RegisterEndpoint(this IServiceCollection collection, Type endpointDefinitionType) { return RegisterEndpoint(collection, new DependencyInjectionContainerRegistrar(collection), endpointDefinitionType); } public static IEndpointRegistration RegisterEndpoint(this IServiceCollection collection, IContainerRegistrar registrar, Type endpointDefinitionType) { if (!endpointDefinitionType.ClosesType(typeof(IEndpointDefinition<>), out Type[] types)) throw new ArgumentException($"{TypeCache.GetShortName(endpointDefinitionType)} is not an endpoint definition", nameof(endpointDefinitionType)); var register = (IEndpointRegistrar)Activator.CreateInstance(typeof(EndpointRegistrar<,>).MakeGenericType(endpointDefinitionType, types[0])); return register.Register(registrar); }
where
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ImageTests/Image_Placeholder.xaml.cs
{ "start": 1076, "end": 1692 }
public class ____ : INotifyPropertyChanged { private string _uri; private string _label; public event PropertyChangedEventHandler PropertyChanged; public string Label { get => _label; set { if (_label != value) { _label = value; OnPropertyChanged(); } } } public string Uri { get => _uri; set { if (_uri != value) { _uri = value; OnPropertyChanged(); } } } private void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
ViewModel
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs
{ "start": 1459, "end": 23170 }
public static class ____ { /// <summary> /// Routing singleton and global config types used to isolate tenants from the host. /// </summary> private static readonly Type[] _routingTypesToIsolate = new ServiceCollection() .AddRouting() .Where(sd => sd.Lifetime == ServiceLifetime.Singleton || sd.ServiceType == typeof(IConfigureOptions<RouteOptions>)) .Select(sd => sd.GetImplementationType()) .ToArray(); /// <summary> /// Http client singleton types used to isolate tenants from the host. /// </summary> private static readonly Type[] _httpClientTypesToIsolate = new ServiceCollection() .AddHttpClient() .Where(sd => sd.Lifetime == ServiceLifetime.Singleton) .Select(sd => sd.GetImplementationType()) .Except(new ServiceCollection() .AddLogging() .Where(sd => sd.Lifetime == ServiceLifetime.Singleton) .Select(sd => sd.GetImplementationType())) .ToArray(); /// <summary> /// Metrics singletons used to isolate tenants from the host. /// </summary> private static readonly Type[] _metricsTypesToIsolate = new ServiceCollection() .AddMetrics() .Where(sd => sd.Lifetime == ServiceLifetime.Singleton) .Select(sd => sd.GetImplementationType()) .ToArray(); /// <summary> /// Adds OrchardCore services to the host service collection. /// </summary> public static OrchardCoreBuilder AddOrchardCore(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); // If an instance of OrchardCoreBuilder exists reuse it, // so we can call AddOrchardCore several times. var builder = services .LastOrDefault(d => d.ServiceType == typeof(OrchardCoreBuilder))? .ImplementationInstance as OrchardCoreBuilder; if (builder == null) { builder = new OrchardCoreBuilder(services); services.AddSingleton(builder); AddDefaultServices(builder); AddShellServices(builder); AddExtensionServices(builder); AddStaticFiles(builder); AddMetrics(builder); AddRouting(builder); IsolateHttpClient(builder); AddEndpointsApiExplorer(builder); AddAntiForgery(builder); AddSameSiteCookieBackwardsCompatibility(builder); AddAuthentication(builder); AddDataProtection(builder); // Register the list of services to be resolved later on services.AddSingleton(services); } return builder; } /// <summary> /// Adds OrchardCore services to the host service collection and let the app change /// the default behavior and set of features through a configure action. /// </summary> public static IServiceCollection AddOrchardCore(this IServiceCollection services, Action<OrchardCoreBuilder> configure) { var builder = services.AddOrchardCore(); configure?.Invoke(builder); return services; } private static void AddDefaultServices(OrchardCoreBuilder builder) { var services = builder.ApplicationServices; services.AddLogging(); services.AddOptions(); // These services might be moved at a higher level if no components from OrchardCore needs them. services.AddLocalization(); // For performance, prevents the 'ResourceManagerStringLocalizer' from being used. // Also support pluralization. services.AddSingleton<IStringLocalizerFactory, NullStringLocalizerFactory>(); services.AddSingleton<IHtmlLocalizerFactory, NullHtmlLocalizerFactory>(); services.AddWebEncoders(); services.AddHttpContextAccessor(); services.AddSingleton<IClock, Clock>(); services.AddScoped<ILocalClock, LocalClock>(); services.AddScoped<ILocalizationService, DefaultLocalizationService>(); services.AddScoped<ICalendarManager, DefaultCalendarManager>(); services.AddScoped<ICalendarSelector, DefaultCalendarSelector>(); services.AddSingleton<IPoweredByMiddlewareOptions, PoweredByMiddlewareOptions>(); services.AddTransient<IConfigureOptions<DocumentJsonSerializerOptions>, DocumentJsonSerializerOptionsConfiguration>(); services.AddTransient<IConfigureOptions<MvcOptions>, MvcOptionsConfiguration>(); services.AddScoped<IOrchardHelper, DefaultOrchardHelper>(); services.AddSingleton<IClientIPAddressAccessor, DefaultClientIPAddressAccessor>(); services.AddSingleton<ISlugService, SlugService>(); builder.ConfigureServices((services, serviceProvider) => { services.AddSingleton<LocalLock>(); services.AddSingleton<ILocalLock>(sp => sp.GetRequiredService<LocalLock>()); services.AddSingleton<IDistributedLock>(sp => sp.GetRequiredService<LocalLock>()); var configuration = serviceProvider.GetService<IShellConfiguration>(); services.Configure<CultureOptions>(configuration.GetSection("OrchardCore_Localization_CultureOptions")); }); } private static void AddShellServices(OrchardCoreBuilder builder) { var services = builder.ApplicationServices; // Use a single tenant and all features by default services.AddHostingShellServices(); services.AddAllFeaturesDescriptor(); // Registers the application primary feature. services.AddTransient(sp => new ShellFeature ( sp.GetRequiredService<IHostEnvironment>().ApplicationName, alwaysEnabled: true) ); // Registers the application default feature. services.AddTransient(sp => new ShellFeature ( Application.DefaultFeatureId, alwaysEnabled: true) ); builder.ConfigureServices(shellServices => { shellServices.AddScoped<IShellReleaseManager, DefaultShellReleaseManager>(); shellServices.AddTransient<IConfigureOptions<ShellContextOptions>, ShellContextOptionsSetup>(); shellServices.AddNullFeatureProfilesService(); shellServices.AddFeatureValidation(); shellServices.ConfigureFeatureProfilesRuleOptions(); }); } private static void AddExtensionServices(OrchardCoreBuilder builder) { builder.ApplicationServices.AddSingleton<IModuleNamesProvider, AssemblyAttributeModuleNamesProvider>(); builder.ApplicationServices.AddSingleton<IApplicationContext, ModularApplicationContext>(); builder.ApplicationServices.AddExtensionManagerHost(); builder.ConfigureServices(services => { services.AddExtensionManager(); services.AddScoped<IShellFeaturesManager, ShellFeaturesManager>(); services.AddScoped<IShellDescriptorFeaturesManager, ShellDescriptorFeaturesManager>(); }); } /// <summary> /// Adds tenant level configuration to serve static files from modules. /// </summary> private static void AddStaticFiles(OrchardCoreBuilder builder) { builder.ConfigureServices(services => { services.AddSingleton<IModuleStaticFileProvider>(serviceProvider => { var env = serviceProvider.GetRequiredService<IHostEnvironment>(); var appContext = serviceProvider.GetRequiredService<IApplicationContext>(); IModuleStaticFileProvider fileProvider; if (env.IsDevelopment()) { var fileProviders = new List<IStaticFileProvider> { new ModuleProjectStaticFileProvider(appContext), new ModuleEmbeddedStaticFileProvider(appContext), }; fileProvider = new ModuleCompositeStaticFileProvider(fileProviders); } else { fileProvider = new ModuleEmbeddedStaticFileProvider(appContext); } return fileProvider; }); services.AddSingleton<IStaticFileProvider>(serviceProvider => { return serviceProvider.GetRequiredService<IModuleStaticFileProvider>(); }); }); builder.Configure((app, routes, serviceProvider) => { var fileProvider = serviceProvider.GetRequiredService<IModuleStaticFileProvider>(); var shellConfiguration = serviceProvider.GetRequiredService<IShellConfiguration>(); // Cache static files for a year as they are coming from embedded resources and should not vary. var cacheControl = shellConfiguration.GetValue("StaticFileOptions:CacheControl", $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-maxage={TimeSpan.FromDays(365.25).TotalSeconds}"); // Use the current options values but without mutating the resolved instance. var options = serviceProvider.GetRequiredService<IOptions<StaticFileOptions>>().Value; options = new StaticFileOptions { RequestPath = string.Empty, FileProvider = fileProvider, RedirectToAppendTrailingSlash = options.RedirectToAppendTrailingSlash, ContentTypeProvider = options.ContentTypeProvider, DefaultContentType = options.DefaultContentType, ServeUnknownFileTypes = options.ServeUnknownFileTypes, HttpsCompression = options.HttpsCompression, OnPrepareResponse = ctx => { ctx.Context.Response.Headers[HeaderNames.CacheControl] = cacheControl; }, }; app.UseStaticFiles(options); }); } /// <summary> /// Adds isolated tenant level metrics services. /// </summary> private static void AddMetrics(OrchardCoreBuilder builder) { // 'AddMetrics()' is called by the host. builder.ConfigureServices(collection => { // The 'DefaultMeterFactory' caches 'Meters' in a non thread safe dictionary. // So, we need to register an isolated 'IMeterFactory' singleton per tenant. var descriptorsToRemove = collection .Where(sd => sd is ClonedSingletonDescriptor && _metricsTypesToIsolate.Contains(sd.GetImplementationType())) .ToArray(); // Isolate each tenant from the host. foreach (var descriptor in descriptorsToRemove) { collection.Remove(descriptor); } collection.AddMetrics(); }, order: OrchardCoreConstants.ConfigureOrder.InfrastructureService); } /// <summary> /// Adds isolated tenant level routing services. /// </summary> private static void AddRouting(OrchardCoreBuilder builder) { // 'AddRouting()' is called by the host. builder.ConfigureServices(collection => { // The routing system is not tenant aware and uses a global list of endpoint data sources which is // setup by the default configuration of 'RouteOptions' and mutated on each call of 'UseEndPoints()'. // So, we need isolated routing singletons (and a default configuration) per tenant. var descriptorsToRemove = collection .Where(sd => (sd is ClonedSingletonDescriptor || sd.ServiceType == typeof(IConfigureOptions<RouteOptions>)) && _routingTypesToIsolate.Contains(sd.GetImplementationType())) .ToArray(); // Isolate each tenant from the host. foreach (var descriptor in descriptorsToRemove) { collection.Remove(descriptor); } collection.AddRouting(); }, order: OrchardCoreConstants.ConfigureOrder.InfrastructureService); } /// <summary> /// Isolates tenant http client singletons and configurations from the host. /// </summary> private static void IsolateHttpClient(OrchardCoreBuilder builder) { builder.ConfigureServices(collection => { // Each tenant needs isolated http client singletons and configurations, so that // typed clients/handlers are activated/resolved from the right tenant container. // Retrieve current options configurations. var configurationDescriptorsToRemove = collection .Where(sd => sd.ServiceType.IsGenericType && sd.ServiceType.GenericTypeArguments.Contains(typeof(HttpClientFactoryOptions))) .ToArray(); // Retrieve all descriptors to remove. var descriptorsToRemove = collection .Where(sd => sd is ClonedSingletonDescriptor && _httpClientTypesToIsolate.Contains(sd.GetImplementationType())) .Concat(configurationDescriptorsToRemove) .ToArray(); // Isolate each tenant from the host. foreach (var descriptor in descriptorsToRemove) { collection.Remove(descriptor); } // Make the http client factory 'IDisposable'. collection.AddSingleton<TenantHttpClientFactory>(); collection.AddSingleton<IHttpClientFactory>(sp => sp.GetRequiredService<TenantHttpClientFactory>()); collection.AddSingleton<IHttpMessageHandlerFactory>(sp => sp.GetRequiredService<TenantHttpClientFactory>()); }, order: OrchardCoreConstants.ConfigureOrder.InfrastructureService); } /// <summary> /// Configures ApiExplorer at the tenant level using <see cref="Endpoint.Metadata"/>. /// </summary> private static void AddEndpointsApiExplorer(OrchardCoreBuilder builder) { // 'AddEndpointsApiExplorer()' is called by the host. builder.ConfigureServices(collection => { // Remove the related host singletons as they are not tenant aware. var descriptorsToRemove = collection .Where(sd => sd is ClonedSingletonDescriptor && (sd.ServiceType == typeof(IActionDescriptorCollectionProvider) || sd.ServiceType == typeof(IApiDescriptionGroupCollectionProvider))) .ToArray(); // Isolate each tenant from the host. foreach (var descriptor in descriptorsToRemove) { collection.Remove(descriptor); } // Configure ApiExplorer at the tenant level. collection.AddEndpointsApiExplorer(); }, order: OrchardCoreConstants.ConfigureOrder.InfrastructureService); } /// <summary> /// Adds host and tenant level antiforgery services. /// </summary> private static void AddAntiForgery(OrchardCoreBuilder builder) { builder.ApplicationServices.AddAntiforgery(); builder.ConfigureServices((services, serviceProvider) => { var settings = serviceProvider.GetRequiredService<ShellSettings>(); var cookieName = "__orchantiforgery_" + settings.VersionId; // Re-register the antiforgery services to be tenant-aware. var collection = new ServiceCollection() .AddAntiforgery(options => { options.Cookie.Name = cookieName; // Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value // set by the pipeline and coming from the request 'PathBase' which already ends with the // tenant prefix but may also start by a path related e.g to a virtual folder. }); services.Add(collection); }); } /// <summary> /// Adds backwards compatibility to the handling of SameSite cookies. /// </summary> private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder builder) { builder.ConfigureServices(services => { services.Configure<CookiePolicyOptions>(options => { options.MinimumSameSitePolicy = SameSiteMode.Unspecified; options.OnAppendCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); options.OnDeleteCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); }); }) .Configure(app => { app.UseCookiePolicy(); }); } private static void CheckSameSiteBackwardsCompatibility(HttpContext httpContext, CookieOptions options) { var userAgent = httpContext.Request.Headers.UserAgent.ToString(); if (options.SameSite == SameSiteMode.None) { if (string.IsNullOrEmpty(userAgent)) { return; } // Cover all iOS based browsers here. This includes: // - Safari on iOS 12 for iPhone, iPod Touch, iPad. // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad. // - Chrome on iOS 12 for iPhone, iPod Touch, iPad. // All of which are broken by SameSite=None, because they use the iOS networking stack. if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12")) { options.SameSite = SameSiteMode.Unspecified; return; } // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes: // - Safari on Mac OS X. // This does not include: // - Chrome on Mac OS X. // Because they do not use the Mac OS networking stack. if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") && userAgent.Contains("Version/") && userAgent.Contains("Safari")) { options.SameSite = SameSiteMode.Unspecified; return; } // Cover Chrome 50-69, because some versions are broken by SameSite=None, // and none in this range require it. // Note: this covers some pre-Chromium Edge versions, // but pre-Chromium Edge does not require SameSite=None. if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6")) { options.SameSite = SameSiteMode.Unspecified; } } } /// <summary> /// Adds host and tenant level authentication services and configuration. /// </summary> private static void AddAuthentication(OrchardCoreBuilder builder) { builder.ApplicationServices.AddAuthentication(); builder.ConfigureServices(services => { services.AddAuthentication(); // IAuthenticationSchemeProvider is already registered at the host level. // We need to register it again so it is taken into account at the tenant level // because it holds a reference to an underlying dictionary, responsible of storing // the registered schemes which need to be distinct for each tenant. services.AddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>(); }) .Configure(app => { app.UseAuthentication(); }, order: OrchardCoreConstants.ConfigureOrder.Authentication); } /// <summary> /// Adds tenant level data protection services. /// </summary> private static void AddDataProtection(OrchardCoreBuilder builder) { builder.ConfigureServices((services, serviceProvider) => { var settings = serviceProvider.GetRequiredService<ShellSettings>(); var options = serviceProvider.GetRequiredService<IOptions<ShellOptions>>(); // The 'FileSystemXmlRepository' will create the directory, but only if it is not overridden. var directory = new DirectoryInfo(Path.Combine( options.Value.ShellsApplicationDataPath, options.Value.ShellsContainerName, settings.Name, "DataProtection-Keys")); // Re-register the data protection services to be tenant-aware so that modules that internally // rely on IDataProtector/IDataProtectionProvider automatically get an isolated instance that // manages its own key ring and doesn't allow decrypting payloads encrypted by another tenant. // By default, the key ring is stored in the tenant directory of the configured App_Data path. var collection = new ServiceCollection() .AddDataProtection() .PersistKeysToFileSystem(directory) .SetApplicationName(settings.Name) .AddKeyManagementOptions(o => o.XmlEncryptor ??= new NullXmlEncryptor()) .Services; // Remove any previously registered options setups. services.RemoveAll<IConfigureOptions<KeyManagementOptions>>(); services.RemoveAll<IConfigureOptions<DataProtectionOptions>>(); services.Add(collection); }, order: OrchardCoreConstants.ConfigureOrder.DataProtection); } }
ServiceCollectionExtensions
csharp
AutoMapper__AutoMapper
src/UnitTests/Bug/CollectionsNullability.cs
{ "start": 38, "end": 127 }
public class ____ : AutoMapperSpecBase { Holder _destination;
CollectionsNullability
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Utilities/Extensions/OperationResolverHelper.cs
{ "start": 71, "end": 2223 }
public static class ____ { public static OperationDefinitionNode GetOperation( this DocumentNode document, string? operationName) { if (string.IsNullOrEmpty(operationName)) { OperationDefinitionNode? operation = null; var definitions = document.Definitions; var length = definitions.Count; for (var i = 0; i < length; i++) { if (definitions[i] is not OperationDefinitionNode op) { continue; } if (operation is null) { operation = op; } else { // TODO : EXCEPTION throw new Exception("OperationResolverHelper_MultipleOperation"); } } if (operation is null) { // TODO : EXCEPTION throw new Exception("OperationResolverHelper_NoOperationFound"); } return operation; } else { for (var i = 0; i < document.Definitions.Count; i++) { if (document.Definitions[i] is OperationDefinitionNode { Name: { } } op && op.Name!.Value.Equals(operationName, StringComparison.Ordinal)) { return op; } } // TODO : EXCEPTION throw new Exception("OperationResolverHelper_InvalidOperationName"); } } public static Dictionary<string, FragmentDefinitionNode> GetFragments( this DocumentNode document) { var definitions = document.Definitions; var length = definitions.Count; var map = new Dictionary<string, FragmentDefinitionNode>(StringComparer.Ordinal); for (var i = 0; i < length; i++) { if (definitions[i] is FragmentDefinitionNode fragmentDef) { map.Add(fragmentDef.Name.Value, fragmentDef); } } return map; } }
FusionDocumentNodeExtensions
csharp
serilog__serilog
test/Serilog.Tests/Support/LogEventPropertyValueComparer.cs
{ "start": 34, "end": 1416 }
class ____ : IEqualityComparer<LogEventPropertyValue> { readonly IEqualityComparer<object> _objectEqualityComparer; public LogEventPropertyValueComparer(IEqualityComparer<object>? objectEqualityComparer = null) { _objectEqualityComparer = objectEqualityComparer ?? EqualityComparer<object>.Default; } public bool Equals(LogEventPropertyValue? x, LogEventPropertyValue? y) { if (x is ScalarValue scalarX && y is ScalarValue scalarY) { if (scalarX.Value is null && scalarY.Value is null) { return true; } if (scalarX.Value is null || scalarY.Value is null) { return false; } return _objectEqualityComparer.Equals(scalarX.Value, scalarY.Value); } if (x is SequenceValue sequenceX && y is SequenceValue sequenceY) { return sequenceX.Elements .SequenceEqual(sequenceY.Elements, this); } if (x is StructureValue || y is StructureValue) { throw new NotImplementedException(); } if (x is DictionaryValue || y is DictionaryValue) { throw new NotImplementedException(); } return false; } public int GetHashCode(LogEventPropertyValue obj) => 0; }
LogEventPropertyValueComparer
csharp
xunit__xunit
src/xunit.v1.tests/xunit/Sdk/Results/AssemblyResultTests.cs
{ "start": 179, "end": 3944 }
public class ____ : IDisposable { static readonly string assembly = "StubAssembly"; static readonly string fullPathName = @"C:\Foo\Bar"; protected AssemblyBuilder builder; static readonly string filename = "StubAssembly.dll"; protected ModuleBuilder moduleBuilder; static AssemblyResultTests() { // Let the system compute it for non-Windows systems fullPathName = Path.GetFullPath(fullPathName); } public AssemblyResultTests() { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = assembly; AppDomain appDomain = Thread.GetDomain(); builder = appDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.RunAndSave); } public void Dispose() { if (File.Exists(filename)) File.Delete(filename); } [Fact] public void AssemblyResultCodeBase() { AssemblyResult assemblyResult = new AssemblyResult(filename); Assert.Equal(Path.GetDirectoryName(Path.GetFullPath(filename)), assemblyResult.Directory); } [Fact] public void AssemblyResultName() { AssemblyResult assemblyResult = new AssemblyResult(filename); Assert.Equal(Path.GetFullPath(filename), assemblyResult.Filename); } [Fact] public void AssemblyResultConfigFilename() { AssemblyResult assemblyResult = new AssemblyResult(filename, fullPathName); Assert.Equal(fullPathName, assemblyResult.ConfigFilename); } [Fact] public void ToXml() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo/>"); XmlNode parentNode = doc.ChildNodes[0]; AssemblyResult assemblyResult = new AssemblyResult(filename, fullPathName); XmlNode resultNode = assemblyResult.ToXml(parentNode); Assert.Equal("assembly", resultNode.Name); Assert.Equal(Path.GetFullPath(filename), resultNode.Attributes["name"].Value); Assert.Equal(fullPathName, resultNode.Attributes["configFile"].Value); Assert.NotNull(resultNode.Attributes["run-date"]); Assert.NotNull(resultNode.Attributes["run-time"]); Assert.Equal("0.000", resultNode.Attributes["time"].Value); Assert.Equal("0", resultNode.Attributes["total"].Value); Assert.Equal("0", resultNode.Attributes["passed"].Value); Assert.Equal("0", resultNode.Attributes["failed"].Value); Assert.Equal("0", resultNode.Attributes["skipped"].Value); Assert.Contains("xUnit.net", resultNode.Attributes["test-framework"].Value); string expectedEnvironment = string.Format("{0}-bit .NET {1}", IntPtr.Size * 8, Environment.Version); Assert.Equal(expectedEnvironment, resultNode.Attributes["environment"].Value); } [Fact] public void ToXml_WithChildren() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo/>"); XmlNode parentNode = doc.ChildNodes[0]; PassedResult passedResult = new PassedResult("foo", "bar", null, null); passedResult.ExecutionTime = 1.1; FailedResult failedResult = new FailedResult("foo", "bar", null, null, "extype", "message", "stack"); failedResult.ExecutionTime = 2.2; SkipResult skipResult = new SkipResult("foo", "bar", null, null, "reason"); ClassResult classResult = new ClassResult(typeof(object)); classResult.Add(passedResult); classResult.Add(failedResult); classResult.Add(skipResult); AssemblyResult assemblyResult = new AssemblyResult(filename); assemblyResult.Add(classResult); XmlNode resultNode = assemblyResult.ToXml(parentNode); Assert.Equal("3.300", resultNode.Attributes["time"].Value); Assert.Equal("3", resultNode.Attributes["total"].Value); Assert.Equal("1", resultNode.Attributes["passed"].Value); Assert.Equal("1", resultNode.Attributes["failed"].Value); Assert.Equal("1", resultNode.Attributes["skipped"].Value); Assert.Single(resultNode.SelectNodes("class")); } } }
AssemblyResultTests
csharp
microsoft__PowerToys
src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Registry/Helpers/RegistryHelper.cs
{ "start": 609, "end": 8675 }
internal static class ____ { /// <summary> /// A list that contain all registry base keys in a long/full version and in a short version (e.g HKLM = HKEY_LOCAL_MACHINE) /// </summary> private static readonly IReadOnlyDictionary<string, RegistryKey> _baseKeys = new Dictionary<string, RegistryKey>(12) { { KeyName.ClassRootShort, Win32.Registry.ClassesRoot }, { Win32.Registry.ClassesRoot.Name, Win32.Registry.ClassesRoot }, { KeyName.CurrentConfigShort, Win32.Registry.CurrentConfig }, { Win32.Registry.CurrentConfig.Name, Win32.Registry.CurrentConfig }, { KeyName.CurrentUserShort, Win32.Registry.CurrentUser }, { Win32.Registry.CurrentUser.Name, Win32.Registry.CurrentUser }, { KeyName.LocalMachineShort, Win32.Registry.LocalMachine }, { Win32.Registry.LocalMachine.Name, Win32.Registry.LocalMachine }, { KeyName.PerformanceDataShort, Win32.Registry.PerformanceData }, { Win32.Registry.PerformanceData.Name, Win32.Registry.PerformanceData }, { KeyName.UsersShort, Win32.Registry.Users }, { Win32.Registry.Users.Name, Win32.Registry.Users }, }; /// <summary> /// Try to find registry base keys based on the given query /// </summary> /// <param name="query">The query to search</param> /// <returns>A combination of a list of base <see cref="RegistryKey"/> and the sub keys</returns> #pragma warning disable CS8632 internal static (IEnumerable<RegistryKey>? BaseKey, string SubKey) GetRegistryBaseKey(in string query) { if (string.IsNullOrWhiteSpace(query)) { return (null, string.Empty); } var baseKey = query.Split('\\').FirstOrDefault() ?? string.Empty; var subKey = string.Empty; if (!string.IsNullOrEmpty(baseKey)) { subKey = query.Replace(baseKey, string.Empty, StringComparison.InvariantCultureIgnoreCase).TrimStart('\\'); } var baseKeyResult = _baseKeys .Where(found => found.Key.StartsWith(baseKey, StringComparison.InvariantCultureIgnoreCase)) .Select(found => found.Value) .Distinct(); return (baseKeyResult, subKey); } /// <summary> /// Return a list of all registry base key /// </summary> /// <returns>A list with all registry base keys</returns> internal static ICollection<RegistryEntry> GetAllBaseKeys() { return new Collection<RegistryEntry> { new(Win32.Registry.ClassesRoot), new(Win32.Registry.CurrentConfig), new(Win32.Registry.CurrentUser), new(Win32.Registry.LocalMachine), new(Win32.Registry.PerformanceData), new(Win32.Registry.Users), }; } /// <summary> /// Search for the given sub-key path in the given registry base key /// </summary> /// <param name="baseKey">The base <see cref="RegistryKey"/></param> /// <param name="subKeyPath">The path of the registry sub-key</param> /// <returns>A list with all found registry keys</returns> internal static ICollection<RegistryEntry> SearchForSubKey(in RegistryKey baseKey, in string subKeyPath) { if (string.IsNullOrEmpty(subKeyPath)) { return FindSubKey(baseKey, string.Empty); } var subKeysNames = subKeyPath.Split('\\'); var index = 0; RegistryKey? subKey = baseKey; #pragma warning restore CS8632 ICollection<RegistryEntry> result; do { result = FindSubKey(subKey, subKeysNames.ElementAtOrDefault(index) ?? string.Empty); if (result.Count == 0) { // If a subKey can't be found, show no results. break; } if (result.Count == 1 && index < subKeysNames.Length) { subKey = result.First().Key; } if (result.Count > 1 || subKey is null) { break; } index++; } while (index < subKeysNames.Length); return result; } /// <summary> /// Return a human readable summary of a given <see cref="RegistryKey"/> /// </summary> /// <param name="key">The <see cref="RegistryKey"/> for the summary</param> /// <returns>A human readable summary</returns> internal static string GetSummary(in RegistryKey key) { return $"{Resources.SubKeys} {key.SubKeyCount} - {Resources.Values} {key.ValueCount}"; } /// <summary> /// Open a given registry key in the registry editor /// </summary> /// <param name="fullKey">The registry key to open</param> internal static void OpenRegistryKey(in string fullKey) { // Set the registry key Win32.Registry.SetValue(@"HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", fullKey); // Open regedit.exe with multi-instance option ProcessStartInfo startInfo = new ProcessStartInfo { FileName = "regedit.exe", Arguments = "-m", UseShellExecute = true, Verb = "runas", // Runs as Administrator }; Process.Start(startInfo); } /// <summary> /// Try to find the given registry sub-key in the given registry parent-key /// </summary> /// <param name="parentKey">The parent-key, also the root to start the search</param> /// <param name="searchSubKey">The sub-key to find</param> /// <returns>A list with all found registry sub-keys</returns> private static Collection<RegistryEntry> FindSubKey(in RegistryKey parentKey, in string searchSubKey) { var list = new Collection<RegistryEntry>(); try { foreach (var subKey in parentKey.GetSubKeyNames().OrderBy(found => found)) { if (!subKey.StartsWith(searchSubKey, StringComparison.InvariantCultureIgnoreCase)) { continue; } if (string.Equals(subKey, searchSubKey, StringComparison.OrdinalIgnoreCase)) { var key = parentKey.OpenSubKey(subKey, RegistryKeyPermissionCheck.ReadSubTree); if (key is not null) { list.Add(new RegistryEntry(key)); } return list; } try { var key = parentKey.OpenSubKey(subKey, RegistryKeyPermissionCheck.ReadSubTree); if (key is not null) { list.Add(new RegistryEntry(key)); } } catch (Exception exception) { list.Add(new RegistryEntry($"{parentKey.Name}\\{subKey}", exception)); } } } catch (Exception ex) { list.Add(new RegistryEntry(parentKey.Name, ex)); } return list; } /// <summary> /// Return a list with a registry sub-keys of the given registry parent-key /// </summary> /// <param name="parentKey">The registry parent-key</param> /// <param name="maxCount">(optional) The maximum count of the results</param> /// <returns>A list with all found registry sub-keys</returns> private static Collection<RegistryEntry> GetAllSubKeys(in RegistryKey parentKey, in int maxCount = 50) { var list = new Collection<RegistryEntry>(); try { foreach (var subKey in parentKey.GetSubKeyNames()) { if (list.Count >= maxCount) { break; } list.Add(new RegistryEntry(parentKey)); } } catch (Exception exception) { list.Add(new RegistryEntry(parentKey.Name, exception)); } return list; } }
RegistryHelper
csharp
unoplatform__uno
src/SourceGenerators/System.Xaml.Tests/Test/System.Xaml.Schema/XamlMemberInvokerTest.cs
{ "start": 7400, "end": 8244 }
class ____ { public TestClass () { ArrayMember = new ArrayExtension (typeof (int)); ArrayMember.AddChild (5); ArrayMember.AddChild (3); ArrayMember.AddChild (-1); } public ArrayExtension ArrayMember { get; set; } } [Test] public void UnknownInvokerGetValue () { Assert.Throws(typeof(NotSupportedException), () => { XamlMemberInvoker.UnknownInvoker.GetValue(new object()); }); } [Test] public void UnknownInvokerSetValue () { Assert.Throws(typeof(NotSupportedException), () => { XamlMemberInvoker.UnknownInvoker.SetValue(new object(), new object()); }); } [Test] public void UnknownInvoker () { Assert.IsNull (XamlMemberInvoker.UnknownInvoker.UnderlyingGetter, "#1"); Assert.IsNull (XamlMemberInvoker.UnknownInvoker.UnderlyingSetter, "#2"); } } }
TestClass
csharp
Tyrrrz__CliWrap
CliWrap/EventStream/PushEventStreamCommandExtensions.cs
{ "start": 357, "end": 4994 }
partial class ____ { /// <inheritdoc cref="EventStreamCommandExtensions" /> extension(Command command) { /// <summary> /// Executes the command as a push-based event stream. /// </summary> /// <remarks> /// Use pattern matching to handle specific instances of <see cref="CommandEvent" />. /// </remarks> // TODO: (breaking change) use optional parameters and remove the other overload public IObservable<CommandEvent> Observe( Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken ) { return Observable.CreateSynchronized<CommandEvent>(observer => { var stdOutPipe = PipeTarget.Merge( command.StandardOutputPipe, PipeTarget.ToDelegate( line => observer.OnNext(new StandardOutputCommandEvent(line)), standardOutputEncoding ) ); var stdErrPipe = PipeTarget.Merge( command.StandardErrorPipe, PipeTarget.ToDelegate( line => observer.OnNext(new StandardErrorCommandEvent(line)), standardErrorEncoding ) ); var commandWithPipes = command .WithStandardOutputPipe(stdOutPipe) .WithStandardErrorPipe(stdErrPipe); var commandTask = commandWithPipes.ExecuteAsync( forcefulCancellationToken, gracefulCancellationToken ); observer.OnNext(new StartedCommandEvent(commandTask.ProcessId)); // Don't pass cancellation token to the continuation because we need it to // trigger regardless of how the task completed. _ = commandTask.Task.ContinueWith( t => { // Canceled tasks don't have exceptions if (t.IsCanceled) { observer.OnError(new TaskCanceledException(t)); } else if (t.Exception is not null) { observer.OnError(t.Exception.TryGetSingle() ?? t.Exception); } else { observer.OnNext(new ExitedCommandEvent(t.Result.ExitCode)); observer.OnCompleted(); } }, TaskContinuationOptions.None ); return Disposable.Null; }); } /// <summary> /// Executes the command as a push-based event stream. /// </summary> /// <remarks> /// Use pattern matching to handle specific instances of <see cref="CommandEvent" />. /// </remarks> public IObservable<CommandEvent> Observe( Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken cancellationToken = default ) { return command.Observe( standardOutputEncoding, standardErrorEncoding, cancellationToken, CancellationToken.None ); } /// <summary> /// Executes the command as a push-based event stream. /// </summary> /// <remarks> /// Use pattern matching to handle specific instances of <see cref="CommandEvent" />. /// </remarks> public IObservable<CommandEvent> Observe( Encoding encoding, CancellationToken cancellationToken = default ) { return command.Observe(encoding, encoding, cancellationToken); } /// <summary> /// Executes the command as a push-based event stream. /// Uses <see cref="Encoding.Default" /> for decoding. /// </summary> /// <remarks> /// Use pattern matching to handle specific instances of <see cref="CommandEvent" />. /// </remarks> public IObservable<CommandEvent> Observe(CancellationToken cancellationToken = default) { return command.Observe(Encoding.Default, cancellationToken); } } }
EventStreamCommandExtensions
csharp
SixLabors__Fonts
tests/SixLabors.Fonts.Tests/FakeFont.cs
{ "start": 176, "end": 1530 }
public class ____ { [Fact] public void TestFontMetricProperties() { Font fakeFont = CreateFont("A"); FontMetrics metrics = fakeFont.FontMetrics; Assert.Equal(30, metrics.UnitsPerEm); Assert.Equal(35, metrics.HorizontalMetrics.Ascender); Assert.Equal(8, metrics.HorizontalMetrics.Descender); Assert.Equal(12, metrics.HorizontalMetrics.LineGap); Assert.Equal(35 - 8 + 12, metrics.HorizontalMetrics.LineHeight); // Vertical metrics are all ones. Descender is always negative due to the grid orientation. Assert.Equal(1, metrics.VerticalMetrics.Ascender); Assert.Equal(-1, metrics.VerticalMetrics.Descender); Assert.Equal(1, metrics.VerticalMetrics.LineGap); Assert.Equal(1 - (-1) + 1, metrics.VerticalMetrics.LineHeight); } public static Font CreateFont(string text, string name = "name") => CreateFontWithInstance(text, name, out _); internal static Font CreateFontWithInstance(string text, string name, out FakeFontInstance instance) { var fc = (IFontMetricsCollection)new FontCollection(); instance = FakeFontInstance.CreateFontWithVaryingVerticalFontMetrics(text, name); Font d = fc.AddMetrics(instance, CultureInfo.InvariantCulture).CreateFont(12); return new Font(d, 1F); } }
FakeFont
csharp
ardalis__GuardClauses
test/GuardClauses.UnitTests/GuardAgainstOutOfRangeForEnumerableLong.cs
{ "start": 5072, "end": 5553 }
public class ____ : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { yield return new object[] { new List<long> { 10, 12, 1500 }, 10, 1200 }; yield return new object[] { new List<long> { 1000, 200, 120, 180000 }, 100, 150000 }; yield return new object[] { new List<long> { 15, 120, 158 }, 10, 110 }; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
IncorrectClassData
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/TypeConversion/IDictionaryConverterTests.cs
{ "start": 7309, "end": 7511 }
private sealed class ____ : ClassMap<Test> { public TestIndexMap() { Map(m => m.Before).Index(0); Map(m => m.Dictionary).Index(1, 3); Map(m => m.After).Index(4); } }
TestIndexMap
csharp
dotnet__maui
src/Compatibility/Core/src/WPF/Microsoft.Windows.Shell/Standard/NativeMethods.cs
{ "start": 17873, "end": 22050 }
internal enum ____ { NULL = 0x0000, CREATE = 0x0001, DESTROY = 0x0002, MOVE = 0x0003, SIZE = 0x0005, ACTIVATE = 0x0006, SETFOCUS = 0x0007, KILLFOCUS = 0x0008, ENABLE = 0x000A, SETREDRAW = 0x000B, SETTEXT = 0x000C, GETTEXT = 0x000D, GETTEXTLENGTH = 0x000E, PAINT = 0x000F, CLOSE = 0x0010, QUERYENDSESSION = 0x0011, QUIT = 0x0012, QUERYOPEN = 0x0013, ERASEBKGND = 0x0014, SYSCOLORCHANGE = 0x0015, SHOWWINDOW = 0x0018, CTLCOLOR = 0x0019, WININICHANGE = 0x001A, SETTINGCHANGE = 0x001A, ACTIVATEAPP = 0x001C, SETCURSOR = 0x0020, MOUSEACTIVATE = 0x0021, CHILDACTIVATE = 0x0022, QUEUESYNC = 0x0023, GETMINMAXINFO = 0x0024, WINDOWPOSCHANGING = 0x0046, WINDOWPOSCHANGED = 0x0047, CONTEXTMENU = 0x007B, STYLECHANGING = 0x007C, STYLECHANGED = 0x007D, DISPLAYCHANGE = 0x007E, GETICON = 0x007F, SETICON = 0x0080, NCCREATE = 0x0081, NCDESTROY = 0x0082, NCCALCSIZE = 0x0083, NCHITTEST = 0x0084, NCPAINT = 0x0085, NCACTIVATE = 0x0086, GETDLGCODE = 0x0087, SYNCPAINT = 0x0088, NCMOUSEMOVE = 0x00A0, NCLBUTTONDOWN = 0x00A1, NCLBUTTONUP = 0x00A2, NCLBUTTONDBLCLK = 0x00A3, NCRBUTTONDOWN = 0x00A4, NCRBUTTONUP = 0x00A5, NCRBUTTONDBLCLK = 0x00A6, NCMBUTTONDOWN = 0x00A7, NCMBUTTONUP = 0x00A8, NCMBUTTONDBLCLK = 0x00A9, SYSKEYDOWN = 0x0104, SYSKEYUP = 0x0105, SYSCHAR = 0x0106, SYSDEADCHAR = 0x0107, COMMAND = 0x0111, SYSCOMMAND = 0x0112, // These two messages aren't defined in winuser.h, but they are sent to windows // with captions. They appear to paint the window caption and frame. // Unfortunately if you override the standard non-client rendering as we do // with CustomFrameWindow, sometimes Windows (not deterministically // reproducibly but definitely frequently) will send these messages to the // window and paint the standard caption/title over the top of the custom one. // So we need to handle these messages in CustomFrameWindow to prevent this // from happening. NCUAHDRAWCAPTION = 0xAE, NCUAHDRAWFRAME = 0xAF, MOUSEMOVE = 0x0200, LBUTTONDOWN = 0x0201, LBUTTONUP = 0x0202, LBUTTONDBLCLK = 0x0203, RBUTTONDOWN = 0x0204, RBUTTONUP = 0x0205, RBUTTONDBLCLK = 0x0206, MBUTTONDOWN = 0x0207, MBUTTONUP = 0x0208, MBUTTONDBLCLK = 0x0209, MOUSEWHEEL = 0x020A, XBUTTONDOWN = 0x020B, XBUTTONUP = 0x020C, XBUTTONDBLCLK = 0x020D, MOUSEHWHEEL = 0x020E, PARENTNOTIFY = 0x0210, CAPTURECHANGED = 0x0215, POWERBROADCAST = 0x0218, DEVICECHANGE = 0x0219, ENTERSIZEMOVE = 0x0231, EXITSIZEMOVE = 0x0232, IME_SETCONTEXT = 0x0281, IME_NOTIFY = 0x0282, IME_CONTROL = 0x0283, IME_COMPOSITIONFULL = 0x0284, IME_SELECT = 0x0285, IME_CHAR = 0x0286, IME_REQUEST = 0x0288, IME_KEYDOWN = 0x0290, IME_KEYUP = 0x0291, NCMOUSELEAVE = 0x02A2, TABLET_DEFBASE = 0x02C0, //WM_TABLET_MAXOFFSET = 0x20, TABLET_ADDED = TABLET_DEFBASE + 8, TABLET_DELETED = TABLET_DEFBASE + 9, TABLET_FLICK = TABLET_DEFBASE + 11, TABLET_QUERYSYSTEMGESTURESTATUS = TABLET_DEFBASE + 12, CUT = 0x0300, COPY = 0x0301, PASTE = 0x0302, CLEAR = 0x0303, UNDO = 0x0304, RENDERFORMAT = 0x0305, RENDERALLFORMATS = 0x0306, DESTROYCLIPBOARD = 0x0307, DRAWCLIPBOARD = 0x0308, PAINTCLIPBOARD = 0x0309, VSCROLLCLIPBOARD = 0x030A, SIZECLIPBOARD = 0x030B, ASKCBFORMATNAME = 0x030C, CHANGECBCHAIN = 0x030D, HSCROLLCLIPBOARD = 0x030E, QUERYNEWPALETTE = 0x030F, PALETTEISCHANGING = 0x0310, PALETTECHANGED = 0x0311, HOTKEY = 0x0312, PRINT = 0x0317, PRINTCLIENT = 0x0318, APPCOMMAND = 0x0319, THEMECHANGED = 0x031A, DWMCOMPOSITIONCHANGED = 0x031E, DWMNCRENDERINGCHANGED = 0x031F, DWMCOLORIZATIONCOLORCHANGED = 0x0320, DWMWINDOWMAXIMIZEDCHANGE = 0x0321, GETTITLEBARINFOEX = 0x033F, #region Windows 7 DWMSENDICONICTHUMBNAIL = 0x0323, DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, #endregion USER = 0x0400, // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. // It's relatively safe to reuse. TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 APP = 0x8000, } /// <summary> /// Window style extended values, WS_EX_* /// </summary> [Flags]
WM
csharp
xunit__xunit
src/xunit.v3.core.tests/Framework/XunitTestFrameworkDiscovererTests.cs
{ "start": 9834, "end": 9935 }
public class ____ : BaseClassWithStaticMethodUnderTest { } }
ClassWithInheritedStaticMethodUnderTest
csharp
bitwarden__server
src/Core/Auth/Identity/TokenProviders/DuoUniversalTokenProvider.cs
{ "start": 432, "end": 4021 }
public class ____( IServiceProvider serviceProvider, IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory, IDuoUniversalTokenService duoUniversalTokenService) : IUserTwoFactorTokenProvider<User> { /// <summary> /// We need the IServiceProvider to resolve the <see cref="IUserService"/>. There is a complex dependency dance /// occurring between <see cref="IUserService"/>, which extends the <see cref="UserManager{User}"/>, and the usage /// of the <see cref="UserManager{User}"/> within this class. Trying to resolve the <see cref="IUserService"/> using /// the DI pipeline will not allow the server to start and it will hang and give no helpful indication as to the /// problem. /// </summary> private readonly IServiceProvider _serviceProvider = serviceProvider; private readonly IDataProtectorTokenFactory<DuoUserStateTokenable> _tokenDataFactory = tokenDataFactory; private readonly IDuoUniversalTokenService _duoUniversalTokenService = duoUniversalTokenService; public async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<User> manager, User user) { var userService = _serviceProvider.GetRequiredService<IUserService>(); var duoUniversalTokenProvider = await GetDuoTwoFactorProvider(user, userService); if (duoUniversalTokenProvider == null) { return false; } return duoUniversalTokenProvider.Enabled; } public async Task<string> GenerateAsync(string purpose, UserManager<User> manager, User user) { var duoClient = await GetDuoClientAsync(user); if (duoClient == null) { return null; } return _duoUniversalTokenService.GenerateAuthUrl(duoClient, _tokenDataFactory, user); } public async Task<bool> ValidateAsync(string purpose, string token, UserManager<User> manager, User user) { var duoClient = await GetDuoClientAsync(user); if (duoClient == null) { return false; } return await _duoUniversalTokenService.RequestDuoValidationAsync(duoClient, _tokenDataFactory, user, token); } /// <summary> /// Get the Duo Two Factor Provider for the user if they have premium access to Duo /// </summary> /// <param name="user">Active User</param> /// <returns>null or Duo TwoFactorProvider</returns> private async Task<TwoFactorProvider> GetDuoTwoFactorProvider(User user, IUserService userService) { if (!await userService.CanAccessPremium(user)) { return null; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo); if (!_duoUniversalTokenService.HasProperDuoMetadata(provider)) { return null; } return provider; } /// <summary> /// Uses the User to fetch a valid TwoFactorProvider and use it to create a Duo.Client /// </summary> /// <param name="user">active user</param> /// <returns>null or Duo TwoFactorProvider</returns> private async Task<Duo.Client> GetDuoClientAsync(User user) { var userService = _serviceProvider.GetRequiredService<IUserService>(); var provider = await GetDuoTwoFactorProvider(user, userService); if (provider == null) { return null; } var duoClient = await _duoUniversalTokenService.BuildDuoTwoFactorClientAsync(provider); if (duoClient == null) { return null; } return duoClient; } }
DuoUniversalTokenProvider
csharp
npgsql__efcore.pg
src/EFCore.PG/Storage/Internal/Mapping/NpgsqlIntervalTypeMapping.cs
{ "start": 627, "end": 8372 }
public class ____ : NpgsqlTypeMapping { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static NpgsqlIntervalTypeMapping Default { get; } = new(); /// <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 NpgsqlIntervalTypeMapping() : this( new RelationalTypeMappingParameters( new CoreTypeMappingParameters(typeof(TimeSpan), jsonValueReaderWriter: NpgsqlJsonTimeSpanReaderWriter.Instance), "interval")) { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected NpgsqlIntervalTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters, NpgsqlDbType.Interval) { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new NpgsqlIntervalTypeMapping(parameters); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override string ProcessStoreType(RelationalTypeMappingParameters parameters, string storeType, string _) => parameters.Precision is null ? storeType : $"interval({parameters.Precision})"; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override string GenerateNonNullSqlLiteral(object value) => $"INTERVAL '{FormatTimeSpanAsInterval((TimeSpan)value)}'"; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override string GenerateEmbeddedNonNullSqlLiteral(object value) => $""" "{FormatTimeSpanAsInterval((TimeSpan)value)}" """; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static string FormatTimeSpanAsInterval(TimeSpan ts) => ts.ToString( $@"{(ts < TimeSpan.Zero ? "\\-" : "")}{(ts.Days == 0 ? "" : "d\\ ")}hh\:mm\:ss{(ts.Ticks % 10000000 == 0 ? "" : "\\.FFFFFF")}", CultureInfo.InvariantCulture); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static TimeSpan ParseIntervalAsTimeSpan(ReadOnlySpan<char> s) { // We store the a PG-compatible interval representation in JSON so it can be queried out, but unfortunately this isn't // compatible with TimeSpan, so we have to parse manually. // Note var isNegated = false; if (s[0] == '-') { isNegated = true; s = s[1..]; } int i; for (i = 0; i < s.Length; i++) { if (!char.IsDigit(s[i])) { break; } } if (i == s.Length) { throw new FormatException(); } // Space is the separator between the days and the hours:minutes:seconds components var days = 0; if (s[i] == ' ') { days = int.Parse(s[..i]); s = s[i..]; } var timeSpan = TimeSpan.Parse(s, CultureInfo.InvariantCulture); // We've already extracted the days, so there shouldn't be a days component in the rest (indicates an incompatible/malformed string) if (timeSpan.Days != 0) { throw new FormatException(); } if (days > 0) { timeSpan = new TimeSpan( days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds, timeSpan.Microseconds); } if (isNegated) { timeSpan = -timeSpan; } return timeSpan; } /// <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>
NpgsqlIntervalTypeMapping
csharp
dotnet__aspire
src/Aspire.Dashboard/Configuration/DashboardOptions.cs
{ "start": 963, "end": 1993 }
public sealed class ____ { private Uri? _parsedUrl; private byte[]? _apiKeyBytes; public string? Url { get; set; } public ResourceClientAuthMode? AuthMode { get; set; } public ResourceServiceClientCertificateOptions ClientCertificate { get; set; } = new(); public string? ApiKey { get; set; } public Uri? GetUri() => _parsedUrl; internal byte[] GetApiKeyBytes() => _apiKeyBytes ?? throw new InvalidOperationException($"{nameof(ApiKey)} is not available."); internal bool TryParseOptions([NotNullWhen(false)] out string? errorMessage) { if (!string.IsNullOrEmpty(Url)) { if (!Uri.TryCreate(Url, UriKind.Absolute, out _parsedUrl)) { errorMessage = $"Failed to parse resource service client endpoint URL '{Url}'."; return false; } } _apiKeyBytes = ApiKey != null ? Encoding.UTF8.GetBytes(ApiKey) : null; errorMessage = null; return true; } }
ResourceServiceClientOptions
csharp
AutoMapper__AutoMapper
src/UnitTests/Internationalization.cs
{ "start": 346, "end": 457 }
public class ____ { public string Æøå { get; set; } }
Customer
csharp
duplicati__duplicati
Duplicati/Library/Utility/Uri.cs
{ "start": 1343, "end": 2082 }
class ____ be deleted. // It was introduced to make it simpler to give the backend url on the commandline, // and because the Mono implementation of System.Uri had some issues. // Since Mono is no longer used, the only problem is the commandline, // but it does not make sense to support "invalid" urls as that increases the complexity // of the code and potentially introduces ambiguity for the user. /// <summary> /// Represents a relaxed parsing of a URL. /// The goal is to cover as many types of url's as possible, /// without being ambiguous. /// The major limitations is that an embedded username may not contain a :, /// and the password may not contain a @. /// </summary>
should
csharp
SixLabors__Fonts
src/SixLabors.Fonts/Tables/Cff/CffParser.cs
{ "start": 16361, "end": 24992 }
struct ____[<varies>] Range2 array (see Table 21) // //----------------------------------------------- // Table 21 Range2 Format // Type Name Description // SID first First glyph in range // Card16 nLeft Glyphs left in range (excluding first) //----------------------------------------------- // Format 2 differs from format 1 only in the size of the nLeft field in each range. // This format is most suitable for fonts with a large well - ordered charset — for example, for Asian CIDFonts. for (int i = 1; i < glyphs.Length;) { int sid = reader.ReadUInt16(); // First glyph in range int count = reader.ReadUInt16() + 1; // since it does not include first element. do { ref CffGlyphData data = ref glyphs[i]; data.GlyphName = GetSid(sid, stringIndex); count--; i++; sid++; } while (count > 0); } } private void ReadFDSelect(BigEndianBinaryReader reader, CidFontInfo cidFontInfo) { if (cidFontInfo.FDSelect == 0) { return; } reader.BaseStream.Position = this.offset + cidFontInfo.FDSelect; switch (reader.ReadByte()) { case 0: cidFontInfo.FdSelectFormat = 0; for (int i = 0; i < cidFontInfo.CIDFountCount; i++) { cidFontInfo.FdSelectMap[i] = reader.ReadByte(); } break; case 3: cidFontInfo.FdSelectFormat = 3; ushort nRanges = reader.ReadUInt16(); FDRange3[] ranges = new FDRange3[nRanges + 1]; cidFontInfo.FdSelectFormat = 3; cidFontInfo.FdRanges = ranges; for (int i = 0; i < nRanges; ++i) { ranges[i] = new FDRange3(reader.ReadUInt16(), reader.ReadByte()); } ranges[nRanges] = new FDRange3(reader.ReadUInt16(), 0); // sentinel break; default: throw new NotSupportedException("Only FD Select format 0 and 3 are supported"); } } private FontDict[] ReadFDArray(BigEndianBinaryReader reader, CidFontInfo cidFontInfo) { if (cidFontInfo.FDArray == 0) { return Array.Empty<FontDict>(); } reader.BaseStream.Position = this.offset + cidFontInfo.FDArray; if (!TryReadIndexDataOffsets(reader, out CffIndexOffset[]? offsets)) { return Array.Empty<FontDict>(); } FontDict[] fontDicts = new FontDict[offsets.Length]; for (int i = 0; i < fontDicts.Length; ++i) { // read DICT data List<CffDataDicEntry> dic = this.ReadDICTData(reader, offsets[i].Length); // translate int offset = 0; int size = 0; int name = 0; foreach (CffDataDicEntry entry in dic) { switch (entry.Operator.Name) { default: throw new NotSupportedException(); case "FontName": name = (int)entry.Operands[0].RealNumValue; break; case "Private": // private dic size = (int)entry.Operands[0].RealNumValue; offset = (int)entry.Operands[1].RealNumValue; break; } } fontDicts[i] = new FontDict(name, size, offset); } foreach (FontDict fdict in fontDicts) { reader.BaseStream.Position = this.offset + fdict.PrivateDicOffset; List<CffDataDicEntry> dicData = this.ReadDICTData(reader, fdict.PrivateDicSize); if (dicData.Count > 0) { // Interpret the values of private dict foreach (CffDataDicEntry dicEntry in dicData) { switch (dicEntry.Operator.Name) { case "Subrs": int localSubrsOffset = (int)dicEntry.Operands[0].RealNumValue; reader.BaseStream.Position = this.offset + fdict.PrivateDicOffset + localSubrsOffset; fdict.LocalSubr = ReadSubrBuffer(reader); break; case "defaultWidthX": case "nominalWidthX": break; } } } } return fontDicts; } private CffGlyphData[] ReadCharStringsIndex( BigEndianBinaryReader reader, CffTopDictionary topDictionary, byte[][] globalSubrBuffers, FontDict[] fontDicts, CffPrivateDictionary? privateDictionary) { // 14. CharStrings INDEX // This contains the charstrings of all the glyphs in a font stored in // an INDEX structure. // Charstring objects contained within this // INDEX are accessed by GID. // The first charstring(GID 0) must be // the.notdef glyph. // The number of glyphs available in a font may // be determined from the count field in the INDEX. // // The format of the charstring data, and therefore the method of // interpretation, is specified by the // CharstringType operator in the Top DICT. // The CharstringType operator has a default value // of 2 indicating the Type 2 charstring format which was designed // in conjunction with CFF. // Type 1 charstrings are documented in // the "Adobe Type 1 Font Format" published by Addison - Wesley. // Type 2 charstrings are described in Adobe Technical Note #5177: // "Type 2 Charstring Format." Other charstring types may also be // supported by this method. reader.BaseStream.Position = this.offset + this.charStringsOffset; if (!TryReadIndexDataOffsets(reader, out CffIndexOffset[]? offsets)) { throw new InvalidFontFileException("No glyph data found."); } int glyphCount = offsets.Length; CffGlyphData[] glyphs = new CffGlyphData[glyphCount]; byte[][]? localSubBuffer = privateDictionary?.LocalSubrRawBuffers; // Is the font a CID font? FDRangeProvider fdRangeProvider = new(topDictionary.CidFontInfo); bool isCidFont = topDictionary.CidFontInfo.FdRanges.Length > 0; for (int i = 0; i < glyphCount; ++i) { CffIndexOffset offset = offsets[i]; byte[] charstringsBuffer = reader.ReadBytes(offset.Length); // Now we can parse the raw glyph instructions if (isCidFont) { // Select proper local private dict fdRangeProvider.SetCurrentGlyphIndex((ushort)i); localSubBuffer = fontDicts[fdRangeProvider.SelectedFDArray].LocalSubr; } glyphs[i] = new CffGlyphData( (ushort)i, globalSubrBuffers, localSubBuffer ?? Array.Empty<byte[]>(), privateDictionary?.NominalWidthX ?? 0, charstringsBuffer); } return glyphs; } private static void ReadFormat0Encoding(BigEndianBinaryReader reader) { // Table 11: Format 0 // Type Name Description // Card8 format = 0 // Card8 nCodes Number of encoded glyphs // Card8 code[nCodes] Code array //------- // Each element of the code array represents the encoding for the // corresponding glyph. This format should be used when the // codes are in a fairly random order // we have read format field( 1st field) .. // so start with 2nd field int nCodes = reader.ReadByte(); byte[] codes = reader.ReadBytes(nCodes); // TODO: Implement based on PDFPig } private static void ReadFormat1Encoding(BigEndianBinaryReader reader) { // Table 12 Format 1 // Type Name Description // Card8 format = 1 // Card8 nRanges Number of code ranges //
Range2
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/Jetbrains.Annotations.cs
{ "start": 13766, "end": 14597 }
internal sealed class ____ : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags]
MeansImplicitUseAttribute
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Types/ObjectTypeCollection.cs
{ "start": 1454, "end": 1991 }
private sealed class ____( ObjectTypeCollection types) : IReadOnlyObjectTypeDefinitionCollection { public int Count => types._types.Length; public IObjectTypeDefinition this[int index] => types._types[index]; public bool ContainsName(string name) => types._nameLookup.ContainsKey(name); public IEnumerator<IObjectTypeDefinition> GetEnumerator() => types.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
ReadOnlyObjectTypeDefinitionCollection
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 126108, "end": 126739 }
partial class ____<T> : Cloning.IDeepCopier<System.Collections.Generic.SortedSet<T>>, Cloning.IDeepCopier, Cloning.IBaseCopier<System.Collections.Generic.SortedSet<T>>, Cloning.IBaseCopier { public SortedSetCopier(Cloning.IDeepCopier<T> elementCopier) { } public System.Collections.Generic.SortedSet<T> DeepCopy(System.Collections.Generic.SortedSet<T> input, Cloning.CopyContext context) { throw null; } public void DeepCopy(System.Collections.Generic.SortedSet<T> input, System.Collections.Generic.SortedSet<T> output, Cloning.CopyContext context) { } } [GenerateSerializer]
SortedSetCopier
csharp
neuecc__MessagePack-CSharp
tests/MessagePack.SourceGenerator.Tests/Resources/FormatterForClassWithPrivateMembers_WithNamespace/MessagePack.GeneratedMessagePackResolver.g.cs
{ "start": 1230, "end": 1850 }
private static class ____ { private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) { { typeof(global::A.MyObject), 0 }, }; internal static object GetFormatter(global::System.Type t) { if (closedTypeLookup.TryGetValue(t, out int closedKey)) { switch (closedKey) { case 0: return new global::A.MyObject.MyObjectFormatter(); default: return null; // unreachable }; } return null; } } } }
GeneratedMessagePackResolverGetFormatterHelper
csharp
ChilliCream__graphql-platform
src/HotChocolate/Data/test/Data.Projections.SqlServer.Tests/QueryableProjectionSortingTests.cs
{ "start": 9753, "end": 10189 }
public class ____ { public int Id { get; set; } public short BarShort { get; set; } public string BarString { get; set; } = string.Empty; public BarEnum BarEnum { get; set; } public bool BarBool { get; set; } [UseFiltering] [UseSorting] public List<BarDeep> ObjectArray { get; set; } = null!; public BarDeep NestedObject { get; set; } = null!; }
Foo
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Configuration/Consumers/IActivityConfigurationObserverConnector.cs
{ "start": 28, "end": 200 }
public interface ____ { ConnectHandle ConnectActivityConfigurationObserver(IActivityConfigurationObserver observer); } }
IActivityConfigurationObserverConnector
csharp
npgsql__npgsql
src/Npgsql/BackendMessages/CopyMessages.cs
{ "start": 978, "end": 1250 }
sealed class ____ : CopyResponseMessageBase { public override BackendMessageCode Code => BackendMessageCode.CopyInResponse; internal new CopyInResponseMessage Load(NpgsqlReadBuffer buf) { base.Load(buf); return this; } }
CopyInResponseMessage
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/Pinecone.ConformanceTests/Support/PineconeTestStore.cs
{ "start": 4262, "end": 5566 }
private sealed class ____ : DelegatingHandler { private readonly Dictionary<int, int> _containerToHostPort; public RedirectHandler(Dictionary<int, int> portRedirections) : base(new HttpClientHandler()) { this._containerToHostPort = portRedirections; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // When "host" argument is not provided for PineconeClient.Index, // it will try to get the host from the Pinecone service. // In the cloud environment it's fine, but with the local emulator // it reports the address with the container port, not the host port. if (request.RequestUri != null && request.RequestUri.IsAbsoluteUri && request.RequestUri.Host == "localhost" && this._containerToHostPort.TryGetValue(request.RequestUri.Port, out int hostPort)) { UriBuilder builder = new(request.RequestUri) { Port = hostPort }; request.RequestUri = builder.Uri; } return base.SendAsync(request, cancellationToken); } } }
RedirectHandler
csharp
MassTransit__MassTransit
src/Transports/MassTransit.AmazonSqsTransport/AmazonSqsTransport/Topology/AmazonSqsBusTopology.cs
{ "start": 107, "end": 2501 }
public class ____ : BusTopology, IAmazonSqsBusTopology { readonly IAmazonSqsTopologyConfiguration _configuration; readonly IAmazonSqsHostConfiguration _hostConfiguration; readonly IMessageNameFormatter _messageNameFormatter; public AmazonSqsBusTopology(IAmazonSqsHostConfiguration hostConfiguration, IMessageNameFormatter messageNameFormatter, IAmazonSqsTopologyConfiguration configuration) : base(hostConfiguration, configuration) { _hostConfiguration = hostConfiguration; _messageNameFormatter = messageNameFormatter; _configuration = configuration; } IAmazonSqsPublishTopology IAmazonSqsBusTopology.PublishTopology => _configuration.Publish; IAmazonSqsSendTopology IAmazonSqsBusTopology.SendTopology => _configuration.Send; IAmazonSqsMessagePublishTopology<T> IAmazonSqsBusTopology.Publish<T>() { return _configuration.Publish.GetMessageTopology<T>(); } IAmazonSqsMessageSendTopology<T> IAmazonSqsBusTopology.Send<T>() { return _configuration.Send.GetMessageTopology<T>(); } public SendSettings GetSendSettings(Uri address) { var endpointAddress = new AmazonSqsEndpointAddress(_hostConfiguration.HostAddress, address); return _configuration.Send.GetSendSettings(endpointAddress); } public Uri GetDestinationAddress(string topicName, Action<IAmazonSqsTopicConfigurator>? configure = null) { var address = new AmazonSqsEndpointAddress(_hostConfiguration.HostAddress, new Uri($"topic:{topicName}")); var publishSettings = new TopicPublishSettings(address); configure?.Invoke(publishSettings); return publishSettings.GetSendAddress(_hostConfiguration.HostAddress); } public Uri GetDestinationAddress(Type messageType, Action<IAmazonSqsTopicConfigurator>? configure = null) { var topicName = _messageNameFormatter.GetMessageName(messageType); var isTemporary = MessageTypeCache.IsTemporaryMessageType(messageType); var address = new AmazonSqsEndpointAddress(_hostConfiguration.HostAddress, new Uri($"topic:{topicName}?temporary={isTemporary}")); var publishSettings = new TopicPublishSettings(address); configure?.Invoke(publishSettings); return publishSettings.GetSendAddress(_hostConfiguration.HostAddress); } }
AmazonSqsBusTopology
csharp
MiniProfiler__dotnet
src/MiniProfiler.EF6/EFProfiledDbConnectionFactory.cs
{ "start": 257, "end": 1488 }
public class ____ : IDbConnectionFactory { private readonly IDbConnectionFactory _inner; /// <summary> /// Initializes a new instance of the <see cref="EFProfiledDbConnectionFactory"/> class. /// </summary> /// <param name="inner">The <see cref="IDbConnectionFactory"/> to wrap.</param> public EFProfiledDbConnectionFactory(IDbConnectionFactory inner) => _inner = inner; /// <summary> /// Creates a connection based on the given database name or connection string. /// </summary> /// <param name="nameOrConnectionString">The database name or connection string.</param> /// <returns>An initialized <see cref="DbConnection"/>.</returns> public DbConnection CreateConnection(string nameOrConnectionString) { var connection = _inner.CreateConnection(nameOrConnectionString); if (connection is ProfiledDbConnection) { return connection; } var profiler = MiniProfiler.Current; return profiler != null ? new ProfiledDbConnection(connection, profiler) : connection; } } }
EFProfiledDbConnectionFactory
csharp
icsharpcode__ILSpy
ICSharpCode.ILSpyX/MermaidDiagrammer/ClassDiagrammer.cs
{ "start": 1455, "end": 2625 }
public sealed class ____ { internal const string NewLine = "\n"; internal string SourceAssemblyName { get; set; } = null!; internal string SourceAssemblyVersion { get; set; } = null!; /// <summary>Types selectable in the diagrammer, grouped by their /// <see cref="System.Type.Namespace"/> to facilitate a structured type selection.</summary> internal Dictionary<string, Type[]> TypesByNamespace { get; set; } = null!; /// <summary>Types not included in the <see cref="ClassDiagrammer"/>, /// but referenced by <see cref="Type"/>s that are. /// Contains display names (values; similar to <see cref="Type.Name"/>) /// by their referenced IDs (keys; similar to <see cref="Type.Id"/>).</summary> internal Dictionary<string, string> OutsideReferences { get; set; } = null!; /// <summary>Types excluded from the <see cref="ClassDiagrammer"/>; /// used to support <see cref="GenerateHtmlDiagrammer.ReportExludedTypes"/>.</summary> internal string[] Excluded { get; set; } = null!; /// <summary>A <see cref="Type"/>-like structure with collections /// of property relations to one or many other <see cref="Type"/>s.</summary>
ClassDiagrammer
csharp
EventStore__EventStore
src/KurrentDB.Plugins.Tests/Diagnostics/PluginDiagnosticsDataCollectorTests.cs
{ "start": 3607, "end": 3675 }
class ____(string? pluginName = null) : Plugin(pluginName);
TestPlugin
csharp
MonoGame__MonoGame
Tools/MonoGame.Tools.Tests/AssetTestClasses.cs
{ "start": 6202, "end": 6342 }
public class ____ { [ContentSerializer(SharedResource = true)] public Linked2[] Next; } #endregion #region CircularReferences
Linked2
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/SimpleStateMachine_Specs.cs
{ "start": 2095, "end": 2797 }
class ____ : MassTransitStateMachine<Instance> { public TestStateMachine() { InstanceState(x => x.CurrentState); Event(() => Started); Event(() => Stopped); Initially( When(Started) .TransitionTo(Running)); During(Running, When(Stopped) .Finalize()); } // ReSharper disable UnassignedGetOnlyAutoProperty public State Running { get; } public Event<Start> Started { get; } public Event<Stop> Stopped { get; } }
TestStateMachine
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web.Framework/Validators/CreditCardPropertyValidator.cs
{ "start": 157, "end": 1414 }
public partial class ____<T, TProperty> : PropertyValidator<T, TProperty> { public override string Name => "CreditCardPropertyValidator"; /// <summary> /// Is valid? /// </summary> /// <param name="context">Validation context</param> /// <returns>Result</returns> public override bool IsValid(ValidationContext<T> context, TProperty value) { var ccValue = value as string; if (string.IsNullOrWhiteSpace(ccValue)) return false; ccValue = ccValue.Replace(" ", ""); ccValue = ccValue.Replace("-", ""); var checksum = 0; var evenDigit = false; //http://www.beachnet.com/~hstiles/cardtype.html foreach (var digit in ccValue.Reverse()) { if (!char.IsDigit(digit)) return false; var digitValue = (digit - '0') * (evenDigit ? 2 : 1); evenDigit = !evenDigit; while (digitValue > 0) { checksum += digitValue % 10; digitValue /= 10; } } return (checksum % 10) == 0; } protected override string GetDefaultMessageTemplate(string errorCode) => "Credit card number is not valid"; }
CreditCardPropertyValidator
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/RequestFilter_Specs.cs
{ "start": 1342, "end": 1625 }
public class ____ : IConsumer<PingMessage> { public Task Consume(ConsumeContext<PingMessage> context) { return context.RespondAsync(new PongMessage(context.Message.CorrelationId)); } }
PingConsumer
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Queries/ViewModels/QueriesIndexViewModel.cs
{ "start": 131, "end": 395 }
public class ____ { public IList<QueryEntry> Queries { get; set; } public ContentOptions Options { get; set; } = new ContentOptions(); public dynamic Pager { get; set; } public IEnumerable<string> QuerySourceNames { get; set; } }
QueriesIndexViewModel
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Composition/Events/SchemaEvents.cs
{ "start": 1454, "end": 1525 }
internal record ____(MutableSchemaDefinition Schema) : IEvent;
SchemaEvent
csharp
dotnet__maui
src/Controls/tests/ManualTests/Views/Layout/LineBreakModeLayoutPage.xaml.cs
{ "start": 85, "end": 367 }
public partial class ____ : ContentPage { public LineBreakModeLayoutPage() { InitializeComponent(); this.BindingContext = this; } public ObservableCollection<object> Items { get; set; } = new() { new(), new(), new(), new(), }; } }
LineBreakModeLayoutPage
csharp
dotnet__orleans
src/Orleans.Core/Configuration/Options/LoadSheddingOptions.cs
{ "start": 133, "end": 2851 }
public class ____ { /// <summary> /// The default value for <see cref="LoadSheddingLimit"/>. /// </summary> internal const int DefaultCpuThreshold = 95; /// <summary> /// The default value for <see cref="MemoryThreshold"/>. /// </summary> internal const int DefaultMemoryThreshold = 90; /// <summary> /// Gets or sets a value indicating whether load shedding in the client gateway and stream providers is enabled. /// The default value is <see langword="false"/>, meaning that load shedding is disabled. /// </summary> /// <value>Load shedding is disabled by default.</value> public bool LoadSheddingEnabled { get; set; } /// <summary> /// Gets or sets the CPU utilization, expressed as a value between <c>0</c> and <c>100</c>, at which load shedding begins. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// </summary> /// <value>Load shedding begins at a CPU utilization of 95% by default, if load shedding is enabled.</value> /// <remarks>This property is deprecated. Use <see cref="CpuThreshold"/> instead.</remarks> [Obsolete($"Use {nameof(CpuThreshold)} instead.", error: true)] public int LoadSheddingLimit { get => CpuThreshold; set => CpuThreshold = value; } /// <summary> /// Gets or sets the CPU utilization, expressed as a value between <c>0</c> and <c>100</c>, at which load shedding begins. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// </summary> /// <value>Load shedding begins at a CPU utilization of 95% by default, if load shedding is enabled.</value> public int CpuThreshold { get; set; } = DefaultCpuThreshold; /// <summary> /// Gets or sets the memory utilization, expressed as a value between <c>0</c> and <c>100</c>, at which load shedding begins. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// </summary> /// <value>Load shedding begins at a memory utilization of 90% by default, if load shedding is enabled.</value> public int MemoryThreshold { get; set; } = DefaultMemoryThreshold; } }
LoadSheddingOptions
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Threading/DispatcherPriority.cs
{ "start": 249, "end": 8638 }
struct ____ : IEquatable<DispatcherPriority>, IComparable<DispatcherPriority> { /// <summary> /// The integer value of the priority /// </summary> public int Value { get; } private DispatcherPriority(int value) { Value = value; } /// <summary> /// The lowest foreground dispatcher priority /// </summary> public static readonly DispatcherPriority Default = new(0); internal static readonly DispatcherPriority MinimumForegroundPriority = Default; /// <summary> /// The job will be processed with the same priority as input. /// </summary> public static readonly DispatcherPriority Input = new(Default - 1); /// <summary> /// The job will be processed after other non-idle operations have completed. /// </summary> public static readonly DispatcherPriority Background = new(Input - 1); /// <summary> /// The job will be processed after background operations have completed. /// </summary> public static readonly DispatcherPriority ContextIdle = new(Background - 1); /// <summary> /// The job will be processed when the application is idle. /// </summary> public static readonly DispatcherPriority ApplicationIdle = new (ContextIdle - 1); /// <summary> /// The job will be processed when the system is idle. /// </summary> public static readonly DispatcherPriority SystemIdle = new(ApplicationIdle - 1); /// <summary> /// Minimum possible priority that's actually dispatched, default value /// </summary> internal static readonly DispatcherPriority MinimumActiveValue = new(SystemIdle); /// <summary> /// A dispatcher priority for jobs that shouldn't be executed yet /// </summary> public static readonly DispatcherPriority Inactive = new(MinimumActiveValue - 1); /// <summary> /// Minimum valid priority /// </summary> internal static readonly DispatcherPriority MinValue = new(Inactive); /// <summary> /// Used internally in dispatcher code /// </summary> public static readonly DispatcherPriority Invalid = new(MinimumActiveValue - 2); /// <summary> /// The job will be processed after layout and render but before input. /// </summary> public static readonly DispatcherPriority Loaded = new(Default + 1); /// <summary> /// A special priority for platforms with UI render timer or for forced full rasterization requests /// </summary> [PrivateApi] public static readonly DispatcherPriority UiThreadRender = new(Loaded + 1); /// <summary> /// A special priority to synchronize native control host positions, IME, etc /// We should probably have a better API for that, so the priority is internal /// </summary> internal static readonly DispatcherPriority AfterRender = new(UiThreadRender + 1); /// <summary> /// The job will be processed with the same priority as render. /// </summary> public static readonly DispatcherPriority Render = new(AfterRender + 1); /// <summary> /// A special platform hook for jobs to be executed before the normal render cycle /// </summary> [PrivateApi] public static readonly DispatcherPriority BeforeRender = new(Render + 1); /// <summary> /// A special priority for platforms that resize the render target in asynchronous-ish matter, /// should be changed into event grouping in the platform backend render /// </summary> [PrivateApi] public static readonly DispatcherPriority AsyncRenderTargetResize = new(BeforeRender + 1); /// <summary> /// The job will be processed with the same priority as data binding. /// </summary> [Obsolete("WPF compatibility"), EditorBrowsable(EditorBrowsableState.Never)] public static readonly DispatcherPriority DataBind = new(AsyncRenderTargetResize + 1); /// <summary> /// The job will be processed with normal priority. /// </summary> #pragma warning disable CS0618 public static readonly DispatcherPriority Normal = new(DataBind + 1); #pragma warning restore CS0618 /// <summary> /// The job will be processed before other asynchronous operations. /// </summary> public static readonly DispatcherPriority Send = new(Normal + 1); /// <summary> /// Maximum possible priority /// </summary> public static readonly DispatcherPriority MaxValue = Send; // Note: unlike ctor this one is validating public static DispatcherPriority FromValue(int value) { if (value < MinValue.Value || value > MaxValue.Value) throw new ArgumentOutOfRangeException(nameof(value)); return new DispatcherPriority(value); } public static implicit operator int(DispatcherPriority priority) => priority.Value; public static implicit operator DispatcherPriority(int value) => FromValue(value); /// <inheritdoc /> public bool Equals(DispatcherPriority other) => Value == other.Value; /// <inheritdoc /> public override bool Equals(object? obj) => obj is DispatcherPriority other && Equals(other); /// <inheritdoc /> public override int GetHashCode() => Value.GetHashCode(); public static bool operator ==(DispatcherPriority left, DispatcherPriority right) => left.Value == right.Value; public static bool operator !=(DispatcherPriority left, DispatcherPriority right) => left.Value != right.Value; public static bool operator <(DispatcherPriority left, DispatcherPriority right) => left.Value < right.Value; public static bool operator >(DispatcherPriority left, DispatcherPriority right) => left.Value > right.Value; public static bool operator <=(DispatcherPriority left, DispatcherPriority right) => left.Value <= right.Value; public static bool operator >=(DispatcherPriority left, DispatcherPriority right) => left.Value >= right.Value; /// <inheritdoc /> public int CompareTo(DispatcherPriority other) => Value.CompareTo(other.Value); public static void Validate(DispatcherPriority priority, string parameterName) { if (priority < Inactive || priority > MaxValue) throw new ArgumentException("Invalid DispatcherPriority value", parameterName); } #pragma warning disable CS0618 public override string ToString() { if (this == Invalid) return nameof(Invalid); if (this == Inactive) return nameof(Inactive); if (this == SystemIdle) return nameof(SystemIdle); if (this == ContextIdle) return nameof(ContextIdle); if (this == ApplicationIdle) return nameof(ApplicationIdle); if (this == Background) return nameof(Background); if (this == Input) return nameof(Input); if (this == Default) return nameof(Default); if (this == Loaded) return nameof(Loaded); if (this == UiThreadRender) return nameof(UiThreadRender); if (this == AfterRender) return nameof(AfterRender); if (this == Render) return nameof(Render); if (this == BeforeRender) return nameof(BeforeRender); if (this == AsyncRenderTargetResize) return nameof(AsyncRenderTargetResize); if (this == DataBind) return nameof(DataBind); if (this == Normal) return nameof(Normal); if (this == Send) return nameof(Send); return Value.ToString(); } #pragma warning restore CS0618 } }
DispatcherPriority
csharp
dotnet__aspnetcore
src/Security/Authentication/test/AuthenticationMiddlewareTests.cs
{ "start": 13279, "end": 14390 }
private class ____ : IAuthenticationRequestHandler { private HttpContext _context; public Task<AuthenticateResult> AuthenticateAsync() { throw new NotImplementedException(); } public Task ChallengeAsync(AuthenticationProperties properties) { throw new NotImplementedException(); } public Task ForbidAsync(AuthenticationProperties properties) { throw new NotImplementedException(); } public Task<bool> HandleRequestAsync() { return Task.FromResult(false); } public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { _context = context; return Task.FromResult(0); } public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) { throw new NotImplementedException(); } public Task SignOutAsync(AuthenticationProperties properties) { throw new NotImplementedException(); } } }
SkipHandler
csharp
ChilliCream__graphql-platform
src/HotChocolate/Adapters/src/Adapters.OpenApi.Core/Storage/IOpenApiDefinitionStorage.cs
{ "start": 42, "end": 258 }
public interface ____ : IObservable<OpenApiDefinitionStorageEventArgs> { ValueTask<IEnumerable<OpenApiDocumentDefinition>> GetDocumentsAsync(CancellationToken cancellationToken = default); }
IOpenApiDefinitionStorage
csharp
MassTransit__MassTransit
src/MassTransit/Sagas/Configuration/ConstructorSagaInstanceFactory.cs
{ "start": 395, "end": 1252 }
public class ____<TSaga> where TSaga : class, ISaga { public ConstructorSagaInstanceFactory() { var constructorInfo = typeof(TSaga).GetConstructor(new[] { typeof(Guid) }); if (constructorInfo == null) { throw new ArgumentException("The saga does not have a public constructor with a single Guid correlationId parameter: " + TypeCache<TSaga>.ShortName); } var correlationId = Expression.Parameter(typeof(Guid), "correlationId"); var @new = Expression.New(constructorInfo, correlationId); FactoryMethod = Expression.Lambda<SagaInstanceFactoryMethod<TSaga>>(@new, correlationId).CompileFast(); } public SagaInstanceFactoryMethod<TSaga> FactoryMethod { get; } } }
ConstructorSagaInstanceFactory
csharp
dotnet__orleans
src/api/Orleans.Transactions/Orleans.Transactions.cs
{ "start": 21026, "end": 21492 }
partial class ____<TAttribute> : Runtime.IAttributeToFactoryMapper<TAttribute> where TAttribute : IFacetMetadata, Abstractions.ITransactionalStateConfiguration { protected abstract Abstractions.TransactionalStateConfiguration AttributeToConfig(TAttribute attribute); public Factory<Runtime.IGrainContext, object> GetFactory(System.Reflection.ParameterInfo parameter, TAttribute attribute) { throw null; } }
TransactionalStateAttributeMapper
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web/Factories/INewsletterModelFactory.cs
{ "start": 155, "end": 924 }
public partial interface ____ { /// <summary> /// Prepare the newsletter box model /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the newsletter box model /// </returns> Task<NewsLetterBoxModel> PrepareNewsLetterBoxModelAsync(); /// <summary> /// Prepare the subscription activation model /// </summary> /// <param name="active">Whether the subscription has been activated</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the subscription activation model /// </returns> Task<SubscriptionActivationModel> PrepareSubscriptionActivationModelAsync(bool active); }
INewsLetterModelFactory
csharp
nunit__nunit
src/NUnitFramework/framework/Internal/AssemblyHelper.cs
{ "start": 365, "end": 2442 }
public static class ____ { private static readonly string UriSchemeFile = Uri.UriSchemeFile; private static readonly string SchemeDelimiter = Uri.SchemeDelimiter; #region GetAssemblyPath /// <summary> /// Gets the path from which an assembly was loaded. /// For builds where this is not possible, returns /// the name of the assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The path.</returns> public static string GetAssemblyPath(Assembly assembly) { #if NETFRAMEWORK // https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location // .NET Framework only: // If the loaded file was shadow-copied, the location is that of the file after being shadow-copied. // To get the location before the file has been shadow-copied, use the CodeBase property. string? codeBase = assembly.CodeBase; if (codeBase is not null && IsFileUri(codeBase)) return GetAssemblyPathFromCodeBase(codeBase); #endif return assembly.Location; } #endregion #region GetDirectoryName /// <summary> /// Gets the path to the directory from which an assembly was loaded. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The path.</returns> public static string GetDirectoryName(Assembly assembly) { return Path.GetDirectoryName(GetAssemblyPath(assembly))!; } #endregion #region GetAssemblyName /// <summary> /// Gets the AssemblyName of an assembly. /// </summary> /// <param name="assembly">The assembly</param> /// <returns>An AssemblyName</returns> public static AssemblyName GetAssemblyName(Assembly assembly) { return assembly.GetName(); } #endregion #region Load #if !NETFRAMEWORK
AssemblyHelper
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Media/Transform/Basics.xaml.cs
{ "start": 217, "end": 311 }
partial class ____ : Page { public Basics() { this.InitializeComponent(); } } }
Basics
csharp
npgsql__npgsql
src/Npgsql.GeoJSON/Internal/CrsMapBuilder.cs
{ "start": 52, "end": 1517 }
struct ____ { CrsMapEntry[] _overrides; int _overriddenIndex; int _wellKnownIndex; internal void Add(in CrsMapEntry entry) { var wellKnown = CrsMap.WellKnown[_wellKnownIndex]; if (wellKnown.MinSrid == entry.MinSrid && wellKnown.MaxSrid == entry.MaxSrid && string.Equals(wellKnown.Authority, entry.Authority, StringComparison.Ordinal)) { _wellKnownIndex++; return; } if (wellKnown.MinSrid < entry.MinSrid) { do _wellKnownIndex++; while (CrsMap.WellKnown.Length < _wellKnownIndex && CrsMap.WellKnown[_wellKnownIndex].MaxSrid < entry.MaxSrid); AddCore(new CrsMapEntry(wellKnown.MinSrid, Math.Min(wellKnown.MaxSrid, entry.MinSrid - 1), null)); } AddCore(entry); } void AddCore(in CrsMapEntry entry) { var index = _overriddenIndex + 1; if (_overrides == null) _overrides = new CrsMapEntry[4]; else if (_overrides.Length == index) Array.Resize(ref _overrides, _overrides.Length << 1); _overrides[_overriddenIndex] = entry; _overriddenIndex = index; } internal CrsMap Build() { if (_overrides != null && _overrides.Length < _overriddenIndex) Array.Resize(ref _overrides, _overriddenIndex); return new CrsMap(_overrides); } }
CrsMapBuilder
csharp
DuendeSoftware__IdentityServer
identity-server/src/EntityFramework.Storage/Entities/ClientCorsOrigin.cs
{ "start": 206, "end": 389 }
public class ____ { public int Id { get; set; } public string Origin { get; set; } public int ClientId { get; set; } public Client Client { get; set; } }
ClientCorsOrigin
csharp
dotnet__aspnetcore
src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiDocumentService/OpenApiDocumentServiceTests.RequestBody.cs
{ "start": 57067, "end": 58077 }
private class ____ : JsonPatchDocument; [Fact] public async Task GetRequestBody_HandlesGenericCustomJsonPatchBody() { // Arrange var builder = CreateBuilder(); // Act builder.MapPatch("/", (CustomJsonPatchDocument<JsonPatchModel> patch) => { }); // Assert await VerifyOpenApiDocument(builder, document => { var paths = Assert.Single(document.Paths.Values); var operation = paths.Operations[HttpMethod.Patch]; Assert.NotNull(operation.RequestBody); Assert.False(operation.RequestBody.Required); Assert.NotNull(operation.RequestBody.Content); var content = Assert.Single(operation.RequestBody.Content); Assert.Equal("application/json-patch+json", content.Key); var schema = Assert.IsType<OpenApiSchemaReference>(content.Value.Schema); Assert.Equal("JsonPatchDocument", schema.Reference.Id); }); }
CustomJsonPatchDocument
csharp
jellyfin__jellyfin
tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManager/FindExtrasTests.cs
{ "start": 801, "end": 12591 }
public class ____ { private readonly Emby.Server.Implementations.Library.LibraryManager _libraryManager; private readonly Mock<IFileSystem> _fileSystemMock; public FindExtrasTests() { var fixture = new Fixture().Customize(new AutoMoqCustomization()); fixture.Register(() => new NamingOptions()); var configMock = fixture.Freeze<Mock<IServerConfigurationManager>>(); configMock.Setup(c => c.ApplicationPaths.ProgramDataPath).Returns("/data"); var itemRepository = fixture.Freeze<Mock<IItemRepository>>(); itemRepository.Setup(i => i.RetrieveItem(It.IsAny<Guid>())).Returns<BaseItem>(null); _fileSystemMock = fixture.Freeze<Mock<IFileSystem>>(); _fileSystemMock.Setup(f => f.GetFileInfo(It.IsAny<string>())).Returns<string>(path => new FileSystemMetadata { FullName = path }); _libraryManager = fixture.Build<Emby.Server.Implementations.Library.LibraryManager>().Do(s => s.AddParts( fixture.Create<IEnumerable<IResolverIgnoreRule>>(), new List<IItemResolver> { new AudioResolver(fixture.Create<NamingOptions>()) }, fixture.Create<IEnumerable<IIntroProvider>>(), fixture.Create<IEnumerable<IBaseItemComparer>>(), fixture.Create<IEnumerable<ILibraryPostScanTask>>())) .Create(); // This is pretty terrible but unavoidable BaseItem.FileSystem ??= fixture.Create<IFileSystem>(); BaseItem.MediaSourceManager ??= fixture.Create<IMediaSourceManager>(); } [Fact] public void FindExtras_SeparateMovieFolder_FindsCorrectExtras() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up.mkv" }; var paths = new List<string> { "/movies/Up/Up.mkv", "/movies/Up/Up - trailer.mkv", "/movies/Up/Up - sample.mkv", "/movies/Up/Up something else.mkv", "/movies/Up/Up-extra.mkv" }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, IsDirectory = false }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); Assert.Equal(3, extras.Count); Assert.Equal(ExtraType.Unknown, extras[0].ExtraType); Assert.Equal(ExtraType.Trailer, extras[1].ExtraType); Assert.Equal(typeof(Trailer), extras[1].GetType()); Assert.Equal(ExtraType.Sample, extras[2].ExtraType); } [Fact] public void FindExtras_SeparateMovieFolder_CleanExtraNames() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up.mkv" }; var paths = new List<string> { "/movies/Up/Up.mkv", "/movies/Up/Recording the audio[Bluray]-behindthescenes.mkv", "/movies/Up/Interview with the dog-interview.mkv", "/movies/Up/shorts/Balloons[1080p].mkv" }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, IsDirectory = false }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); Assert.Equal(3, extras.Count); Assert.Equal(ExtraType.BehindTheScenes, extras[0].ExtraType); Assert.Equal("Recording the audio", extras[0].Name); Assert.Equal(ExtraType.Interview, extras[1].ExtraType); Assert.Equal("Interview with the dog", extras[1].Name); Assert.Equal(ExtraType.Short, extras[2].ExtraType); Assert.Equal("Balloons", extras[2].Name); } [Fact] public void FindExtras_SeparateMovieFolderWithMixedExtras_FindsCorrectExtras() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up.mkv" }; var paths = new List<string> { "/movies/Up/Up.mkv", "/movies/Up/Up - trailer.mkv", "/movies/Up/trailers", "/movies/Up/theme-music", "/movies/Up/theme.mp3", "/movies/Up/not a theme.mp3", "/movies/Up/behind the scenes", "/movies/Up/behind the scenes.mkv", "/movies/Up/Up - sample.mkv", "/movies/Up/Up something else.mkv", "/movies/Up/extras" }; _fileSystemMock.Setup(f => f.GetFiles( "/movies/Up/trailers", It.IsAny<string[]>(), false, false)) .Returns(new List<FileSystemMetadata> { new() { FullName = "/movies/Up/trailers/some trailer.mkv", Name = "some trailer.mkv", IsDirectory = false } }).Verifiable(); _fileSystemMock.Setup(f => f.GetFiles( "/movies/Up/behind the scenes", It.IsAny<string[]>(), false, false)) .Returns(new List<FileSystemMetadata> { new() { FullName = "/movies/Up/behind the scenes/the making of Up.mkv", Name = "the making of Up.mkv", IsDirectory = false } }).Verifiable(); _fileSystemMock.Setup(f => f.GetFiles( "/movies/Up/theme-music", It.IsAny<string[]>(), false, false)) .Returns(new List<FileSystemMetadata> { new() { FullName = "/movies/Up/theme-music/theme2.mp3", Name = "theme2.mp3", IsDirectory = false } }).Verifiable(); _fileSystemMock.Setup(f => f.GetFiles( "/movies/Up/extras", It.IsAny<string[]>(), false, false)) .Returns(new List<FileSystemMetadata> { new() { FullName = "/movies/Up/extras/Honest Trailer.mkv", Name = "Honest Trailer.mkv", IsDirectory = false } }).Verifiable(); var files = paths.Select(p => new FileSystemMetadata { FullName = p, Name = Path.GetFileName(p), IsDirectory = !Path.HasExtension(p) }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); _fileSystemMock.Verify(); Assert.Equal(7, extras.Count); Assert.Equal(ExtraType.Unknown, extras[0].ExtraType); Assert.Equal(typeof(Video), extras[0].GetType()); Assert.Equal(ExtraType.Trailer, extras[1].ExtraType); Assert.Equal(typeof(Trailer), extras[1].GetType()); Assert.Equal(ExtraType.Trailer, extras[2].ExtraType); Assert.Equal(typeof(Trailer), extras[2].GetType()); Assert.Equal(ExtraType.BehindTheScenes, extras[3].ExtraType); Assert.Equal(ExtraType.Sample, extras[4].ExtraType); Assert.Equal(ExtraType.ThemeSong, extras[5].ExtraType); Assert.Equal(typeof(Audio), extras[5].GetType()); Assert.Equal(ExtraType.ThemeSong, extras[6].ExtraType); Assert.Equal(typeof(Audio), extras[6].GetType()); } [Fact] public void FindExtras_SeparateMovieFolderWithMixedExtras_FindsOnlyExtrasInMovieFolder() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up.mkv" }; var paths = new List<string> { "/movies/Up/Up.mkv", "/movies/Up/trailer.mkv", "/movies/Another Movie/trailer.mkv" }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, IsDirectory = false }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); Assert.Single(extras); Assert.Equal(ExtraType.Trailer, extras[0].ExtraType); Assert.Equal(typeof(Trailer), extras[0].GetType()); Assert.Equal("trailer", extras[0].FileNameWithoutExtension); Assert.Equal("/movies/Up/trailer.mkv", extras[0].Path); } [Fact] public void FindExtras_SeparateMovieFolderWithParts_FindsCorrectExtras() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up - part1.mkv" }; var paths = new List<string> { "/movies/Up/Up - part1.mkv", "/movies/Up/Up - part2.mkv", "/movies/Up/trailer.mkv", "/movies/Another Movie/trailer.mkv" }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, IsDirectory = false }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); Assert.Single(extras); Assert.Equal(ExtraType.Trailer, extras[0].ExtraType); Assert.Equal(typeof(Trailer), extras[0].GetType()); Assert.Equal("trailer", extras[0].FileNameWithoutExtension); Assert.Equal("/movies/Up/trailer.mkv", extras[0].Path); } [Fact] public void FindExtras_WrongExtensions_FindsNoExtras() { var owner = new Movie { Name = "Up", Path = "/movies/Up/Up.mkv" }; var paths = new List<string> { "/movies/Up/Up.mkv", "/movies/Up/trailer.noext", "/movies/Up/theme.png", "/movies/Up/trailers" }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, Name = Path.GetFileName(p), IsDirectory = !Path.HasExtension(p) }).ToList(); _fileSystemMock.Setup(f => f.GetFiles( "/movies/Up/trailers", It.IsAny<string[]>(), false, false)) .Returns(new List<FileSystemMetadata> { new() { FullName = "/movies/Up/trailers/trailer.jpg", Name = "trailer.jpg", IsDirectory = false } }).Verifiable(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); _fileSystemMock.Verify(); Assert.Empty(extras); } [Fact] public void FindExtras_SeriesWithTrailers_FindsCorrectExtras() { var owner = new Series { Name = "Dexter", Path = "/series/Dexter" }; var paths = new List<string> { "/series/Dexter/Season 1/S01E01.mkv", "/series/Dexter/trailer.mkv", "/series/Dexter/trailers/trailer2.mkv", }; var files = paths.Select(p => new FileSystemMetadata { FullName = p, IsDirectory = string.IsNullOrEmpty(Path.GetExtension(p)) }).ToList(); var extras = _libraryManager.FindExtras(owner, files, new DirectoryService(_fileSystemMock.Object)).OrderBy(e => e.ExtraType).ToList(); Assert.Equal(2, extras.Count); Assert.Equal(ExtraType.Trailer, extras[0].ExtraType); Assert.Equal(typeof(Trailer), extras[0].GetType()); Assert.Equal("trailer", extras[0].FileNameWithoutExtension); Assert.Equal("/series/Dexter/trailer.mkv", extras[0].Path); Assert.Equal("/series/Dexter/trailers/trailer2.mkv", extras[1].Path); } }
FindExtrasTests
csharp
louthy__language-ext
LanguageExt.Core/Class Instances/Eq/EqLong.cs
{ "start": 153, "end": 806 }
public struct ____ : Eq<long> { /// <summary> /// Equality test /// </summary> /// <param name="x">The left hand side of the equality operation</param> /// <param name="y">The right hand side of the equality operation</param> /// <returns>True if x and y are equal</returns> [Pure] public static bool Equals(long a, long b) => a == b; /// <summary> /// Get hash code of the value /// </summary> /// <param name="x">Value to get the hash code of</param> /// <returns>The hash code of x</returns> [Pure] public static int GetHashCode(long x) => HashableLong.GetHashCode(x); }
EqLong
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Media.Imaging/XamlRenderingBackgroundTask.cs
{ "start": 306, "end": 1568 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] protected XamlRenderingBackgroundTask() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Media.Imaging.XamlRenderingBackgroundTask", "XamlRenderingBackgroundTask.XamlRenderingBackgroundTask()"); } #endif // Forced skipping of method Microsoft.UI.Xaml.Media.Imaging.XamlRenderingBackgroundTask.XamlRenderingBackgroundTask() #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] protected virtual void OnRun(global::Windows.ApplicationModel.Background.IBackgroundTaskInstance taskInstance) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Media.Imaging.XamlRenderingBackgroundTask", "void XamlRenderingBackgroundTask.OnRun(IBackgroundTaskInstance taskInstance)"); } #endif } }
XamlRenderingBackgroundTask
csharp
unoplatform__uno
src/Uno.UI.Runtime.Skia.Linux.FrameBuffer/Native/LibInput.cs
{ "start": 430, "end": 4843 }
class ____ { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int OpenRestrictedCallbackDelegate(IntPtr path, int flags, IntPtr userData); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void CloseRestrictedCallbackDelegate(int fd, IntPtr userData); static int OpenRestricted(IntPtr path, int flags, IntPtr userData) { if (!(Marshal.PtrToStringAnsi(path) is { } pathAsString)) { return -1; } var fd = Libc.open(pathAsString, flags, 0); if (fd == -1) { return -Marshal.GetLastWin32Error(); } return fd; } static void CloseRestricted(int fd, IntPtr userData) #pragma warning disable CA1806 // Do not ignore method results => Libc.close(fd); #pragma warning restore CA1806 // Do not ignore method results private static readonly IntPtr* s_Interface; static LibInput() { s_Interface = (IntPtr*)Marshal.AllocHGlobal(IntPtr.Size * 2); static IntPtr Convert<TDelegate>(TDelegate del) where TDelegate : notnull { GCHandle.Alloc(del); return Marshal.GetFunctionPointerForDelegate(del); } s_Interface[0] = Convert<OpenRestrictedCallbackDelegate>(OpenRestricted); s_Interface[1] = Convert<CloseRestrictedCallbackDelegate>(CloseRestricted); } private const string LibInputName = "libinput.so.10"; [DllImport(LibInputName)] public extern static IntPtr libinput_path_create_context(IntPtr* iface, IntPtr userData); public static IntPtr libinput_path_create_context() => libinput_path_create_context(s_Interface, IntPtr.Zero); [DllImport(LibInputName)] public extern static IntPtr libinput_path_add_device(IntPtr ctx, [MarshalAs(UnmanagedType.LPStr)] string path); [DllImport(LibInputName)] public extern static IntPtr libinput_path_remove_device(IntPtr device); [DllImport(LibInputName)] public extern static int libinput_get_fd(IntPtr ctx); [DllImport(LibInputName)] public extern static void libinput_dispatch(IntPtr ctx); [DllImport(LibInputName)] public extern static IntPtr libinput_get_event(IntPtr ctx); [DllImport(LibInputName)] public extern static libinput_event_type libinput_event_get_type(IntPtr ev); [DllImport(LibInputName)] public extern static void libinput_event_destroy(IntPtr ev); [DllImport(LibInputName)] public extern static IntPtr libinput_event_get_touch_event(IntPtr ev); [DllImport(LibInputName)] public extern static int libinput_event_touch_get_slot(IntPtr ev); [DllImport(LibInputName)] public extern static ulong libinput_event_touch_get_time_usec(IntPtr ev); [DllImport(LibInputName)] public extern static double libinput_event_touch_get_x_transformed(IntPtr ev, int width); [DllImport(LibInputName)] public extern static double libinput_event_touch_get_y_transformed(IntPtr ev, int height); [DllImport(LibInputName)] public extern static IntPtr libinput_event_get_pointer_event(IntPtr ev); [DllImport(LibInputName)] public extern static ulong libinput_event_pointer_get_time_usec(IntPtr ev); [DllImport(LibInputName)] public extern static double libinput_event_pointer_get_absolute_x_transformed(IntPtr ev, int width); [DllImport(LibInputName)] public extern static double libinput_event_pointer_get_absolute_y_transformed(IntPtr ev, int height); [DllImport(LibInputName)] public extern static libinput_event_code libinput_event_pointer_get_button(IntPtr ev); [DllImport(LibInputName)] public extern static libinput_button_state libinput_event_pointer_get_button_state(IntPtr ev); [DllImport(LibInputName)] public extern static int libinput_event_pointer_has_axis(IntPtr ev, libinput_pointer_axis axis); [DllImport(LibInputName)] public extern static double libinput_event_pointer_get_axis_value(IntPtr ev, libinput_pointer_axis axis); [DllImport(LibInputName)] public extern static libinput_pointer_axis_source libinput_event_pointer_get_axis_source(IntPtr ev); [DllImport(LibInputName)] public extern static double libinput_event_pointer_get_axis_value_discrete(IntPtr ev, libinput_pointer_axis axis); [DllImport(LibInputName)] public extern static IntPtr libinput_event_get_keyboard_event(IntPtr ev); [DllImport(LibInputName)] public extern static libinput_key libinput_event_keyboard_get_key(IntPtr ev); [DllImport(LibInputName)] public extern static libinput_key_state libinput_event_keyboard_get_key_state(IntPtr ev); } }
LibInput
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.Testing/Storage/FileHandle.cs
{ "start": 2211, "end": 2756 }
private sealed class ____ : IStorageAccessHandle { #region IStorageAccessHandle Members /// <inheritdoc cref="IStorageAccessHandle.Access" /> public FileAccess Access => FileAccess.ReadWrite; /// <inheritdoc cref="IStorageAccessHandle.DeleteAccess" /> public bool DeleteAccess => false; /// <inheritdoc cref="IStorageAccessHandle.Share" /> public FileShare Share => FileShare.ReadWrite; /// <inheritdoc cref="IDisposable.Dispose()" /> public void Dispose() { // Do nothing } #endregion } }
IgnoreFileHandle
csharp
xunit__xunit
src/xunit.v2.tests/Acceptance/Xunit2TheoryAcceptanceTests.cs
{ "start": 21228, "end": 21261 }
enum ____ { A, B }
SomeEnum
csharp
dotnetcore__CAP
src/DotNetCore.CAP.AmazonSQS/CAP.AmazonSQSOptionsExtension.cs
{ "start": 352, "end": 945 }
internal sealed class ____ : ICapOptionsExtension { private readonly Action<AmazonSQSOptions> _configure; public AmazonSQSOptionsExtension(Action<AmazonSQSOptions> configure) { _configure = configure; } public void AddServices(IServiceCollection services) { services.AddSingleton(new CapMessageQueueMakerService("Amazon SQS")); services.Configure(_configure); services.AddSingleton<ITransport, AmazonSQSTransport>(); services.AddSingleton<IConsumerClientFactory, AmazonSQSConsumerClientFactory>(); } }
AmazonSQSOptionsExtension
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Controls/When_xBind_With_Cast.xaml.cs
{ "start": 714, "end": 828 }
partial class ____ : Page { public When_xBind_With_Cast() { this.InitializeComponent(); } }
When_xBind_With_Cast
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Controllers/SalesEmployeeController.cs
{ "start": 554, "end": 3979 }
public class ____ : BaseAdminController { #region Constructors public SalesEmployeeController( ISalesEmployeeService salesEmployeeService, ICustomerService customerService, IOrderService orderService, IDocumentService documentService ) { _salesEmployeeService = salesEmployeeService; _customerService = customerService; _orderService = orderService; _documentService = documentService; } #endregion [PermissionAuthorizeAction(PermissionActionName.List)] public IActionResult Index() { return View(); } [HttpPost] [PermissionAuthorizeAction(PermissionActionName.List)] public async Task<IActionResult> List(DataSourceRequest command) { var weightsModel = (await _salesEmployeeService.GetAll()) .Select(x => x.ToModel()) .ToList(); var gridModel = new DataSourceResult { Data = weightsModel, Total = weightsModel.Count }; return Json(gridModel); } [HttpPost] [PermissionAuthorizeAction(PermissionActionName.Edit)] public async Task<IActionResult> Update(SalesEmployeeModel model) { if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() }); var salesemployee = await _salesEmployeeService.GetSalesEmployeeById(model.Id); salesemployee = model.ToEntity(salesemployee); await _salesEmployeeService.UpdateSalesEmployee(salesemployee); return new JsonResult(""); } [HttpPost] [PermissionAuthorizeAction(PermissionActionName.Create)] public async Task<IActionResult> Add(SalesEmployeeModel model) { if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() }); var salesEmployee = new SalesEmployee(); salesEmployee = model.ToEntity(salesEmployee); await _salesEmployeeService.InsertSalesEmployee(salesEmployee); return new JsonResult(""); } [HttpPost] [PermissionAuthorizeAction(PermissionActionName.Delete)] public async Task<IActionResult> Delete(string id) { var salesemployee = await _salesEmployeeService.GetSalesEmployeeById(id); if (salesemployee == null) throw new ArgumentException("No sales employee found with the specified id"); var customers = await _customerService.GetAllCustomers(salesEmployeeId: id); if (customers.Any()) return Json(new DataSourceResult { Errors = "Sales employee is related with customers" }); var orders = await _orderService.SearchOrders(salesEmployeeId: id); if (orders.Any()) return Json(new DataSourceResult { Errors = "Sales employee is related with orders" }); var documents = await _documentService.GetAll(seId: id); if (documents.Any()) return Json(new DataSourceResult { Errors = "Sales employee is related with documents" }); await _salesEmployeeService.DeleteSalesEmployee(salesemployee); return new JsonResult(""); } #region Fields private readonly ISalesEmployeeService _salesEmployeeService; private readonly ICustomerService _customerService; private readonly IOrderService _orderService; private readonly IDocumentService _documentService; #endregion }
SalesEmployeeController
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Attributes/BinaryVectorAttributeTests.cs
{ "start": 7332, "end": 7603 }
public class ____ { public BinaryVectorInt8 ValuesInt8 { get; set; } public BinaryVectorPackedBit ValuesPackedBit { get; set; } public BinaryVectorFloat32 ValuesFloat { get; set; } }
BinaryVectorNoAttributeHolder
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.System.RemoteDesktop/InteractiveSession.cs
{ "start": 316, "end": 976 }
partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static bool IsRemote { get { throw new global::System.NotImplementedException("The member bool InteractiveSession.IsRemote is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20InteractiveSession.IsRemote"); } } #endif // Forced skipping of method Windows.System.RemoteDesktop.InteractiveSession.IsRemote.get } }
InteractiveSession
csharp
dotnet__maui
src/Controls/src/Build.Tasks/CompiledConverters/ConstraintTypeConverter.cs
{ "start": 285, "end": 1111 }
class ____ : ICompiledTypeConverter { public IEnumerable<Instruction> ConvertFromString(string value, ILContext context, BaseNode node) { var module = context.Body.Method.Module; double size; if (string.IsNullOrEmpty(value) || !double.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out size)) throw new BuildException(BuildExceptionCode.Conversion, node, null, value, typeof(Compatibility.Constraint)); yield return Create(Ldc_R8, size); yield return Create(Call, module.ImportMethodReference(context.Cache, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Compatibility", "Constraint"), methodName: "Constant", parameterTypes: new[] { ("mscorlib", "System", "Double") }, isStatic: true)); } } }
ConstraintTypeConverter
csharp
dotnet__orleans
src/Orleans.Core/Timers/TimerManager.cs
{ "start": 9137, "end": 9711 }
private sealed class ____ : ILinkedList<T> { public readonly RecursiveInterlockedExchangeLock Lock = new RecursiveInterlockedExchangeLock(); /// <summary> /// The number of times that this queue has been starved since it was last serviced. /// </summary> public int StarvationCount; public T Head { get; set; } public T Tail { get; set; } } /// <summary> /// Holds timers that have expired and should be fired. /// </summary>
ThreadLocalQueue
csharp
dotnet__maui
src/Compatibility/Core/src/Android/Flags.cs
{ "start": 51, "end": 153 }
internal static class ____ { internal const string UseLegacyRenderers = "UseLegacyRenderers"; } }
Flags