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/SchemaRegistry/KurrentDB.SchemaRegistry.Tests/Wait.cs
|
{
"start": 225,
"end": 1942
}
|
static class ____ {
static readonly TimeSpan DefaultDelay = TimeSpan.FromMilliseconds(100);
static readonly Action? DefaultOnTimeout = () => throw new TimeoutException();
static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
public static Task Until(Func<Task<bool>> predicate, TimeSpan? delay = null, TimeSpan? timeout = null, Action? onTimeout = null, CancellationToken cancellationToken = default) {
onTimeout ??= DefaultOnTimeout;
return Task.Run(
async () => {
bool satisfied;
do {
satisfied = await predicate();
if (!satisfied)
await Task.Delay(delay.GetValueOrDefault(DefaultDelay), cancellationToken);
} while (!satisfied);
},
cancellationToken
).WithTimeout(timeout.GetValueOrDefault(DefaultTimeout), onTimeout, cancellationToken);
}
public static async Task UntilAsserted(Func<Task> assertion, TimeSpan? delay = null, TimeSpan? timeout = null, Action? onTimeout = null, CancellationToken cancellationToken = default) {
Exception? lastException = null;
await Until(
async () => {
lastException = null;
try {
await assertion();
}
catch (Exception ex) {
lastException = ex;
}
return lastException == null;
},
delay,
timeout,
() => {
onTimeout?.Invoke();
throw lastException!;
},
cancellationToken
);
}
}
|
Wait
|
csharp
|
dotnet__aspnetcore
|
src/Mvc/test/Mvc.FunctionalTests/ApiExplorerTest.cs
|
{
"start": 67388,
"end": 67538
}
|
private class ____
{
public string MediaType { get; set; }
public string FormatterType { get; set; }
}
}
|
ApiExplorerRequestFormat
|
csharp
|
CommunityToolkit__dotnet
|
tests/CommunityToolkit.Mvvm.SourceGenerators.Roslyn4001.UnitTests/Test_UnsupportedRoslynVersionForPartialPropertyAnalyzer.cs
|
{
"start": 397,
"end": 733
}
|
public class ____
{
[TestMethod]
public async Task UnsupportedRoslynVersionForPartialPropertyAnalyzer_Warns()
{
const string source = """
using CommunityToolkit.Mvvm.ComponentModel;
namespace MyApp
{
|
Test_UnsupportedRoslynVersionForPartialPropertyAnalyzer
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit/DependencyInjection/Configuration/DependencyInjectionActivityRegistrationExtensions.cs
|
{
"start": 5473,
"end": 5638
}
|
interface ____
{
IActivityRegistration Register(IServiceCollection collection, IContainerRegistrar registrar);
}
|
IActivityRegistrar
|
csharp
|
AvaloniaUI__Avalonia
|
tests/Avalonia.Base.UnitTests/AvaloniaObjectTests_Coercion.cs
|
{
"start": 13619,
"end": 14380
}
|
private class ____ : Control
{
public static readonly StyledProperty<int> FooProperty =
AvaloniaProperty.Register<Control1, int>(
"Foo",
defaultValue: 11,
coerce: CoerceFoo);
public int Foo
{
get => GetValue(FooProperty);
set => SetValue(FooProperty, value);
}
public int MinFoo { get; set; } = 0;
public int MaxFoo { get; set; } = 100;
public static int CoerceFoo(AvaloniaObject instance, int value)
{
var o = (Control1)instance;
return Math.Clamp(value, o.MinFoo, o.MaxFoo);
}
}
}
}
|
Control1
|
csharp
|
dotnet__maui
|
src/Controls/src/Core/Compatibility/Handlers/Shell/Android/ShellToolbarTracker.cs
|
{
"start": 22413,
"end": 24255
}
|
class ____ : DrawerArrowDrawable
{
public Drawable IconBitmap { get; set; }
public string Text { get; set; }
public Color TintColor { get; set; }
public ImageSource IconBitmapSource { get; set; }
float _defaultSize;
Color _pressedBackgroundColor => TintColor.AddLuminosity(-.12f);//<item name="highlight_alpha_material_light" format="float" type="dimen">0.12</item>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && IconBitmap != null)
{
IconBitmap.Dispose();
}
}
public FlyoutIconDrawerDrawable(Context context, Color defaultColor, Drawable icon, string text) : base(context)
{
TintColor = defaultColor;
if (context.TryResolveAttribute(AndroidResource.Attribute.TextSize, out float? value) &&
value != null)
{
_defaultSize = value.Value;
}
else
{
_defaultSize = 50;
}
IconBitmap = icon;
Text = text;
}
public override void Draw(Canvas canvas)
{
bool pressed = false;
if (IconBitmap != null)
{
ADrawableCompat.SetTint(IconBitmap, TintColor.ToPlatform());
ADrawableCompat.SetTintMode(IconBitmap, PorterDuff.Mode.SrcAtop);
IconBitmap.SetBounds(Bounds.Left, Bounds.Top, Bounds.Right, Bounds.Bottom);
IconBitmap.Draw(canvas);
}
else if (!string.IsNullOrEmpty(Text))
{
var paint = new Paint { AntiAlias = true };
paint.TextSize = _defaultSize;
#pragma warning disable CA1416 // https://github.com/xamarin/xamarin-android/issues/6962
paint.Color = pressed ? _pressedBackgroundColor.ToPlatform() : TintColor.ToPlatform();
#pragma warning restore CA1416
paint.SetStyle(Paint.Style.Fill);
var y = (Bounds.Height() + paint.TextSize) / 2;
canvas.DrawText(Text, 0, y, paint);
}
}
}
}
}
|
FlyoutIconDrawerDrawable
|
csharp
|
MapsterMapper__Mapster
|
src/Mapster.Tests/WhenUsingDestinationValue.cs
|
{
"start": 1992,
"end": 2368
}
|
public class ____
{
public long Id { get; set; }
public string DocumentNumber { get; set; }
public string SupplierName { get; set; }
public string SupplierCompany { get; set; }
public IEnumerable<int> Numbers { get; set; }
public ICollection<string> Strings { get; set; }
}
}
}
|
InvoiceDto
|
csharp
|
unoplatform__uno
|
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Geolocation/VisitStateChange.cs
|
{
"start": 265,
"end": 825
}
|
public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
TrackingLost = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Arrived = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Departed = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
OtherMovement = 3,
#endif
}
#endif
}
|
VisitStateChange
|
csharp
|
dotnet__maui
|
src/Essentials/src/SecureStorage/SecureStorage.shared.cs
|
{
"start": 201,
"end": 1318
}
|
public interface ____
{
/// <summary>
/// Gets and decrypts the value for a given key.
/// </summary>
/// <param name="key">The key to retrieve the value for.</param>
/// <returns>The decrypted string value or <see langword="null"/> if a value was not found.</returns>
Task<string?> GetAsync(string key);
/// <summary>
/// Sets and encrypts a value for a given key.
/// </summary>
/// <param name="key">The key to set the value for.</param>
/// <param name="value">Value to set.</param>
/// <returns>A <see cref="Task"/> object with the current status of the asynchronous operation.</returns>
Task SetAsync(string key, string value);
/// <summary>
/// Removes a key and its associated value if it exists.
/// </summary>
/// <param name="key">The key to remove.</param>
bool Remove(string key);
/// <summary>
/// Removes all of the stored encrypted key/value pairs.
/// </summary>
void RemoveAll();
}
/// <summary>
/// Provides abstractions for the platform specific secure storage functionality for use with <see cref="ISecureStorage"/>.
/// </summary>
|
ISecureStorage
|
csharp
|
MaterialDesignInXAML__MaterialDesignInXamlToolkit
|
src/MaterialDesignThemes.Wpf/ExpanderAssist.cs
|
{
"start": 139,
"end": 4018
}
|
public static class ____
{
private static readonly Thickness DefaultHorizontalHeaderPadding = new(24, 12, 24, 12);
private static readonly Thickness DefaultVerticalHeaderPadding = new(12, 24, 12, 24);
#region AttachedProperty : HorizontalHeaderPaddingProperty
public static readonly DependencyProperty HorizontalHeaderPaddingProperty
= DependencyProperty.RegisterAttached("HorizontalHeaderPadding", typeof(Thickness), typeof(ExpanderAssist),
new FrameworkPropertyMetadata(DefaultHorizontalHeaderPadding, FrameworkPropertyMetadataOptions.Inherits));
public static Thickness GetHorizontalHeaderPadding(Expander element)
=> (Thickness)element.GetValue(HorizontalHeaderPaddingProperty);
public static void SetHorizontalHeaderPadding(Expander element, Thickness value)
=> element.SetValue(HorizontalHeaderPaddingProperty, value);
#endregion
#region AttachedProperty : VerticalHeaderPaddingProperty
public static readonly DependencyProperty VerticalHeaderPaddingProperty
= DependencyProperty.RegisterAttached("VerticalHeaderPadding", typeof(Thickness), typeof(ExpanderAssist),
new FrameworkPropertyMetadata(DefaultVerticalHeaderPadding, FrameworkPropertyMetadataOptions.Inherits));
public static Thickness GetVerticalHeaderPadding(Expander element)
=> (Thickness)element.GetValue(VerticalHeaderPaddingProperty);
public static void SetVerticalHeaderPadding(Expander element, Thickness value)
=> element.SetValue(VerticalHeaderPaddingProperty, value);
#endregion
#region AttachedProperty : HeaderFontSizeProperty
public static readonly DependencyProperty HeaderFontSizeProperty
= DependencyProperty.RegisterAttached("HeaderFontSize", typeof(double), typeof(ExpanderAssist),
new FrameworkPropertyMetadata(15.0));
public static double GetHeaderFontSize(Expander element)
=> (double)element.GetValue(HeaderFontSizeProperty);
public static void SetHeaderFontSize(Expander element, double value)
=> element.SetValue(HeaderFontSizeProperty, value);
#endregion
#region AttachedProperty : HeaderBackgroundProperty
public static readonly DependencyProperty HeaderBackgroundProperty
= DependencyProperty.RegisterAttached("HeaderBackground", typeof(Brush), typeof(ExpanderAssist));
public static Brush? GetHeaderBackground(Expander element)
=> (Brush?)element.GetValue(HeaderBackgroundProperty);
public static void SetHeaderBackground(Expander element, Brush? value)
=> element.SetValue(HeaderBackgroundProperty, value);
#endregion
#region AttachedProperty : ExpanderButtonContentProperty
public static readonly DependencyProperty ExpanderButtonContentProperty
= DependencyProperty.RegisterAttached("ExpanderButtonContent", typeof(object), typeof(ExpanderAssist));
public static object? GetExpanderButtonContent(Expander element)
=> (object?)element.GetValue(ExpanderButtonContentProperty);
public static void SetExpanderButtonContent(Expander element, object? value)
=> element.SetValue(ExpanderButtonContentProperty, value);
#endregion
#region AttachedProperty : ExpanderButtonPositionProperty
public static readonly DependencyProperty ExpanderButtonPositionProperty
= DependencyProperty.RegisterAttached("ExpanderButtonPosition", typeof(ExpanderButtonPosition), typeof(ExpanderAssist), new PropertyMetadata(ExpanderButtonPosition.Default));
public static ExpanderButtonPosition GetExpanderButtonPosition(Expander element)
=> (ExpanderButtonPosition)element.GetValue(ExpanderButtonPositionProperty);
public static void SetExpanderButtonPosition(Expander element, ExpanderButtonPosition value)
=> element.SetValue(ExpanderButtonPositionProperty, value);
#endregion
}
|
ExpanderAssist
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Core/src/Types.Abstractions/Types/TypeComparison.cs
|
{
"start": 100,
"end": 316
}
|
public enum ____
{
/// <summary>
/// Compare types by reference.
/// </summary>
Reference = 0,
/// <summary>
/// Compare types structurally.
/// </summary>
Structural = 1
}
|
TypeComparison
|
csharp
|
nuke-build__nuke
|
source/Nuke.GlobalTool/Rewriting/Cake/TargetDefinitionRewriter.cs
|
{
"start": 405,
"end": 4354
}
|
internal class ____ : SafeSyntaxRewriter
{
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
node = (InvocationExpressionSyntax) base.VisitInvocationExpression(node).NotNull();
if (node.Expression is IdentifierNameSyntax identifierName &&
identifierName.Identifier.Text == "Task")
{
return SimpleLambdaExpression(Parameter(Identifier("_")))
.WithExpressionBody(IdentifierName("_"));
}
var memberAccessExpression = node.Expression as MemberAccessExpressionSyntax;
// if (memberAccessExpression?.GetIdentifierName() == "IsDependentOn" ||
// memberAccessExpression?.GetIdentifierName() == "IsDependeeOf")
// {
// node = node.WithExpression(memberAccessExpression
// .WithName(IdentifierName(memberAccessExpression.GetIdentifierName()
// .Replace("IsDependentOn", nameof(ITargetDefinition.DependsOn))
// .Replace("IsDependeeOf", nameof(ITargetDefinition.DependentFor)))));
//
// node = node.WithConvertedArguments(x =>
// {
// var literalExpression = x as LiteralExpressionSyntax;
// var targetName = literalExpression.GetConstantValue<string>();
// return IdentifierName(targetName);
// });
// }
//
// if (memberAccessExpression?.GetIdentifierName() == "WithCriteria")
// {
// node = node.WithExpression(memberAccessExpression
// .WithName(IdentifierName(
// node.GetSingleArgument<LambdaExpressionSyntax>() == null
// ? nameof(ITargetDefinition.OnlyWhenStatic)
// : nameof(ITargetDefinition.OnlyWhenDynamic))));
//
// if (node.GetSingleArgument<LambdaExpressionSyntax>() == null)
// node = node.WithConvertedArguments(ParenthesizedLambdaExpression);
// }
// if (memberAccessExpression?.GetIdentifierName() == "Does")
// {
// node = node.WithExpression(memberAccessExpression
// .WithName(IdentifierName("Executes")));
//
// node = node.WithConvertedArguments(x =>
// {
// var lambdaExpression = (LambdaExpressionSyntax) x;
// return lambdaExpression.Block != null
// ? lambdaExpression
// : lambdaExpression
// .WithExpressionBody(null)
// .WithBlock(Block(ExpressionStatement(lambdaExpression.ExpressionBody.NotNull())));
// });
// }
return node;
}
public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
{
var reducedNode = (GlobalStatementSyntax) base.VisitGlobalStatement(node).NotNull();
if (node.Statement is not ExpressionStatementSyntax expressionStatement)
return reducedNode;
var innerInvocationExpression = (expressionStatement.Expression as InvocationExpressionSyntax)
.Descendants(x => (x.Expression as MemberAccessExpressionSyntax)?.Expression as InvocationExpressionSyntax)
.LastOrDefault();
if (innerInvocationExpression?.GetIdentifierName() == "Task")
{
var name = innerInvocationExpression.GetSingleArgument<LiteralExpressionSyntax>()
.GetConstantValue<string>()
.Replace("-", "_");
var expression = ((ExpressionStatementSyntax) reducedNode.Statement).Expression;
return PropertyDeclaration(ParseTypeName(nameof(Target)), name)
.WithExpressionBody(ArrowExpressionClause(expression))
.WithSemicolonToken(expressionStatement.SemicolonToken);
}
return reducedNode;
}
}
|
TargetDefinitionRewriter
|
csharp
|
dotnet__aspnetcore
|
src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerSuppressDiagnosticsContext.cs
|
{
"start": 320,
"end": 373
}
|
record ____ for an exception.
/// </summary>
|
diagnostics
|
csharp
|
dotnet__orleans
|
test/NonSilo.Tests/ClientBuilderTests.cs
|
{
"start": 428,
"end": 1292
}
|
public class ____ : IGatewayListProvider
{
public TimeSpan MaxStaleness => throw new NotImplementedException();
public bool IsUpdatable => throw new NotImplementedException();
public Task<IList<Uri>> GetGateways()
{
throw new NotImplementedException();
}
public Task InitializeGatewayListProvider()
{
throw new NotImplementedException();
}
}
/// <summary>
/// Tests for the Orleans ClientBuilder, which is responsible for configuring and building Orleans client instances.
/// These tests verify client configuration validation, service registration, and proper initialization of client components
/// without requiring a full Orleans cluster.
/// </summary>
[TestCategory("BVT")]
[TestCategory("ClientBuilder")]
|
NoOpGatewaylistProvider
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/OrmLiteComplexTypesTests.cs
|
{
"start": 281,
"end": 3994
}
|
public class ____(DialectContext context) : OrmLiteProvidersTestBase(context)
{
[Test]
public void Can_insert_into_ModelWithComplexTypes_table()
{
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithComplexTypes>(true);
var row = ModelWithComplexTypes.Create(1);
db.Insert(row);
}
}
[Test]
public void Can_insert_and_select_from_ModelWithComplexTypes_table()
{
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithComplexTypes>(true);
var row = ModelWithComplexTypes.Create(1);
db.Insert(row);
var rows = db.Select<ModelWithComplexTypes>();
Assert.That(rows, Has.Count.EqualTo(1));
ModelWithComplexTypes.AssertIsEqual(rows[0], row);
}
}
[Test]
public void Can_insert_and_select_from_OrderLineData()
{
using (var db = OpenDbConnection())
{
db.CreateTable<SampleOrderLine>(true);
var orderIds = new[] { 1, 2, 3, 4, 5 }.ToList();
orderIds.ForEach(x => db.Insert(
SampleOrderLine.Create(Guid.NewGuid(), x, 1)));
var rows = db.Select<SampleOrderLine>();
Assert.That(rows, Has.Count.EqualTo(orderIds.Count));
}
}
[Test]
public void Lists_Of_Guids_Are_Formatted_Correctly()
{
LogManager.LogFactory = new ConsoleLogFactory();
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<WithAListOfGuids>();
JsConfig<Guid>.RawSerializeFn = x => x.ToString();
var item = new WithAListOfGuids
{
GuidOne = new Guid("32cb0acb-db43-4061-a6aa-7f4902a7002a"),
GuidTwo = new Guid("13083231-b005-4ff4-ab62-41bdc7f50a4d"),
TheGuids = new[] { new Guid("18176030-7a1c-4288-82df-a52f71832381"), new Guid("017f986b-f7be-4b6f-b978-ff05fba3b0aa") },
};
db.Insert(item);
var tbl = "WithAListOfGuids".SqlTable(DialectProvider);
var savedGuidOne = db.Select<Guid>("SELECT {0} FROM {1}".Fmt("GuidOne".SqlColumn(DialectProvider), tbl)).First();
Assert.That(savedGuidOne, Is.EqualTo(new Guid("32cb0acb-db43-4061-a6aa-7f4902a7002a")));
var savedGuidTwo = db.Select<Guid>("SELECT {0} FROM {1}".Fmt("GuidTwo".SqlColumn(DialectProvider), tbl)).First();
Assert.That(savedGuidTwo, Is.EqualTo(new Guid("13083231-b005-4ff4-ab62-41bdc7f50a4d")));
var savedGuidList = db.Select<string>("SELECT {0} FROM {1}".Fmt("TheGuids".SqlColumn(DialectProvider), tbl)).First();
Assert.That(savedGuidList, Is.EqualTo("[18176030-7a1c-4288-82df-a52f71832381,017f986b-f7be-4b6f-b978-ff05fba3b0aa]"));
JsConfig.Reset();
}
}
[Test]
public void Can_insert_Contact_with_Complex_NameDetail()
{
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<Contact>();
var contact = new Contact
{
FullName = new NameDetail("Sinéad", "O'Connor"),
Email = "Sinéad@O'Connor.com",
Age = 10
};
db.Save(contact);
var dbContact = db.Single<Contact>(q => q.Email == contact.Email);
Assert.That(dbContact.Email, Is.EqualTo(contact.Email));
Assert.That(dbContact.Age, Is.EqualTo(contact.Age));
Assert.That(dbContact.FullName.First, Is.EqualTo(contact.FullName.First));
Assert.That(dbContact.FullName.Last, Is.EqualTo(contact.FullName.Last));
}
}
}
|
OrmLiteComplexTypesTests
|
csharp
|
dotnetcore__Util
|
src/Util.Ui.NgZorro/Enums/DividerType.cs
|
{
"start": 75,
"end": 293
}
|
public enum ____ {
/// <summary>
/// 水平
/// </summary>
[Description( "horizontal" )]
Horizontal,
/// <summary>
/// 垂直
/// </summary>
[Description( "vertical" )]
Vertical
}
|
DividerType
|
csharp
|
icsharpcode__ILSpy
|
ICSharpCode.Decompiler/CSharp/Resolver/CSharpOperators.cs
|
{
"start": 1476,
"end": 2290
}
|
sealed class ____
{
readonly ICompilation compilation;
private CSharpOperators(ICompilation compilation)
{
this.compilation = compilation;
InitParameterArrays();
}
/// <summary>
/// Gets the CSharpOperators instance for the specified <see cref="ICompilation"/>.
/// This will make use of the context's cache manager (if available) to reuse the CSharpOperators instance.
/// </summary>
public static CSharpOperators Get(ICompilation compilation)
{
CacheManager cache = compilation.CacheManager;
CSharpOperators? operators = (CSharpOperators?)cache.GetShared(typeof(CSharpOperators));
if (operators == null)
{
operators = (CSharpOperators)cache.GetOrAddShared(typeof(CSharpOperators), new CSharpOperators(compilation));
}
return operators;
}
#region
|
CSharpOperators
|
csharp
|
dotnet__aspire
|
src/Aspire.Cli/Utils/ConsoleActivityLogger.cs
|
{
"start": 2572,
"end": 12307
}
|
public enum ____
{
InProgress,
Success,
Warning,
Failure,
Info
}
public void StartTask(string taskKey, string? startingMessage = null)
{
lock (_lock)
{
// Initialize step state as InProgress if first time seen
if (!_stepStates.ContainsKey(taskKey))
{
_stepStates[taskKey] = ActivityState.InProgress;
}
}
WriteLine(taskKey, InProgressSymbol, startingMessage ?? "Starting...", ActivityState.InProgress);
}
public void StartTask(string taskKey, string displayName, string? startingMessage = null)
{
lock (_lock)
{
if (!_stepStates.ContainsKey(taskKey))
{
_stepStates[taskKey] = ActivityState.InProgress;
}
_displayNames[taskKey] = displayName;
}
WriteLine(taskKey, InProgressSymbol, startingMessage ?? ($"Starting {displayName}..."), ActivityState.InProgress);
}
public void StartSpinner()
{
// Skip spinner in non-interactive environments
if (!_hostEnvironment.SupportsInteractiveOutput || _spinning)
{
return;
}
_spinning = true;
_spinnerTask = Task.Run(async () =>
{
AnsiConsole.Cursor.Hide();
try
{
while (_spinning)
{
var spinChar = _spinnerChars[_spinnerIndex % _spinnerChars.Length];
// Write then move back so nothing can write between these events (hopefully)
AnsiConsole.Write(CultureInfo.InvariantCulture, spinChar);
AnsiConsole.Cursor.MoveLeft();
_spinnerIndex++;
await Task.Delay(120).ConfigureAwait(false);
}
}
finally
{
// Clear spinner character
AnsiConsole.Write(CultureInfo.InvariantCulture, ' ');
AnsiConsole.Cursor.MoveLeft();
AnsiConsole.Cursor.Show();
}
});
}
public async Task StopSpinnerAsync()
{
_spinning = false;
if (_spinnerTask is not null)
{
await _spinnerTask.ConfigureAwait(false);
_spinnerTask = null;
}
}
public void Progress(string taskKey, string message)
{
WriteLine(taskKey, InProgressSymbol, message, ActivityState.InProgress);
}
public void Success(string taskKey, string message, double? seconds = null)
{
lock (_lock)
{
_successCount++;
_stepStates[taskKey] = ActivityState.Success;
}
WriteCompletion(taskKey, SuccessSymbol, message, ActivityState.Success, seconds);
}
public void Warning(string taskKey, string message, double? seconds = null)
{
lock (_lock)
{
_warningCount++;
_stepStates[taskKey] = ActivityState.Warning;
}
WriteCompletion(taskKey, WarningSymbol, message, ActivityState.Warning, seconds);
}
public void Failure(string taskKey, string message, double? seconds = null)
{
lock (_lock)
{
_failureCount++;
_stepStates[taskKey] = ActivityState.Failure;
}
WriteCompletion(taskKey, FailureSymbol, message, ActivityState.Failure, seconds);
}
public void Info(string taskKey, string message)
{
WriteLine(taskKey, InfoSymbol, message, ActivityState.Info);
}
public void Continuation(string message)
{
lock (_lock)
{
// Continuation lines: indent with two spaces relative to the symbol column for readability
const string continuationPrefix = " ";
foreach (var line in SplitLinesPreserve(message))
{
Console.Write(continuationPrefix);
Console.WriteLine(line);
}
}
}
public void WriteSummary()
{
lock (_lock)
{
var totalSeconds = _stopwatch.Elapsed.TotalSeconds;
var line = new string('-', 60);
AnsiConsole.MarkupLine(line);
var totalSteps = _stepStates.Count;
// Derive per-step outcome counts from _stepStates (not task-level counters) for accurate X/Y display.
var succeededSteps = _stepStates.Values.Count(v => v == ActivityState.Success);
var warningSteps = _stepStates.Values.Count(v => v == ActivityState.Warning);
var failedSteps = _stepStates.Values.Count(v => v == ActivityState.Failure);
var summaryParts = new List<string>();
var succeededSegment = totalSteps > 0 ? $"{succeededSteps}/{totalSteps} steps succeeded" : $"{succeededSteps} steps succeeded";
if (_enableColor)
{
summaryParts.Add($"[green]{SuccessSymbol} {succeededSegment}[/]");
if (warningSteps > 0)
{
summaryParts.Add($"[yellow]{WarningSymbol} {warningSteps} warning{(warningSteps == 1 ? string.Empty : "s")}[/]");
}
if (failedSteps > 0)
{
summaryParts.Add($"[red]{FailureSymbol} {failedSteps} failed[/]");
}
}
else
{
summaryParts.Add($"{SuccessSymbol} {succeededSegment}");
if (warningSteps > 0)
{
summaryParts.Add($"{WarningSymbol} {warningSteps} warning{(warningSteps == 1 ? string.Empty : "s")}");
}
if (failedSteps > 0)
{
summaryParts.Add($"{FailureSymbol} {failedSteps} failed");
}
}
summaryParts.Add($"Total time: {totalSeconds.ToString("0.0", CultureInfo.InvariantCulture)}s");
AnsiConsole.MarkupLine(string.Join(" • ", summaryParts));
if (_durationRecords is { Count: > 0 })
{
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("Steps Summary:");
foreach (var rec in _durationRecords)
{
var durStr = rec.Duration.TotalSeconds.ToString("0.0", CultureInfo.InvariantCulture).PadLeft(4);
var symbol = rec.State switch
{
ActivityState.Success => _enableColor ? "[green]" + SuccessSymbol + "[/]" : SuccessSymbol,
ActivityState.Warning => _enableColor ? "[yellow]" + WarningSymbol + "[/]" : WarningSymbol,
ActivityState.Failure => _enableColor ? "[red]" + FailureSymbol + "[/]" : FailureSymbol,
_ => _enableColor ? "[cyan]" + InProgressSymbol + "[/]" : InProgressSymbol
};
var name = rec.DisplayName.EscapeMarkup();
var reason = rec.State == ActivityState.Failure && !string.IsNullOrEmpty(rec.FailureReason)
? ( _enableColor ? $" [red]— {HighlightMessage(rec.FailureReason!)}[/]" : $" — {rec.FailureReason}" )
: string.Empty;
var lineSb = new StringBuilder();
lineSb.Append(" ")
.Append(durStr).Append(" s ")
.Append(symbol).Append(' ')
.Append("[dim]").Append(name).Append("[/]")
.Append(reason);
AnsiConsole.MarkupLine(lineSb.ToString());
}
AnsiConsole.WriteLine();
}
// If a caller provided a final status line via SetFinalResult, print it now
if (!string.IsNullOrEmpty(_finalStatusHeader))
{
AnsiConsole.MarkupLine(_finalStatusHeader!);
// If pipeline failed and not already in debug/trace mode, show help message about using --log-level debug
if (!_pipelineSucceeded && !_isDebugOrTraceLoggingEnabled)
{
var helpMessage = _enableColor
? "[dim]For more details, add --log-level debug/trace to the command.[/]"
: "For more details, add --log-level debug/trace to the command.";
AnsiConsole.MarkupLine(helpMessage);
}
}
AnsiConsole.MarkupLine(line);
AnsiConsole.WriteLine(); // Ensure final newline after deployment summary
}
}
/// <summary>
/// Sets the final deployment result lines to be displayed in the summary (e.g., DEPLOYMENT FAILED ...).
/// Optional usage so existing callers remain compatible.
/// </summary>
public void SetFinalResult(bool succeeded)
{
_pipelineSucceeded = succeeded;
// Always show only a single final header line with symbol; no per-step duplication.
if (succeeded)
{
_finalStatusHeader = _enableColor
? $"[green]{SuccessSymbol} PIPELINE SUCCEEDED[/]"
: $"{SuccessSymbol} PIPELINE SUCCEEDED";
}
else
{
_finalStatusHeader = _enableColor
? $"[red]{FailureSymbol} PIPELINE FAILED[/]"
: $"{FailureSymbol} PIPELINE FAILED";
}
}
/// <summary>
/// Provides per-step duration data (already sorted) for inclusion in the summary.
/// </summary>
public void SetStepDurations(IEnumerable<StepDurationRecord> records)
{
_durationRecords = records.ToList();
}
public readonly
|
ActivityState
|
csharp
|
jellyfin__jellyfin
|
MediaBrowser.Controller/Entities/ICollectionFolder.cs
|
{
"start": 459,
"end": 564
}
|
public interface ____
{
bool EnableUserSpecificView { get; }
}
|
ISupportsUserSpecificView
|
csharp
|
dotnet__maui
|
src/Core/src/Platform/Android/MauiBoxView.cs
|
{
"start": 102,
"end": 221
}
|
public class ____ : PlatformGraphicsView
{
public MauiBoxView(Context? context) : base(context)
{
}
}
}
|
MauiBoxView
|
csharp
|
getsentry__sentry-dotnet
|
test/Sentry.Extensions.Logging.Tests/SentryLoggerTests.cs
|
{
"start": 118,
"end": 12585
}
|
private class ____
{
public string CategoryName { get; set; } = "SomeApp";
public IHub Hub { get; set; } = Substitute.For<IHub>();
public SentryLoggingOptions Options { get; set; } = new();
public Scope Scope { get; } = new(new SentryOptions());
public Fixture()
{
_ = Hub.IsEnabled.Returns(true);
Hub.SubstituteConfigureScope(Scope);
}
public SentryLogger GetSut() => new(CategoryName, Options, new MockClock(), Hub);
}
private readonly Fixture _fixture = new();
private const string BreadcrumbType = null;
[Fact]
public void Log_InvokesSdkIsEnabled()
{
var sut = _fixture.GetSut();
sut.Log(LogLevel.Critical, 1, "info", null, null);
_ = _fixture.Hub.Received(1).IsEnabled;
}
[Fact]
public void Log_EventWithException_NoBreadcrumb()
{
var expectedException = new Exception("expected message");
var sut = _fixture.GetSut();
// LogLevel.Critical will create an event
sut.Log<object>(LogLevel.Critical, default, null, expectedException, null);
// Breadcrumbs get created automatically by the hub for captured exceptions... we don't want
// our logging integration to be creating these also
_fixture.Scope.Breadcrumbs.Should().BeEmpty();
}
[Fact]
public void Log_EventWithoutException_LeavesBreadcrumb()
{
var sut = _fixture.GetSut();
// LogLevel.Critical will create an event, but there's no exception so we do want a breadcrumb
sut.Log<object>(LogLevel.Critical, default, null, null, null);
_fixture.Scope.Breadcrumbs.Should().NotBeEmpty();
}
[Fact]
public void Log_WithEventId_EventIdAsTagOnEvent()
{
var expectedEventId = new EventId(10, "EventId-!@#$%^&*(");
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, expectedEventId, null, null, null);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Is<SentryEvent>(
e => e.Tags[EventIdExtensions.DataKey] == expectedEventId.ToString()));
}
[Fact]
public void Log_WithProperties_SetsTagsInEvent()
{
var guidValue = Guid.NewGuid();
var props = new List<KeyValuePair<string, object>>
{
new("fooString", "bar"),
new("fooInteger", 1234),
new("fooLong", 1234L),
new("fooUShort", (ushort)1234),
new("fooDouble", (double)1234),
new("fooFloat", (float)1234.123),
new("fooGuid", guidValue),
new("fooEnum", UriKind.Absolute) // any enum, just an example
};
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, default, props, null, null);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Is<SentryEvent>(
e => e.Tags["fooString"] == "bar" &&
e.Tags["fooInteger"] == "1234" &&
e.Tags["fooLong"] == "1234" &&
e.Tags["fooUShort"] == "1234" &&
e.Tags["fooDouble"] == "1234" &&
e.Tags["fooFloat"] == "1234.123" &&
e.Tags["fooGuid"] == guidValue.ToString() &&
e.Tags["fooEnum"] == "Absolute"));
}
[Fact]
public void Culture_does_not_effect_tags()
{
var props = new List<KeyValuePair<string, object>>
{
new("fooInteger", 12345),
new("fooDouble", 12345.123d),
new("fooFloat", 1234.123f),
};
SentryEvent sentryEvent;
var culture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = new("da-DK");
sentryEvent = SentryLogger.CreateEvent(LogLevel.Debug, default, props, null, null, "category");
}
finally
{
Thread.CurrentThread.CurrentCulture = culture;
}
var tags = sentryEvent.Tags;
Assert.Equal("12345", tags["fooInteger"]);
Assert.Equal("12345.123", tags["fooDouble"]);
Assert.Equal("1234.123", tags["fooFloat"]);
}
[Fact]
public void Log_WithEmptyGuidProperty_DoesntSetTagInEvent()
{
var props = new List<KeyValuePair<string, object>>
{
new("fooGuid", Guid.Empty)
};
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, default, props, null, null);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Is<SentryEvent>(
e => e.Tags.Count == 0));
}
[Fact]
public void LogCritical_MatchingFilter_DoesNotCapturesEvent()
{
const string expected = "message";
_fixture.Options.AddLogEntryFilter((_, _, _, _) => false);
_fixture.Options.AddLogEntryFilter((_, _, _, _) => true);
var sut = _fixture.GetSut();
sut.LogCritical(expected);
_ = _fixture.Hub.DidNotReceive()
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void LogCritical_MatchingFilter_DoesNotAddBreadcrumb()
{
const string expected = "message";
_fixture.Options.AddLogEntryFilter((_, _, _, _) => false);
_fixture.Options.AddLogEntryFilter((_, _, _, _) => true);
var sut = _fixture.GetSut();
sut.LogCritical(expected);
_fixture.Hub.DidNotReceive()
// Breadcrumbs live in the scope
.ConfigureScope(Arg.Any<Action<Scope>>());
}
[Fact]
public void LogCritical_NotMatchingFilter_CapturesEvent()
{
const string expected = "message";
_fixture.Options.AddLogEntryFilter((_, _, _, _) => false);
_fixture.Options.AddLogEntryFilter((_, _, _, _) => false);
var sut = _fixture.GetSut();
sut.LogCritical(expected);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void LogCritical_DefaultOptions_CapturesEvent()
{
const string expected = "message";
var sut = _fixture.GetSut();
sut.LogCritical(expected);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void LogError_DefaultOptions_CapturesEvent()
{
const string expected = "message";
var sut = _fixture.GetSut();
sut.LogError(expected);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void Log_SentryCategory_DoesNotSendEvent()
{
var expectedException = new Exception("expected message");
_fixture.CategoryName = "Sentry.Some.Class";
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, default, null, expectedException, null);
_ = _fixture.Hub.DidNotReceive()
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void Log_SentryRootCategory_DoesNotSendEvent()
{
var expectedException = new Exception("expected message");
_fixture.CategoryName = "Sentry";
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, default, null, expectedException, null);
_ = _fixture.Hub.DidNotReceive()
.CaptureEvent(Arg.Any<SentryEvent>());
}
// https://github.com/getsentry/sentry-dotnet/issues/132
[Fact]
public void Log_SentrySomethingCategory_SendEvent()
{
var expectedException = new Exception("expected message");
_fixture.CategoryName = "SentrySomething";
var sut = _fixture.GetSut();
sut.Log<object>(LogLevel.Critical, default, null, expectedException, null);
_ = _fixture.Hub.Received(1)
.CaptureEvent(Arg.Any<SentryEvent>());
}
[Fact]
public void LogWarning_DefaultOptions_RecordsBreadcrumbs()
{
const string expectedMessage = "message";
const BreadcrumbLevel expectedLevel = BreadcrumbLevel.Warning;
var sut = _fixture.GetSut();
sut.LogWarning(expectedMessage);
var b = _fixture.Scope.Breadcrumbs.First();
Assert.Equal(expectedMessage, b.Message);
Assert.Equal(DateTimeOffset.MaxValue, b.Timestamp);
Assert.Equal(_fixture.CategoryName, b.Category);
Assert.Equal(expectedLevel, b.Level);
Assert.Equal(BreadcrumbType, b.Type);
Assert.Null(b.Data);
}
[Fact]
public void LogInformation_DefaultOptions_RecordsBreadcrumbs()
{
const string expectedMessage = "message";
const BreadcrumbLevel expectedLevel = BreadcrumbLevel.Info;
var sut = _fixture.GetSut();
sut.LogInformation(expectedMessage);
var b = _fixture.Scope.Breadcrumbs.First();
Assert.Equal(expectedMessage, b.Message);
Assert.Equal(DateTimeOffset.MaxValue, b.Timestamp);
Assert.Equal(_fixture.CategoryName, b.Category);
Assert.Equal(expectedLevel, b.Level);
Assert.Equal(BreadcrumbType, b.Type);
Assert.Null(b.Data);
}
[Fact]
public void LogDebug_DefaultOptions_DoesNotRecordsBreadcrumbs()
{
var sut = _fixture.GetSut();
sut.LogDebug("anything");
_fixture.Hub.DidNotReceiveWithAnyArgs()
.AddBreadcrumb(
default,
string.Empty,
default,
default,
default,
default);
}
[Fact]
public void LogTrace_DefaultOptions_DoesNotRecordsBreadcrumbs()
{
var sut = _fixture.GetSut();
sut.LogTrace("anything");
_fixture.Hub.DidNotReceiveWithAnyArgs()
.AddBreadcrumb(
default,
string.Empty,
default,
default,
default,
default);
}
[Fact]
public void IsEnabled_DisabledSdk_ReturnsFalse()
{
_ = _fixture.Hub.IsEnabled.Returns(false);
var sut = _fixture.GetSut();
Assert.False(sut.IsEnabled(LogLevel.Critical));
}
[Fact]
public void IsEnabled_EnabledSdk_ReturnsTrue()
{
_ = _fixture.Hub.IsEnabled.Returns(true);
var sut = _fixture.GetSut();
Assert.True(sut.IsEnabled(LogLevel.Critical));
}
[Fact]
public void IsEnabled_EnabledSdkLogLevelNone_ReturnsFalse()
{
_ = _fixture.Hub.IsEnabled.Returns(true);
var sut = _fixture.GetSut();
Assert.False(sut.IsEnabled(LogLevel.None));
}
[Fact]
public void IsEnabled_EnabledSdkLogLevelLower_ReturnsFalse()
{
_fixture.Options.MinimumBreadcrumbLevel = LogLevel.Critical;
_fixture.Options.MinimumEventLevel = LogLevel.Critical;
_ = _fixture.Hub.IsEnabled.Returns(true);
var sut = _fixture.GetSut();
Assert.False(sut.IsEnabled(LogLevel.Error));
}
[Fact]
public void IsEnabled_EnabledSdkLogLevelBreadcrumbLower_ReturnsTrue()
{
_fixture.Options.MinimumBreadcrumbLevel = LogLevel.Critical;
_fixture.Options.MinimumEventLevel = LogLevel.Trace;
_ = _fixture.Hub.IsEnabled.Returns(true);
var sut = _fixture.GetSut();
Assert.True(sut.IsEnabled(LogLevel.Error));
}
[Fact]
public void IsEnabled_EnabledSdkLogLevelEventLower_ReturnsTrue()
{
_fixture.Options.MinimumBreadcrumbLevel = LogLevel.Trace;
_fixture.Options.MinimumEventLevel = LogLevel.Critical;
_ = _fixture.Hub.IsEnabled.Returns(true);
var sut = _fixture.GetSut();
Assert.True(sut.IsEnabled(LogLevel.Error));
}
[Fact]
public void BeginScope_NullState_PushesScope()
{
var sut = _fixture.GetSut();
_ = sut.BeginScope<object>(null);
_ = _fixture.Hub.Received(1).PushScope<object>(null);
}
[Fact]
public void BeginScope_StringState_PushesScope()
{
const string expected = "state";
var sut = _fixture.GetSut();
_ = sut.BeginScope(expected);
_ = _fixture.Hub.Received(1).PushScope(expected);
}
[Fact]
public void BeginScope_Disposable_Scope()
{
var expected = Substitute.For<IDisposable>();
_ = _fixture.Hub.PushScope(Arg.Any<string>()).Returns(expected);
var sut = _fixture.GetSut();
var actual = sut.BeginScope("state");
Assert.Same(actual, expected);
}
}
|
Fixture
|
csharp
|
dotnet__tye
|
src/Microsoft.Tye.Core/DeploymentKind.cs
|
{
"start": 235,
"end": 323
}
|
public enum ____
{
None,
Kubernetes,
Oam,
}
}
|
DeploymentKind
|
csharp
|
dotnet__maui
|
src/Essentials/src/TextToSpeech/TextToSpeech.macos.cs
|
{
"start": 2230,
"end": 2716
}
|
class ____ : NSSpeechSynthesizerDelegate
{
public event Action<bool> FinishedSpeaking;
public event Action<string> EncounteredError;
public override void DidEncounterError(NSSpeechSynthesizer sender, nuint characterIndex, string theString, string message) =>
EncounteredError?.Invoke(message);
public override void DidFinishSpeaking(NSSpeechSynthesizer sender, bool finishedSpeaking) =>
FinishedSpeaking?.Invoke(finishedSpeaking);
}
}
}
|
SpeechSynthesizerDelegate
|
csharp
|
dotnet__orleans
|
src/api/Orleans.Core/Orleans.Core.cs
|
{
"start": 257263,
"end": 257993
}
|
partial class ____<T> : global::Orleans.Serialization.Cloning.IDeepCopier<Invokable_IMemoryStorageGrain_GrainReference_45659318_1<T>>, global::Orleans.Serialization.Cloning.IDeepCopier
{
public Invokable_IMemoryStorageGrain_GrainReference_45659318_1<T> DeepCopy(Invokable_IMemoryStorageGrain_GrainReference_45659318_1<T> original, global::Orleans.Serialization.Cloning.CopyContext context) { throw null; }
}
[System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public sealed
|
Copier_Invokable_IMemoryStorageGrain_GrainReference_45659318_1
|
csharp
|
unoplatform__uno
|
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Bluetooth.Rfcomm/RfcommDeviceService.cs
|
{
"start": 307,
"end": 13401
}
|
public partial class ____ : global::System.IDisposable
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal RfcommDeviceService()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Networking.HostName ConnectionHostName
{
get
{
throw new global::System.NotImplementedException("The member HostName RfcommDeviceService.ConnectionHostName is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=HostName%20RfcommDeviceService.ConnectionHostName");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string ConnectionServiceName
{
get
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.ConnectionServiceName is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.ConnectionServiceName");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Networking.Sockets.SocketProtectionLevel MaxProtectionLevel
{
get
{
throw new global::System.NotImplementedException("The member SocketProtectionLevel RfcommDeviceService.MaxProtectionLevel is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SocketProtectionLevel%20RfcommDeviceService.MaxProtectionLevel");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Networking.Sockets.SocketProtectionLevel ProtectionLevel
{
get
{
throw new global::System.NotImplementedException("The member SocketProtectionLevel RfcommDeviceService.ProtectionLevel is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SocketProtectionLevel%20RfcommDeviceService.ProtectionLevel");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId ServiceId
{
get
{
throw new global::System.NotImplementedException("The member RfcommServiceId RfcommDeviceService.ServiceId is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=RfcommServiceId%20RfcommDeviceService.ServiceId");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Devices.Bluetooth.BluetoothDevice Device
{
get
{
throw new global::System.NotImplementedException("The member BluetoothDevice RfcommDeviceService.Device is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=BluetoothDevice%20RfcommDeviceService.Device");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Devices.Enumeration.DeviceAccessInformation DeviceAccessInformation
{
get
{
throw new global::System.NotImplementedException("The member DeviceAccessInformation RfcommDeviceService.DeviceAccessInformation is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DeviceAccessInformation%20RfcommDeviceService.DeviceAccessInformation");
}
}
#endif
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.ConnectionHostName.get
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.ConnectionServiceName.get
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.ServiceId.get
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.ProtectionLevel.get
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.MaxProtectionLevel.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncOperation<global::System.Collections.Generic.IReadOnlyDictionary<uint, global::Windows.Storage.Streams.IBuffer>> GetSdpRawAttributesAsync()
{
throw new global::System.NotImplementedException("The member IAsyncOperation<IReadOnlyDictionary<uint, IBuffer>> RfcommDeviceService.GetSdpRawAttributesAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CIReadOnlyDictionary%3Cuint%2C%20IBuffer%3E%3E%20RfcommDeviceService.GetSdpRawAttributesAsync%28%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncOperation<global::System.Collections.Generic.IReadOnlyDictionary<uint, global::Windows.Storage.Streams.IBuffer>> GetSdpRawAttributesAsync(global::Windows.Devices.Bluetooth.BluetoothCacheMode cacheMode)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<IReadOnlyDictionary<uint, IBuffer>> RfcommDeviceService.GetSdpRawAttributesAsync(BluetoothCacheMode cacheMode) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CIReadOnlyDictionary%3Cuint%2C%20IBuffer%3E%3E%20RfcommDeviceService.GetSdpRawAttributesAsync%28BluetoothCacheMode%20cacheMode%29");
}
#endif
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.Device.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void Dispose()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService", "void RfcommDeviceService.Dispose()");
}
#endif
// Forced skipping of method Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.DeviceAccessInformation.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncOperation<global::Windows.Devices.Enumeration.DeviceAccessStatus> RequestAccessAsync()
{
throw new global::System.NotImplementedException("The member IAsyncOperation<DeviceAccessStatus> RfcommDeviceService.RequestAccessAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CDeviceAccessStatus%3E%20RfcommDeviceService.RequestAccessAsync%28%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static string GetDeviceSelectorForBluetoothDevice(global::Windows.Devices.Bluetooth.BluetoothDevice bluetoothDevice)
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.GetDeviceSelectorForBluetoothDevice(BluetoothDevice bluetoothDevice) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.GetDeviceSelectorForBluetoothDevice%28BluetoothDevice%20bluetoothDevice%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static string GetDeviceSelectorForBluetoothDevice(global::Windows.Devices.Bluetooth.BluetoothDevice bluetoothDevice, global::Windows.Devices.Bluetooth.BluetoothCacheMode cacheMode)
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.GetDeviceSelectorForBluetoothDevice(BluetoothDevice bluetoothDevice, BluetoothCacheMode cacheMode) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.GetDeviceSelectorForBluetoothDevice%28BluetoothDevice%20bluetoothDevice%2C%20BluetoothCacheMode%20cacheMode%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static string GetDeviceSelectorForBluetoothDeviceAndServiceId(global::Windows.Devices.Bluetooth.BluetoothDevice bluetoothDevice, global::Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId serviceId)
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.GetDeviceSelectorForBluetoothDeviceAndServiceId(BluetoothDevice bluetoothDevice, RfcommServiceId serviceId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.GetDeviceSelectorForBluetoothDeviceAndServiceId%28BluetoothDevice%20bluetoothDevice%2C%20RfcommServiceId%20serviceId%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static string GetDeviceSelectorForBluetoothDeviceAndServiceId(global::Windows.Devices.Bluetooth.BluetoothDevice bluetoothDevice, global::Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId serviceId, global::Windows.Devices.Bluetooth.BluetoothCacheMode cacheMode)
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.GetDeviceSelectorForBluetoothDeviceAndServiceId(BluetoothDevice bluetoothDevice, RfcommServiceId serviceId, BluetoothCacheMode cacheMode) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.GetDeviceSelectorForBluetoothDeviceAndServiceId%28BluetoothDevice%20bluetoothDevice%2C%20RfcommServiceId%20serviceId%2C%20BluetoothCacheMode%20cacheMode%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static global::Windows.Foundation.IAsyncOperation<global::Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService> FromIdAsync(string deviceId)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<RfcommDeviceService> RfcommDeviceService.FromIdAsync(string deviceId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CRfcommDeviceService%3E%20RfcommDeviceService.FromIdAsync%28string%20deviceId%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static string GetDeviceSelector(global::Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId serviceId)
{
throw new global::System.NotImplementedException("The member string RfcommDeviceService.GetDeviceSelector(RfcommServiceId serviceId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20RfcommDeviceService.GetDeviceSelector%28RfcommServiceId%20serviceId%29");
}
#endif
// Processing: System.IDisposable
}
}
|
RfcommDeviceService
|
csharp
|
microsoft__garnet
|
libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/InternalUpsert.cs
|
{
"start": 187,
"end": 572
}
|
partial class ____<TKey, TValue, TStoreFunctions, TAllocator> : TsavoriteBase
where TStoreFunctions : IStoreFunctions<TKey, TValue>
where TAllocator : IAllocator<TKey, TValue, TStoreFunctions>
{
/// <summary>
/// Upsert operation. Replaces the value corresponding to 'key' with provided 'value', if one exists
/// else inserts a new
|
TsavoriteKV
|
csharp
|
bitwarden__server
|
src/Core/Vault/Queries/IGetSecurityTasksNotificationDetailsQuery.cs
|
{
"start": 102,
"end": 658
}
|
public interface ____
{
/// <summary>
/// Retrieves all users within the given organization that are applicable to the given security tasks.
///
/// <param name="organizationId"></param>
/// <param name="tasks"></param>
/// <returns>A dictionary of UserIds and the corresponding amount of security tasks applicable to them.</returns>
/// </summary>
public Task<ICollection<UserSecurityTaskCipher>> GetNotificationDetailsByManyIds(Guid organizationId, IEnumerable<SecurityTask> tasks);
}
|
IGetSecurityTasksNotificationDetailsQuery
|
csharp
|
StackExchange__StackExchange.Redis
|
src/StackExchange.Redis/RedisDatabase.cs
|
{
"start": 297724,
"end": 299085
}
|
private sealed class ____ : ResultProcessor<RedisValueWithExpiry>
{
public static readonly ResultProcessor<RedisValueWithExpiry> Default = new StringGetWithExpiryProcessor();
private StringGetWithExpiryProcessor() { }
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Resp2TypeBulkString)
{
case ResultType.Integer:
case ResultType.SimpleString:
case ResultType.BulkString:
RedisValue value = result.AsRedisValue();
if (message is StringGetWithExpiryMessage sgwem && sgwem.UnwrapValue(out var expiry, out var ex))
{
if (ex == null)
{
SetResult(message, new RedisValueWithExpiry(value, expiry));
}
else
{
SetException(message, ex);
}
return true;
}
break;
}
return false;
}
}
}
}
|
StringGetWithExpiryProcessor
|
csharp
|
nopSolutions__nopCommerce
|
src/Libraries/Nop.Data/Mapping/Builders/Orders/RecurringPaymentHistoryBuilder.cs
|
{
"start": 235,
"end": 713
}
|
public partial class ____ : NopEntityBuilder<RecurringPaymentHistory>
{
#region Methods
/// <summary>
/// Apply entity configuration
/// </summary>
/// <param name="table">Create table expression builder</param>
public override void MapEntity(CreateTableExpressionBuilder table)
{
table.WithColumn(nameof(RecurringPaymentHistory.RecurringPaymentId)).AsInt32().ForeignKey<RecurringPayment>();
}
#endregion
}
|
RecurringPaymentHistoryBuilder
|
csharp
|
dotnet__efcore
|
src/EFCore/Metadata/RuntimeComplexProperty.cs
|
{
"start": 589,
"end": 5702
}
|
public class ____ : RuntimePropertyBase, IRuntimeComplexProperty
{
private readonly bool _isNullable;
// Warning: Never access these fields directly as access needs to be thread-safe
private IClrCollectionAccessor? _collectionAccessor;
private bool _collectionAccessorInitialized;
/// <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>
[EntityFrameworkInternal]
public RuntimeComplexProperty(
string name,
Type clrType,
string targetTypeName,
[DynamicallyAccessedMembers(IEntityType.DynamicallyAccessedMemberTypes)] Type targetType,
PropertyInfo? propertyInfo,
FieldInfo? fieldInfo,
RuntimeTypeBase declaringType,
PropertyAccessMode propertyAccessMode,
bool nullable,
bool collection,
ChangeTrackingStrategy changeTrackingStrategy,
PropertyInfo? indexerPropertyInfo,
bool propertyBag,
string? discriminatorProperty,
object? discriminatorValue,
int propertyCount,
int complexPropertyCount)
: base(name, propertyInfo, fieldInfo, propertyAccessMode)
{
DeclaringType = declaringType;
ClrType = clrType;
_isNullable = nullable;
IsCollection = collection;
ComplexType = new RuntimeComplexType(
targetTypeName, targetType, this, changeTrackingStrategy, indexerPropertyInfo, propertyBag,
discriminatorProperty, discriminatorValue,
propertyCount: propertyCount,
complexPropertyCount: complexPropertyCount);
}
/// <summary>
/// Gets the type of value that this property-like object holds.
/// </summary>
[DynamicallyAccessedMembers(IProperty.DynamicallyAccessedMemberTypes)]
protected override Type ClrType { get; }
/// <summary>
/// Gets the type that this property belongs to.
/// </summary>
public override RuntimeTypeBase DeclaringType { get; }
/// <summary>
/// Gets the type of value that this property-like object holds.
/// </summary>
public virtual RuntimeComplexType ComplexType { get; }
/// <inheritdoc />
public override bool IsCollection { get; }
/// <inheritdoc />
public override object? Sentinel
=> null;
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
=> ((IReadOnlyComplexProperty)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);
/// <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>
[EntityFrameworkInternal]
public virtual DebugView DebugView
=> new(
() => ((IReadOnlyComplexProperty)this).ToDebugString(),
() => ((IReadOnlyComplexProperty)this).ToDebugString(MetadataDebugStringOptions.LongDefault));
/// <inheritdoc />
IReadOnlyTypeBase IReadOnlyPropertyBase.DeclaringType
{
[DebuggerStepThrough]
get => DeclaringType;
}
/// <inheritdoc />
ITypeBase IPropertyBase.DeclaringType
{
[DebuggerStepThrough]
get => DeclaringType;
}
/// <inheritdoc />
IComplexType IComplexProperty.ComplexType
{
[DebuggerStepThrough]
get => ComplexType;
}
/// <inheritdoc />
IReadOnlyComplexType IReadOnlyComplexProperty.ComplexType
{
[DebuggerStepThrough]
get => ComplexType;
}
/// <inheritdoc />
bool IReadOnlyComplexProperty.IsNullable
{
[DebuggerStepThrough]
get => _isNullable;
}
/// <inheritdoc />
[DebuggerStepThrough]
IClrCollectionAccessor? IPropertyBase.GetCollectionAccessor()
=> NonCapturingLazyInitializer.EnsureInitialized(
ref _collectionAccessor,
ref _collectionAccessorInitialized,
this,
static complexProperty => ((IComplexProperty)complexProperty).IsCollection
? RuntimeFeature.IsDynamicCodeSupported
? ClrCollectionAccessorFactory.Instance.Create(complexProperty)
: throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel)
: null);
}
|
RuntimeComplexProperty
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Fusion-vnext/src/Fusion.Packaging/FusionArchiveReadOptions.cs
|
{
"start": 141,
"end": 412
}
|
record ____ FusionArchiveReadOptions(
int MaxAllowedSchemaSize,
int MaxAllowedSettingsSize)
{
/// <summary>
/// Gets the default read options.
/// </summary>
public static FusionArchiveReadOptions Default { get; } = new(50_000_000, 512_000);
}
|
struct
|
csharp
|
icsharpcode__ILSpy
|
ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs
|
{
"start": 1429,
"end": 1913
}
|
internal class ____ : MetadataTableTreeNode<PropertyTableTreeNode.PropertyDefEntry>
{
public PropertyTableTreeNode(MetadataFile metadataFile)
: base(TableIndex.Property, metadataFile)
{
}
protected override IReadOnlyList<PropertyDefEntry> LoadTable()
{
var list = new List<PropertyDefEntry>();
foreach (var row in metadataFile.Metadata.PropertyDefinitions)
{
list.Add(new PropertyDefEntry(metadataFile, row));
}
return list;
}
|
PropertyTableTreeNode
|
csharp
|
neuecc__MessagePack-CSharp
|
src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs
|
{
"start": 524,
"end": 16016
}
|
public class ____ : DiagnosticAnalyzer
{
public const string UseMessagePackObjectAttributeId = "MsgPack003";
public const string AttributeMessagePackObjectMembersId = "MsgPack004";
public const string InvalidMessagePackObjectId = "MsgPack005";
public const string MessagePackFormatterMustBeMessagePackFormatterId = "MsgPack006";
public const string DeserializingConstructorId = "MsgPack007";
public const string AOTLimitationsId = "MsgPack008";
public const string CollidingFormattersId = "MsgPack009";
public const string InaccessibleFormatterTypeId = "MsgPack010";
public const string PartialTypeRequiredId = "MsgPack011";
public const string InaccessibleDataTypeId = "MsgPack012";
public const string InaccessibleFormatterInstanceId = "MsgPack013";
public const string NullableReferenceTypeFormatterId = "MsgPack014";
public const string MessagePackObjectAllowPrivateId = "MsgPack015";
public const string AOTDerivedKeyId = "MsgPack016";
public const string AOTInitPropertyId = "MsgPack017";
public const string CollidingMemberNamesInForceMapModeId = "MsgPack018";
internal const string Category = "Usage";
public const string MessagePackObjectAttributeShortName = Constants.MessagePackObjectAttributeName;
public const string KeyAttributeShortName = "KeyAttribute";
public const string IgnoreShortName = "IgnoreMemberAttribute";
public const string DataMemberShortName = "DataMemberAttribute";
public const string IgnoreDataMemberShortName = "IgnoreDataMemberAttribute";
public const string AllowPrivatePropertyName = "AllowPrivate";
private const string InvalidMessagePackObjectTitle = "MessagePackObject validation";
private const DiagnosticSeverity InvalidMessagePackObjectSeverity = DiagnosticSeverity.Error;
public static readonly DiagnosticDescriptor TypeMustBeMessagePackObject = new DiagnosticDescriptor(
id: UseMessagePackObjectAttributeId,
title: "Use MessagePackObjectAttribute",
category: Category,
messageFormat: "Type must be marked with MessagePackObjectAttribute: {0}", // type.Name
description: "Type must be marked with MessagePackObjectAttribute.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(UseMessagePackObjectAttributeId));
public static readonly DiagnosticDescriptor MessageFormatterMustBeMessagePackFormatter = new DiagnosticDescriptor(
id: MessagePackFormatterMustBeMessagePackFormatterId,
title: "Must be IMessageFormatter",
category: Category,
messageFormat: "Type must be of IMessagePackFormatter: {0}", // type.Name
description: "Type must be of IMessagePackFormatter.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(MessagePackFormatterMustBeMessagePackFormatterId));
public static readonly DiagnosticDescriptor MemberNeedsKey = new DiagnosticDescriptor(
id: AttributeMessagePackObjectMembersId,
title: "Attribute properties and fields of MessagePack objects",
category: Category,
messageFormat: "Properties and fields of MessagePackObject-attributed types require either KeyAttribute or IgnoreMemberAttribute: {0}.{1}", // type.Name + "." + item.Name
description: "Member must be marked with KeyAttribute or IgnoreMemberAttribute.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AttributeMessagePackObjectMembersId));
public static readonly DiagnosticDescriptor BaseTypeContainsUnattributedPublicMembers = new DiagnosticDescriptor(
id: AttributeMessagePackObjectMembersId,
title: "Attribute properties and fields of MessagePack objects",
category: Category,
messageFormat: "Properties and fields of base types of MessagePackObject-attributed types require either KeyAttribute or IgnoreMemberAttribute: {0}.{1}", // type.Name + "." + item.Name
description: "Member must be marked with KeyAttribute or IgnoreMemberAttribute.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AttributeMessagePackObjectMembersId));
public static readonly DiagnosticDescriptor InvalidMessagePackObject = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "Invalid MessagePackObject definition: {0}", // details
description: "Invalid MessagePackObject definition.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
public static readonly DiagnosticDescriptor BothStringAndIntKeyAreNull = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "Both int and string keys are null: {0}.{1}", // type.Name + "." + item.Name
description: "An int or string key must be supplied to the KeyAttribute.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
public static readonly DiagnosticDescriptor DoNotMixStringAndIntKeys = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "All KeyAttribute arguments must be of the same type (either string or int)",
description: "Use string or int keys consistently.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
public static readonly DiagnosticDescriptor KeysMustBeUnique = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "All KeyAttribute arguments must be unique",
description: "Each key must be unique.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
public static readonly DiagnosticDescriptor UnionAttributeRequired = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "This type must carry a UnionAttribute",
description: "A UnionAttribute is required on interfaces and abstract base classes used as serialized types.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
// This is important because [Key] on a private member still will not be serialized, which is very confusing until
// one realizes the type is serializing in map mode.
public static readonly DiagnosticDescriptor KeyAnnotatedMemberInMapMode = new DiagnosticDescriptor(
id: InvalidMessagePackObjectId,
title: InvalidMessagePackObjectTitle,
category: Category,
messageFormat: "Types in map mode should not annotate members with KeyAttribute",
description: "When in map mode (by compilation setting or with [MessagePackObject(true)]), internal and public members are automatically included in serialization and should not be annotated with KeyAttribute.",
defaultSeverity: InvalidMessagePackObjectSeverity,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId));
public static readonly DiagnosticDescriptor NoDeserializingConstructor = new DiagnosticDescriptor(
id: DeserializingConstructorId,
title: "Deserializing constructors",
category: Category,
messageFormat: "Cannot find a public constructor",
description: "A deserializable type must carry a public constructor.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId));
public static readonly DiagnosticDescriptor DeserializingConstructorParameterTypeMismatch = new DiagnosticDescriptor(
id: DeserializingConstructorId,
title: "Deserializing constructors",
category: Category,
messageFormat: "Deserializing constructor parameter type mismatch",
description: "Constructor parameter types must match the serializable members.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId));
public static readonly DiagnosticDescriptor DeserializingConstructorParameterIndexMissing = new DiagnosticDescriptor(
id: DeserializingConstructorId,
title: "Deserializing constructors",
category: Category,
messageFormat: "Deserializing constructor parameter count mismatch",
description: "The deserializing constructor parameter count must meet or exceed the number of serialized members.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId));
public static readonly DiagnosticDescriptor DeserializingConstructorParameterNameMissing = new DiagnosticDescriptor(
id: DeserializingConstructorId,
title: "Deserializing constructors",
category: Category,
messageFormat: "Deserializing constructor parameter name mismatch",
description: "Parameter names must match the serialized members' named keys.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId));
public static readonly DiagnosticDescriptor DeserializingConstructorParameterNameDuplicate = new DiagnosticDescriptor(
id: DeserializingConstructorId,
title: "Deserializing constructors",
category: Category,
messageFormat: "Duplicate matched constructor parameter name",
description: "Parameter names must match the serialized members' named keys.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId));
public static readonly DiagnosticDescriptor AotUnionAttributeRequiresTypeArg = new DiagnosticDescriptor(
id: AOTLimitationsId,
title: "AOT limitations",
category: Category,
messageFormat: "The source generator only supports UnionAttribute with a Type argument",
description: "Use a type argument with UnionAttribute.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTLimitationsId));
public static readonly DiagnosticDescriptor AotArrayRankTooHigh = new DiagnosticDescriptor(
id: AOTLimitationsId,
title: "AOT limitations",
category: Category,
messageFormat: "Array rank too high for built-in array formatters",
description: "Avoid excessively high array ranks, or write a custom formatter.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTLimitationsId));
public static readonly DiagnosticDescriptor AOTDerivedKeyAttribute = new DiagnosticDescriptor(
id: AOTDerivedKeyId,
title: "KeyAttribute derivatives",
category: Category,
messageFormat: "KeyAttribute-derived attributes are not supported by AOT formatters",
description: "Use [Key(x)] attributes directly, or switch off source generation for this type using [MessagePackObject(SuppressSourceGeneration = true)].",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTDerivedKeyId));
public static readonly DiagnosticDescriptor AOTInitProperty = new(
id: AOTInitPropertyId,
title: "Property with init accessor and initializer",
category: Category,
messageFormat: "The value of a property with an init accessor and an initializer will be reset to the default value for the type upon deserialization when no value for them is deserialized",
description: "Due to a limitation in the C# language, properties with init accessor must be set by source generated deserializers unconditionally. When the data stream lacks a value for the property, it will be set with the default value for the property type, overriding a default that an initializer might set.",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTInitPropertyId));
public static readonly DiagnosticDescriptor CollidingFormatters = new(
id: CollidingFormattersId,
title: "Colliding formatters",
category: Category,
messageFormat: "Multiple formatters for type {0} found",
description: "Only one formatter per type is allowed.",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(CollidingFormattersId));
public static readonly DiagnosticDescriptor InaccessibleFormatterInstance = new(
id: InaccessibleFormatterInstanceId,
title: "Inaccessible formatter",
category: Category,
messageFormat: "Formatter should declare a default constructor with at least internal visibility or a public static readonly field named Instance that returns the singleton",
description: "The auto-generated resolver cannot construct this formatter without a constructor. It will be omitted from the resolver.",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InaccessibleFormatterInstanceId));
public static readonly DiagnosticDescriptor InaccessibleFormatterType = new(
id: InaccessibleFormatterTypeId,
title: "Inaccessible formatter",
category: Category,
messageFormat: "Formatter should be declared with at least internal visibility",
description: "The auto-generated resolver cannot access this formatter. It will be omitted from the resolver.",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InaccessibleFormatterTypeId));
public static readonly DiagnosticDescriptor PartialTypeRequired = new(
id: PartialTypeRequiredId,
title: "Partial type required",
category: Category,
messageFormat: "Types with private, serializable members must be declared as partial, including nesting types",
description: "When a data type has serializable members that may only be accessible to the
|
MsgPack00xMessagePackAnalyzer
|
csharp
|
Testably__Testably.Abstractions
|
Source/Testably.Abstractions.Testing/Polyfills/MatchType.cs
|
{
"start": 193,
"end": 1054
}
|
public enum ____
{
/// <summary>
/// <para>Matches using '*' and '?' wildcards.</para>
/// <para>
/// <c>*</c> matches from zero to any amount of characters. <c>?</c> matches exactly one character. <c>*.*</c>
/// matches any name with a period in it (with <see cref="MatchType.Win32" />, this would match all items).
/// </para>
/// </summary>
Simple,
/// <summary>
/// <para>Match using Win32 DOS style matching semantics.</para>
/// <para>
/// '*', '?', '<', '>', and '"' are all considered wildcards. Matches in a traditional DOS <c>/</c> Windows
/// command prompt way. <c>*.*</c> matches all files. <c>?</c> matches collapse to periods. <c>file.??t</c> will
/// match <c>file.t</c>, <c>file.at</c>, and <c>file.txt</c>.
/// </para>
/// </summary>
Win32,
}
#endif
|
MatchType
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit.Abstractions/Topology/Configuration/IMessageTopologyConfigurator.cs
|
{
"start": 43,
"end": 702
}
|
public interface ____<TMessage> :
IMessageTypeTopologyConfigurator,
IMessageTopology<TMessage>
where TMessage : class
{
/// <summary>
/// Sets the entity name formatter used for this message type
/// </summary>
/// <param name="entityNameFormatter"></param>
void SetEntityNameFormatter(IMessageEntityNameFormatter<TMessage> entityNameFormatter);
/// <summary>
/// Sets the entity name for this message type
/// </summary>
/// <param name="entityName">The entity name</param>
void SetEntityName(string entityName);
}
|
IMessageTopologyConfigurator
|
csharp
|
unoplatform__uno
|
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Store/LicenseInformation.cs
|
{
"start": 305,
"end": 4511
}
|
public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal LicenseInformation()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.DateTimeOffset ExpirationDate
{
get
{
throw new global::System.NotImplementedException("The member DateTimeOffset LicenseInformation.ExpirationDate is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DateTimeOffset%20LicenseInformation.ExpirationDate");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsActive
{
get
{
throw new global::System.NotImplementedException("The member bool LicenseInformation.IsActive is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20LicenseInformation.IsActive");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsTrial
{
get
{
throw new global::System.NotImplementedException("The member bool LicenseInformation.IsTrial is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20LicenseInformation.IsTrial");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Collections.Generic.IReadOnlyDictionary<string, global::Windows.ApplicationModel.Store.ProductLicense> ProductLicenses
{
get
{
throw new global::System.NotImplementedException("The member IReadOnlyDictionary<string, ProductLicense> LicenseInformation.ProductLicenses is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyDictionary%3Cstring%2C%20ProductLicense%3E%20LicenseInformation.ProductLicenses");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.ProductLicenses.get
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.IsActive.get
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.IsTrial.get
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.ExpirationDate.get
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.LicenseChanged.add
// Forced skipping of method Windows.ApplicationModel.Store.LicenseInformation.LicenseChanged.remove
#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 event global::Windows.ApplicationModel.Store.LicenseChangedEventHandler LicenseChanged
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.LicenseInformation", "event LicenseChangedEventHandler LicenseInformation.LicenseChanged");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.LicenseInformation", "event LicenseChangedEventHandler LicenseInformation.LicenseChanged");
}
}
#endif
}
}
|
LicenseInformation
|
csharp
|
protobuf-net__protobuf-net
|
src/Examples/Issues/Issue27.cs
|
{
"start": 514,
"end": 1375
}
|
public class ____
{
[Fact]
public void Roundtrip()
{
KeyPair<int, string> pair = new KeyPair<int, string>(1, "abc");
KeyPair<int,string> clone = Serializer.DeepClone<KeyPairProxy<int,string>>(pair);
Assert.Equal(pair.Key1, clone.Key1);
Assert.Equal(pair.Key2, clone.Key2);
}
[Fact]
public void TestWrapped()
{
Foo foo = new Foo { Pair = new KeyPair<int, string>(1, "abc") };
Assert.Equal(1, foo.Pair.Key1); //, "Key1 - orig");
Assert.Equal("abc", foo.Pair.Key2); //, "Key2 - orig");
var clone = Serializer.DeepClone(foo);
Assert.Equal(1, clone.Pair.Key1); //, "Key1 - clone");
Assert.Equal("abc", clone.Pair.Key2); //, "Key2 - clone");
}
}
[DataContract]
|
Issue27
|
csharp
|
AvaloniaUI__Avalonia
|
src/Avalonia.Base/Utilities/PooledInlineList.cs
|
{
"start": 3543,
"end": 5265
}
|
public struct ____ : IEnumerator<T>
{
private readonly T? _singleItem;
private int _index;
private readonly SimplePooledList? _list;
public Enumerator(object? item)
{
_index = -1;
_list = item as SimplePooledList;
if (_list == null)
_singleItem = (T?)item;
}
public bool MoveNext()
{
if (_singleItem != null)
{
if (_index >= 0)
return false;
_index = 0;
return true;
}
if (_list != null)
{
if (_index >= _list.Count - 1)
return false;
_index++;
return true;
}
return false;
}
public void Reset() => throw new NotSupportedException();
object IEnumerator.Current => Current;
public T Current
{
get
{
if (_list != null)
return _list.Items![_index];
return _singleItem!;
}
}
public void Dispose()
{
}
}
/// <summary>
/// For compositor serialization purposes only, takes the ownership of previously transferred state
/// </summary>
public PooledInlineList(object? rawState)
{
_item = rawState;
}
/// <summary>
/// For compositor serialization purposes only, gives up the ownership of the internal state and returns it
/// </summary>
public object? TransferRawState()
{
var rv = _item;
_item = null;
return rv;
}
}
|
Enumerator
|
csharp
|
abpframework__abp
|
framework/test/Volo.Abp.Features.Tests/Volo/Abp/Features/TestFeatureStore.cs
|
{
"start": 165,
"end": 1441
}
|
public class ____ : IFeatureStore, ISingletonDependency
{
public const string Tenant1IdValue = "f460fcf7-f944-469a-967b-3b2463323dfe";
public const string Tenant2IdValue = "e10428ad-4608-4c34-a304-6f82502156f2";
public static Guid Tenant1Id = new Guid(Tenant1IdValue);
public static Guid Tenant2Id = new Guid(Tenant2IdValue);
private readonly List<SettingRecord> _settingRecords;
public TestFeatureStore()
{
_settingRecords = new List<SettingRecord>
{
new SettingRecord("BooleanTestFeature1", TenantFeatureValueProvider.ProviderName, Tenant1Id.ToString(), "true"),
new SettingRecord("BooleanTestFeature2", TenantFeatureValueProvider.ProviderName, Tenant1Id.ToString(), "true"),
new SettingRecord("IntegerTestFeature1", TenantFeatureValueProvider.ProviderName, Tenant2Id.ToString(), "34")
};
}
public Task<string> GetOrNullAsync(string name, string providerName, string providerKey)
{
return Task.FromResult(
_settingRecords.FirstOrDefault(sr =>
sr.Name == name &&
sr.ProviderName == providerName &&
sr.ProviderKey == providerKey
)?.Value
);
}
|
TestFeatureStore
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.Shared.Tests/ViewContainers/StateViewContainerRemote.cs
|
{
"start": 86,
"end": 723
}
|
internal sealed class ____ : BaseViewContainerRemote
{
public StateViewContainerRemote(IUIClientContext? testContext, Enum formsType)
: base(testContext, formsType)
{
}
public StateViewContainerRemote(IUIClientContext? testContext, string formsType)
: base(testContext, formsType)
{
}
public void TapStateButton()
{
App.Screenshot("Before state change");
App.WaitForElementTillPageNavigationSettled(StateButtonQuery);
App.Tap(StateButtonQuery);
App.Screenshot("After state change");
}
public IUIElement GetStateLabel()
{
return App.FindElement(StateLabelQuery);
}
}
}
|
StateViewContainerRemote
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
|
{
"start": 384577,
"end": 384797
}
|
public class ____
{
public int Id { get; set; }
public RelatedEntity1762 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1764> ChildEntities { get; set; }
}
|
RelatedEntity1763
|
csharp
|
dotnet__maui
|
src/Controls/tests/SourceGen.UnitTests/XmlParserErrorTests.cs
|
{
"start": 308,
"end": 4182
}
|
private record ____(string Path, string Content, string? RelativePath = null, string? TargetPath = null, string? ManifestResourceName = null, string? TargetFramework = null, string? NoWarn = null)
: AdditionalFile(Text: SourceGeneratorDriver.ToAdditionalText(Path, Content), Kind: "Xaml", RelativePath: RelativePath ?? Path, TargetPath: TargetPath, ManifestResourceName: ManifestResourceName, TargetFramework: TargetFramework, NoWarn: NoWarn);
[Fact]
public void UnclosedTagReportsErrorWithCorrectLocationAndMessage()
{
// XAML with an unclosed Label tag (missing > or /> or </Label>)
// This simulates a common XML syntax error
var xaml =
"""
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Test.TestPage">
<Label Text="foo"
</ContentPage>
""";
var compilation = CreateMauiCompilation();
var result = RunGenerator<XamlGenerator>(compilation, new AdditionalXamlFile("Test.xaml", xaml));
// Should have an error diagnostic
var errors = result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
Assert.Single(errors);
var diagnostic = errors[0];
// Verify diagnostic ID for XAML parser error
Assert.Equal("MAUIG1001", diagnostic.Id);
// Get the location information
var location = diagnostic.Location.GetLineSpan();
var message = diagnostic.GetMessage();
// Output for debugging
System.Console.WriteLine($"Line (0-indexed): {location.StartLinePosition.Line}");
System.Console.WriteLine($"Character (0-indexed): {location.StartLinePosition.Character}");
System.Console.WriteLine($"Message: {message}");
// The error message should mention the XML parsing error
// The XmlException says: "Name cannot begin with the '<' character, hexadecimal value 0x3C. Line 7, position 1."
Assert.Contains("Name cannot begin with the '<' character", message, System.StringComparison.Ordinal);
// PR #13797 fix: The location should be extracted from XmlException
// and the duplicate "Line X, position Y" should be stripped from the message
Assert.Equal(6, location.StartLinePosition.Line); // Line 7 in 1-indexed = line 6 in 0-indexed
Assert.Equal(1, location.StartLinePosition.Character); // Position 1 from XmlException (not converted to 0-indexed by LocationHelpers)
Assert.DoesNotContain("Line 7, position 1", message, System.StringComparison.Ordinal);
}
[Fact]
public void MissingClosingTagReportsErrorWithCorrectLocation()
{
// Another common XML error: tag opened but never closed
var xaml =
"""
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Test.TestPage">
<StackLayout>
<Label Text="Hello"/>
""";
var compilation = CreateMauiCompilation();
var result = RunGenerator<XamlGenerator>(compilation, new AdditionalXamlFile("Test.xaml", xaml));
// Should have an error diagnostic
var errors = result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
Assert.Single(errors);
var diagnostic = errors[0];
Assert.Equal("MAUIG1001", diagnostic.Id);
var message = diagnostic.GetMessage();
var location = diagnostic.Location.GetLineSpan();
System.Console.WriteLine($"Message: {message}");
System.Console.WriteLine($"Location: Line {location.StartLinePosition.Line}, Char {location.StartLinePosition.Character}");
// The error should mention unexpected end of file
Assert.Contains("Unexpected end of file", message, System.StringComparison.Ordinal);
// And should NOT have duplicate line position info
// The message should not end with " Line X, position Y."
Assert.DoesNotContain("Line ", message.Substring(message.Length - 20), System.StringComparison.Ordinal);
}
}
|
AdditionalXamlFile
|
csharp
|
DuendeSoftware__IdentityServer
|
bff/hosts/Hosts.ServiceDefaults/BffAppHostRoutes.cs
|
{
"start": 182,
"end": 881
}
|
public class ____ : IAppHostServiceRoutes
{
public string[] ServiceNames => AppHostServices.All;
public Uri UrlTo(string clientName)
{
var url = clientName switch
{
AppHostServices.Bff => "https://localhost:5002",
AppHostServices.BffBlazorPerComponent => "https://localhost:5105",
AppHostServices.BffMultiFrontend => "https://localhost:5005",
AppHostServices.BffBlazorWebassembly => "https://localhost:5006",
AppHostServices.TemplateBffBlazor => "https://localhost:7035",
_ => throw new InvalidOperationException("client not configured")
};
return new Uri(url);
}
}
|
BffAppHostRoutes
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit/SendEndpointRecurringSchedulerExtensions.cs
|
{
"start": 133,
"end": 8837
}
|
public static class ____
{
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage<T>> ScheduleRecurringSend<T>(this ISendEndpoint endpoint, Uri destinationAddress,
RecurringSchedule schedule, T message,
CancellationToken cancellationToken = default)
where T : class
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage<T>> ScheduleRecurringSend<T>(this ISendEndpoint endpoint, Uri destinationAddress,
RecurringSchedule schedule, T message,
IPipe<SendContext<T>> pipe, CancellationToken cancellationToken = default)
where T : class
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, pipe, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage<T>> ScheduleRecurringSend<T>(this ISendEndpoint endpoint, Uri destinationAddress,
RecurringSchedule schedule, T message,
IPipe<SendContext> pipe, CancellationToken cancellationToken = default)
where T : class
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, pipe, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message object</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage> ScheduleRecurringSend(this ISendEndpoint endpoint, Uri destinationAddress, RecurringSchedule schedule,
object message, CancellationToken cancellationToken = default)
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message object</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="messageType">The type of the message (use message.GetType() if desired)</param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage> ScheduleRecurringSend(this ISendEndpoint endpoint, Uri destinationAddress, RecurringSchedule schedule,
object message, Type messageType, CancellationToken cancellationToken = default)
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, messageType, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message object</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage> ScheduleRecurringSend(this ISendEndpoint endpoint, Uri destinationAddress, RecurringSchedule schedule,
object message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default)
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, pipe, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <param name="endpoint">The message scheduler endpoint</param>
/// <param name="message">The message object</param>
/// <param name="destinationAddress">The destination address where the schedule message should be sent</param>
/// <param name="schedule">The schedule for the message to be delivered</param>
/// <param name="messageType">The type of the message (use message.GetType() if desired)</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static Task<ScheduledRecurringMessage> ScheduleRecurringSend(this ISendEndpoint endpoint, Uri destinationAddress, RecurringSchedule schedule,
object message, Type messageType, IPipe<SendContext> pipe, CancellationToken cancellationToken = default)
{
IRecurringMessageScheduler scheduler = new EndpointRecurringMessageScheduler(endpoint);
return scheduler.ScheduleRecurringSend(destinationAddress, schedule, message, messageType, pipe, cancellationToken);
}
/// <summary>
/// Schedule a message for recurring delivery using the specified schedule
/// </summary>
/// <typeparam name="T">The
|
SendEndpointRecurringSchedulerExtensions
|
csharp
|
dotnet__aspire
|
src/Aspire.Hosting/Dcp/Model/ModelCommon.cs
|
{
"start": 7445,
"end": 8046
}
|
internal static class ____
{
public static bool IsValidObjectName(string candidate)
{
if (string.IsNullOrWhiteSpace(candidate))
{
return false;
}
if (candidate.Length > 253)
{
return false;
}
// Can only contain alphanumeric characters, hyphen, period, underscore, tilde.
// (essentially the same as URL path characters).
// Needs to start with a letter, underscore, or tilde.
bool isValid = Regex.IsMatch(candidate, @"^[[a-zA-Z_~][a-zA-Z0-9\-._~]*$");
return isValid;
}
}
|
Rules
|
csharp
|
unoplatform__uno
|
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Text/TextScript.cs
|
{
"start": 255,
"end": 8386
}
|
public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Undefined = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Ansi = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
EastEurope = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Cyrillic = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Greek = 4,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Turkish = 5,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Hebrew = 6,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Arabic = 7,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Baltic = 8,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Vietnamese = 9,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Default = 10,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Symbol = 11,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Thai = 12,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
ShiftJis = 13,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
GB2312 = 14,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Hangul = 15,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Big5 = 16,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
PC437 = 17,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Oem = 18,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Mac = 19,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Armenian = 20,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Syriac = 21,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Thaana = 22,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Devanagari = 23,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Bengali = 24,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Gurmukhi = 25,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Gujarati = 26,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Oriya = 27,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Tamil = 28,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Telugu = 29,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Kannada = 30,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Malayalam = 31,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Sinhala = 32,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Lao = 33,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Tibetan = 34,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Myanmar = 35,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Georgian = 36,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Jamo = 37,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Ethiopic = 38,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Cherokee = 39,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Aboriginal = 40,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Ogham = 41,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Runic = 42,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Khmer = 43,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Mongolian = 44,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Braille = 45,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Yi = 46,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Limbu = 47,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
TaiLe = 48,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
NewTaiLue = 49,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
SylotiNagri = 50,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Kharoshthi = 51,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Kayahli = 52,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
UnicodeSymbol = 53,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Emoji = 54,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Glagolitic = 55,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Lisu = 56,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Vai = 57,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
NKo = 58,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Osmanya = 59,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
PhagsPa = 60,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Gothic = 61,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Deseret = 62,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Tifinagh = 63,
#endif
}
#endif
}
|
TextScript
|
csharp
|
CommunityToolkit__Maui
|
samples/CommunityToolkit.Maui.Sample/Platforms/MacCatalyst/Program.cs
|
{
"start": 56,
"end": 169
}
|
public class ____
{
static void Main(string[] args) => UIApplication.Main(args, null, typeof(AppDelegate));
}
|
Program
|
csharp
|
nunit__nunit
|
src/NUnitFramework/tests/Constraints/NUnitEqualityComparerTests.cs
|
{
"start": 19281,
"end": 19402
}
|
public interface ____ : IEquatable<IEquatableObject>
{
int SomeProperty { get; set; }
}
|
IEquatableObject
|
csharp
|
AvaloniaUI__Avalonia
|
src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/CompiledBindingPath.cs
|
{
"start": 11034,
"end": 11748
}
|
internal class ____ : ICompiledBindingPathElement
{
public MethodAsCommandElement(string methodName, Action<object, object?> executeHelper, Func<object, object?, bool>? canExecuteHelper, string[] dependsOnElements)
{
MethodName = methodName;
ExecuteMethod = executeHelper;
CanExecuteMethod = canExecuteHelper;
DependsOnProperties = new HashSet<string>(dependsOnElements);
}
public string MethodName { get; }
public Action<object, object?> ExecuteMethod { get; }
public Func<object, object?, bool>? CanExecuteMethod { get; }
public HashSet<string> DependsOnProperties { get; }
}
|
MethodAsCommandElement
|
csharp
|
graphql-dotnet__graphql-dotnet
|
src/GraphQL.Tests/Instrumentation/MiddlewareOrderTests.cs
|
{
"start": 22942,
"end": 23410
}
|
private class ____ : IFieldMiddleware
{
private readonly List<string> _executionOrder;
public OrderTrackingMiddleware2(List<string> executionOrder)
{
_executionOrder = executionOrder;
}
public ValueTask<object?> ResolveAsync(IResolveFieldContext context, FieldMiddlewareDelegate next)
{
_executionOrder.Add("DI2");
return next(context);
}
}
|
OrderTrackingMiddleware2
|
csharp
|
AutoMapper__AutoMapper
|
src/IntegrationTests/IncludeMembers.cs
|
{
"start": 87475,
"end": 87707
}
|
public class ____(DatabaseFixture databaseFixture) : IntegrationTest<SubqueryMapFromWithIncludeMembersFirstOrDefaultWithIheritance.DatabaseInitializer>(databaseFixture)
{
|
SubqueryMapFromWithIncludeMembersFirstOrDefaultWithIheritance
|
csharp
|
xunit__xunit
|
src/xunit.v3.core/Utility/DelegatingMessageBus.cs
|
{
"start": 451,
"end": 1561
}
|
public class ____(
IMessageBus innerMessageBus,
Action<IMessageSinkMessage>? callback = null) :
IMessageBus
{
readonly IMessageBus innerMessageBus = Guard.ArgumentNotNull(innerMessageBus);
/// <inheritdoc/>
public virtual bool QueueMessage(IMessageSinkMessage message)
{
callback?.Invoke(message);
return innerMessageBus.QueueMessage(message);
}
/// <inheritdoc/>
public void Dispose()
{
GC.SuppressFinalize(this);
innerMessageBus.SafeDispose();
}
}
/// <summary>
/// Implementation of <see cref="IMessageBus"/> that delegates to another implementation of
/// <see cref="IMessageBus"/> while calling into an optional callback for each message. In addition,
/// it issues a <see cref="Finished"/> event when a message of the type <typeparamref name="TFinalMessage"/>
/// is seen and records the final message for later retrieval.
/// </summary>
/// <typeparam name="TFinalMessage">The type of the T final message.</typeparam>
/// <param name="innerMessageBus">The message bus to delegate to.</param>
/// <param name="callback">The callback to send messages to.</param>
|
DelegatingMessageBus
|
csharp
|
dotnet__efcore
|
test/EFCore.Tests/ChangeTracking/Internal/InternalClrEntityEntryTest.cs
|
{
"start": 313,
"end": 8616
}
|
public class ____ : InternalEntityEntryTestBase<
InternalClrEntityEntryTest.SomeEntity,
InternalClrEntityEntryTest.SomeSimpleEntityBase,
InternalClrEntityEntryTest.SomeDependentEntity,
InternalClrEntityEntryTest.SomeMoreDependentEntity,
InternalClrEntityEntryTest.Root,
InternalClrEntityEntryTest.FirstDependent,
InternalClrEntityEntryTest.SecondDependent,
InternalClrEntityEntryTest.CompositeRoot,
InternalClrEntityEntryTest.CompositeFirstDependent,
InternalClrEntityEntryTest.SomeCompositeEntityBase,
InternalClrEntityEntryTest.CompositeSecondDependent,
InternalClrEntityEntryTest.KClrContext,
InternalClrEntityEntryTest.KClrSnapContext>
{
[ConditionalFact]
public virtual void All_original_values_can_be_accessed_for_entity_that_does_full_change_tracking_if_eager_values_on()
=> AllOriginalValuesTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Required_original_values_can_be_accessed_for_entity_that_does_full_change_tracking()
=> OriginalValuesTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Required_original_values_can_be_accessed_for_entity_that_does_changed_only_notification()
=> OriginalValuesTest(new ChangedOnlyEntity());
[ConditionalFact]
public virtual void Required_original_values_can_be_accessed_generically_for_entity_that_does_full_change_tracking()
=> GenericOriginalValuesTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Required_original_values_can_be_accessed_generically_for_entity_that_does_changed_only_notification()
=> GenericOriginalValuesTest(new ChangedOnlyEntity());
[ConditionalFact]
public virtual void Null_original_values_are_handled_for_entity_that_does_full_change_tracking()
=> NullOriginalValuesTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Null_original_values_are_handled_for_entity_that_does_changed_only_notification()
=> NullOriginalValuesTest(new ChangedOnlyEntity());
[ConditionalFact]
public virtual void Null_original_values_are_handled_generically_for_entity_that_does_full_change_tracking()
=> GenericNullOriginalValuesTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Null_original_values_are_handled_generically_for_entity_that_does_changed_only_notification()
=> GenericNullOriginalValuesTest(new ChangedOnlyEntity());
[ConditionalFact]
public virtual void Setting_property_using_state_entry_always_marks_as_modified_full_notifications()
=> SetPropertyInternalEntityEntryTest(new FullNotificationEntity());
[ConditionalFact]
public virtual void Setting_property_using_state_entry_always_marks_as_modified_changed_notifications()
=> SetPropertyInternalEntityEntryTest(new ChangedOnlyEntity());
[ConditionalFact]
public void All_original_values_can_be_accessed_for_entity_that_does_changed_only_notifications()
=> AllOriginalValuesTest(new ChangedOnlyEntity());
[ConditionalFact]
public virtual void Temporary_values_are_not_reset_when_entity_is_detached()
{
using var context = new KClrContext();
var entity = new SomeEntity();
var entry = context.Add(entity).GetInfrastructure();
var keyProperty = entry.EntityType.FindProperty("Id");
entry.SetEntityState(EntityState.Added);
entry.SetTemporaryValue(keyProperty, -1);
Assert.NotNull(entry[keyProperty]);
Assert.Equal(-1, entity.Id);
Assert.Equal(-1, entry[keyProperty]);
entry.SetEntityState(EntityState.Detached);
Assert.Equal(-1, entity.Id);
Assert.Equal(-1, entry[keyProperty]);
entry.SetEntityState(EntityState.Added);
Assert.Equal(-1, entity.Id);
Assert.Equal(-1, entry[keyProperty]);
}
[ConditionalTheory, InlineData(EntityState.Unchanged), InlineData(EntityState.Detached), InlineData(EntityState.Modified),
InlineData(EntityState.Added), InlineData(EntityState.Deleted)]
public void AcceptChanges_handles_different_entity_states_for_owned_types(EntityState entityState)
{
using var context = new KClrContext();
var ownerEntry = context.Entry(
new OwnerClass { Id = 1, Owned = new OwnedClass { Value = "Kool" } }).GetInfrastructure();
ownerEntry.SetEntityState(EntityState.Unchanged);
var entry = context.Entry(((OwnerClass)ownerEntry.Entity).Owned).GetInfrastructure();
var valueProperty = entry.EntityType.FindProperty(nameof(OwnedClass.Value));
entry.SetEntityState(entityState);
if (entityState != EntityState.Unchanged)
{
entry[valueProperty] = "Pickle";
}
entry.SetOriginalValue(valueProperty, "Cheese");
entry.AcceptChanges();
Assert.Equal(
entityState is EntityState.Deleted or EntityState.Detached
? EntityState.Detached
: EntityState.Unchanged,
entry.EntityState);
if (entityState == EntityState.Unchanged)
{
Assert.Equal("Kool", entry[valueProperty]);
Assert.Equal("Kool", entry.GetOriginalValue(valueProperty));
}
else
{
Assert.Equal("Pickle", entry[valueProperty]);
Assert.Equal(
entityState is EntityState.Detached or EntityState.Deleted ? "Cheese" : "Pickle",
entry.GetOriginalValue(valueProperty));
}
}
[ConditionalFact]
public void Setting_an_explicit_value_on_the_entity_does_not_mark_property_as_temporary()
{
using var context = new KClrContext();
var entry = context.Entry(new SomeEntity()).GetInfrastructure();
var keyProperty = entry.EntityType.FindProperty("Id");
var entity = (SomeEntity)entry.Entity;
entry.SetEntityState(EntityState.Added);
entry.SetTemporaryValue(keyProperty, -1);
Assert.True(entry.HasTemporaryValue(keyProperty));
entity.Id = 77;
context.GetService<IChangeDetector>().DetectChanges(entry);
Assert.False(entry.HasTemporaryValue(keyProperty));
entry.SetEntityState(EntityState.Unchanged); // Does not throw
var nameProperty = entry.EntityType.FindProperty(nameof(SomeEntity.Name));
Assert.False(entry.HasExplicitValue(nameProperty));
entity.Name = "Name";
Assert.True(entry.HasExplicitValue(nameProperty));
}
[ConditionalFact]
public void Setting_CLR_property_with_snapshot_change_tracking_requires_DetectChanges()
=> SetPropertyClrTest(
new SomeEntity { Id = 1, Name = "Kool" }, needsDetectChanges: true);
[ConditionalFact]
public void Setting_CLR_property_with_changed_only_notifications_does_not_require_DetectChanges()
=> SetPropertyClrTest(
new ChangedOnlyEntity { Id = 1, Name = "Kool" }, needsDetectChanges: false);
[ConditionalFact]
public void Setting_CLR_property_with_full_notifications_does_not_require_DetectChanges()
=> SetPropertyClrTest(
new FullNotificationEntity { Id = 1, Name = "Kool" }, needsDetectChanges: false);
private void SetPropertyClrTest<TEntity>(TEntity entity, bool needsDetectChanges)
where TEntity : class, ISomeEntity
{
using var context = new KClrContext();
var entry = context.Attach(entity).GetInfrastructure();
var nameProperty = entry.EntityType.FindProperty("Name");
Assert.False(entry.IsModified(nameProperty));
Assert.Equal(EntityState.Unchanged, entry.EntityState);
entity.Name = "Kool";
Assert.False(entry.IsModified(nameProperty));
Assert.Equal(EntityState.Unchanged, entry.EntityState);
entity.Name = "Beans";
if (needsDetectChanges)
{
Assert.False(entry.IsModified(nameProperty));
Assert.Equal(EntityState.Unchanged, entry.EntityState);
context.GetService<IChangeDetector>().DetectChanges(entry);
}
Assert.True(entry.IsModified(nameProperty));
Assert.Equal(EntityState.Modified, entry.EntityState);
}
|
InternalClrEntityEntryTest
|
csharp
|
dotnet__aspnetcore
|
src/Framework/AspNetCoreAnalyzers/src/Analyzers/RouteEmbeddedLanguage/FrameworkParametersCompletionProvider.cs
|
{
"start": 1407,
"end": 18188
}
|
public sealed class ____ : CompletionProvider
{
private const string StartKey = nameof(StartKey);
private const string LengthKey = nameof(LengthKey);
private const string NewTextKey = nameof(NewTextKey);
private const string NewPositionKey = nameof(NewPositionKey);
private const string DescriptionKey = nameof(DescriptionKey);
// Always soft-select these completion items. Also, never filter down.
private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(
selectionBehavior: CompletionItemSelectionBehavior.SoftSelection,
filterCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, Array.Empty<char>())));
// The space between type and parameter name.
// void TestMethod(int // <- space after type name
public ImmutableHashSet<char> TriggerCharacters { get; } = ImmutableHashSet.Create(' ');
public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
{
if (trigger.Kind is CompletionTriggerKind.Invoke or CompletionTriggerKind.InvokeAndCommitIfUnique)
{
return true;
}
if (trigger.Kind == CompletionTriggerKind.Insertion)
{
return TriggerCharacters.Contains(trigger.Character);
}
return false;
}
public override Task<CompletionDescription?> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
{
if (!item.Properties.TryGetValue(DescriptionKey, out var description))
{
return Task.FromResult<CompletionDescription?>(null);
}
return Task.FromResult<CompletionDescription?>(CompletionDescription.Create(
ImmutableArray.Create(new TaggedText(TextTags.Text, description))));
}
public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken)
{
// These values have always been added by us.
var startString = item.Properties[StartKey];
var lengthString = item.Properties[LengthKey];
var newText = item.Properties[NewTextKey];
// This value is optionally added in some cases and may not always be there.
item.Properties.TryGetValue(NewPositionKey, out var newPositionString);
return Task.FromResult(CompletionChange.Create(
new TextChange(new TextSpan(int.Parse(startString, CultureInfo.InvariantCulture), int.Parse(lengthString, CultureInfo.InvariantCulture)), newText),
newPositionString == null ? null : int.Parse(newPositionString, CultureInfo.InvariantCulture)));
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
var position = context.Position;
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root == null)
{
return;
}
SyntaxToken? parentOpt = null;
var token = root.FindTokenOnLeftOfPosition(position);
// If space is after ? or > then it's likely a nullable or generic type. Move to previous type token.
if (token.IsKind(SyntaxKind.QuestionToken) || token.IsKind(SyntaxKind.GreaterThanToken))
{
token = token.GetPreviousToken();
}
// Whitespace should follow the identifier token of the parameter.
if (!IsArgumentTypeToken(token))
{
return;
}
var container = TryFindMinimalApiArgument(token.Parent) ?? TryFindMvcActionParameter(token.Parent);
if (container == null)
{
return;
}
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
if (semanticModel == null)
{
return;
}
var wellKnownTypes = WellKnownTypes.GetOrCreate(semanticModel.Compilation);
// Don't offer route parameter names when the parameter type can't be bound to route parameters.
// e.g. special types like HttpContext, non-primitive types that don't have a static TryParse method.
if (!IsCurrentParameterBindable(token, semanticModel, wellKnownTypes, context.CancellationToken))
{
return;
}
// Don't offer route parameter names when the parameter has an attribute that can't be bound to route parameters.
// e.g [AsParameters] or [IFromBodyMetadata].
var hasNonRouteAttribute = HasNonRouteAttribute(token, semanticModel, wellKnownTypes, context.CancellationToken);
if (hasNonRouteAttribute)
{
return;
}
SyntaxToken routeStringToken;
SyntaxNode methodNode;
if (container.Parent.IsKind(SyntaxKind.Argument))
{
// Minimal API
var mapMethodParts = RouteUsageDetector.FindMapMethodParts(semanticModel, wellKnownTypes, container, context.CancellationToken);
if (mapMethodParts == null)
{
return;
}
var (_, routeStringExpression, delegateExpression) = mapMethodParts.Value;
routeStringToken = routeStringExpression.Token;
methodNode = delegateExpression;
// Incomplete inline delegate syntax is very messy and arguments are mixed together.
// Examine tokens to figure out whether the current token is the argument name.
var previous = token.GetPreviousToken();
if (previous.IsKind(SyntaxKind.CommaToken) ||
previous.IsKind(SyntaxKind.OpenParenToken) ||
previous.IsKind(SyntaxKind.OutKeyword) ||
previous.IsKind(SyntaxKind.InKeyword) ||
previous.IsKind(SyntaxKind.RefKeyword) ||
previous.IsKind(SyntaxKind.ParamsKeyword) ||
(previous.IsKind(SyntaxKind.CloseBracketToken) && previous.GetRequiredParent().FirstAncestorOrSelf<AttributeListSyntax>() != null) ||
(previous.IsKind(SyntaxKind.LessThanToken) && previous.GetRequiredParent().FirstAncestorOrSelf<GenericNameSyntax>() != null))
{
// Positioned after type token. Don't replace current.
}
else
{
// Space after argument name. Don't show completion options.
if (context.Trigger.Kind == CompletionTriggerKind.Insertion)
{
return;
}
parentOpt = token;
}
}
else if (container.IsKind(SyntaxKind.Parameter))
{
// MVC
var methodSyntax = container.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (methodSyntax == null)
{
return;
}
var methodSymbol = semanticModel.GetDeclaredSymbol(methodSyntax, context.CancellationToken);
// Check method is a valid MVC action.
if (methodSymbol?.ContainingType is not INamedTypeSymbol typeSymbol ||
!MvcDetector.IsController(typeSymbol, wellKnownTypes) ||
!MvcDetector.IsAction(methodSymbol, wellKnownTypes))
{
return;
}
var routeToken = TryGetMvcActionRouteToken(context, semanticModel, methodSyntax);
if (routeToken == null)
{
return;
}
routeStringToken = routeToken.Value;
methodNode = methodSyntax;
if (((ParameterSyntax)container).Identifier == token)
{
// Space after argument name. Don't show completion options.
if (context.Trigger.Kind == CompletionTriggerKind.Insertion)
{
return;
}
parentOpt = token;
}
}
else
{
return;
}
var routeUsageCache = RouteUsageCache.GetOrCreate(semanticModel.Compilation);
var routeUsage = routeUsageCache.Get(routeStringToken, context.CancellationToken);
if (routeUsage is null)
{
return;
}
var routePatternCompletionContext = new EmbeddedCompletionContext(context, routeUsage.RoutePattern);
var existingParameterNames = GetExistingParameterNames(methodNode);
foreach (var parameterName in existingParameterNames)
{
routePatternCompletionContext.AddUsedParameterName(parameterName);
}
ProvideCompletions(routePatternCompletionContext, parentOpt);
if (routePatternCompletionContext.Items == null || routePatternCompletionContext.Items.Count == 0)
{
return;
}
foreach (var embeddedItem in routePatternCompletionContext.Items)
{
var change = embeddedItem.Change;
var textChange = change.TextChange;
var properties = ImmutableDictionary.CreateBuilder<string, string>();
properties.Add(StartKey, textChange.Span.Start.ToString(CultureInfo.InvariantCulture));
properties.Add(LengthKey, textChange.Span.Length.ToString(CultureInfo.InvariantCulture));
properties.Add(NewTextKey, textChange.NewText ?? string.Empty);
properties.Add(DescriptionKey, embeddedItem.FullDescription);
if (change.NewPosition != null)
{
properties.Add(NewPositionKey, change.NewPosition.Value.ToString(CultureInfo.InvariantCulture));
}
// Keep everything sorted in the order we just produced the items in.
var sortText = routePatternCompletionContext.Items.Count.ToString("0000", CultureInfo.InvariantCulture);
context.AddItem(CompletionItem.Create(
displayText: embeddedItem.DisplayText,
inlineDescription: "",
sortText: sortText,
properties: properties.ToImmutable(),
rules: s_rules,
tags: ImmutableArray.Create(embeddedItem.Glyph)));
}
context.SuggestionModeItem = CompletionItem.Create(
displayText: "<Name>",
inlineDescription: "",
rules: CompletionItemRules.Default);
context.IsExclusive = true;
}
private static bool IsArgumentTypeToken(SyntaxToken token)
{
return SyntaxFacts.IsPredefinedType(token.Kind()) || token.IsKind(SyntaxKind.IdentifierToken);
}
private static SyntaxToken? TryGetMvcActionRouteToken(CompletionContext context, SemanticModel semanticModel, MethodDeclarationSyntax method)
{
foreach (var attributeList in method.AttributeLists)
{
foreach (var attribute in attributeList.Attributes)
{
if (attribute.ArgumentList != null)
{
foreach (var attributeArgument in attribute.ArgumentList.Arguments)
{
if (RouteStringSyntaxDetector.IsArgumentToAttributeParameterWithMatchingStringSyntaxAttribute(
semanticModel,
attributeArgument,
context.CancellationToken,
out var identifer) &&
identifer == "Route" &&
attributeArgument.Expression is LiteralExpressionSyntax literalExpression)
{
return literalExpression.Token;
}
}
}
}
}
return null;
}
private static SyntaxNode? TryFindMvcActionParameter(SyntaxNode? node)
{
var current = node;
while (current != null)
{
if (current.IsKind(SyntaxKind.Parameter))
{
return current;
}
current = current.Parent;
}
return null;
}
private static SyntaxNode? TryFindMinimalApiArgument(SyntaxNode? node)
{
var current = node;
while (current != null)
{
if (current.Parent?.IsKind(SyntaxKind.Argument) ?? false)
{
if (current.Parent?.Parent?.IsKind(SyntaxKind.ArgumentList) ?? false)
{
return current;
}
}
current = current.Parent;
}
return null;
}
private static bool HasNonRouteAttribute(SyntaxToken token, SemanticModel semanticModel, WellKnownTypes wellKnownTypes, CancellationToken cancellationToken)
{
if (token.Parent?.Parent is ParameterSyntax parameter)
{
foreach (var attributeList in parameter.AttributeLists.OfType<AttributeListSyntax>())
{
foreach (var attribute in attributeList.Attributes)
{
var attributeTypeSymbol = semanticModel.GetSymbolInfo(attribute, cancellationToken).GetAnySymbol();
if (attributeTypeSymbol != null)
{
if (attributeTypeSymbol.ContainingSymbol is ITypeSymbol typeSymbol &&
wellKnownTypes.Implements(typeSymbol, RouteWellKnownTypes.NonRouteMetadataTypes))
{
return true;
}
if (SymbolEqualityComparer.Default.Equals(attributeTypeSymbol.ContainingSymbol, wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Http_AsParametersAttribute)))
{
return true;
}
}
}
}
}
return false;
}
private static bool IsCurrentParameterBindable(SyntaxToken token, SemanticModel semanticModel, WellKnownTypes wellKnownTypes, CancellationToken cancellationToken)
{
if (token.Parent.IsKind(SyntaxKind.PredefinedType))
{
return true;
}
var parameterTypeSymbol = semanticModel.GetSymbolInfo(token.Parent!, cancellationToken).GetAnySymbol();
if (parameterTypeSymbol is INamedTypeSymbol typeSymbol)
{
return ParsabilityHelper.GetParsability(typeSymbol, wellKnownTypes) == Parsability.Parsable;
}
else if (parameterTypeSymbol is IMethodSymbol)
{
// If the parameter type is a method then the method is bound to the minimal API.
return false;
}
// The cursor is on an identifier (parameter name) and completion is explicitly triggered (e.g. CTRL+SPACE)
return true;
}
private static ImmutableArray<string> GetExistingParameterNames(SyntaxNode node)
{
var builder = ImmutableArray.CreateBuilder<string>();
if (node is TupleExpressionSyntax tupleExpression)
{
foreach (var argument in tupleExpression.Arguments)
{
if (argument.Expression is DeclarationExpressionSyntax declarationExpression &&
declarationExpression.Designation is SingleVariableDesignationSyntax variableDesignationSyntax &&
variableDesignationSyntax.Identifier is { IsMissing: false } identifer)
{
builder.Add(identifer.ValueText);
}
}
}
else
{
var parameterList = node switch
{
ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpression => parenthesizedLambdaExpression.ParameterList,
MethodDeclarationSyntax methodDeclaration => methodDeclaration.ParameterList,
_ => null
};
if (parameterList != null)
{
foreach (var p in parameterList.Parameters)
{
if (p is ParameterSyntax parameter &&
parameter.Identifier is { IsMissing: false } identifer)
{
builder.Add(identifer.ValueText);
}
}
}
}
return builder.ToImmutable();
}
private static void ProvideCompletions(EmbeddedCompletionContext context, SyntaxToken? parentOpt)
{
foreach (var routeParameter in context.Tree.RouteParameters)
{
context.AddIfMissing(routeParameter.Name, suffix: string.Empty, description: "(Route parameter)", WellKnownTags.Parameter, parentOpt);
}
}
private readonly
|
FrameworkParametersCompletionProvider
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.Transforms/MissingValueIndicatorTransformer.cs
|
{
"start": 23149,
"end": 26400
}
|
public sealed class ____ : TrivialEstimator<MissingValueIndicatorTransformer>
{
/// <summary>
/// Initializes a new instance of <see cref="MissingValueIndicatorEstimator"/>
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="columns">The names of the input columns of the transformation and the corresponding names for the output columns.</param>
internal MissingValueIndicatorEstimator(IHostEnvironment env, params (string outputColumnName, string inputColumnName)[] columns)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(MissingValueIndicatorTransformer)), new MissingValueIndicatorTransformer(env, columns))
{
Contracts.CheckValue(env, nameof(env));
}
/// <summary>
/// Initializes a new instance of <see cref="MissingValueIndicatorEstimator"/>
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="outputColumnName">Name of the column resulting from the transformation of <paramref name="inputColumnName"/>.</param>
/// <param name="inputColumnName">Name of the column to transform. If set to <see langword="null"/>, the value of the <paramref name="outputColumnName"/> will be used as source.</param>
internal MissingValueIndicatorEstimator(IHostEnvironment env, string outputColumnName, string inputColumnName = null)
: this(env, (outputColumnName, inputColumnName ?? outputColumnName))
{
}
/// <summary>
/// Returns the <see cref="SchemaShape"/> of the schema which will be produced by the transformer.
/// Used for schema propagation and verification in a pipeline.
/// </summary>
public override SchemaShape GetOutputSchema(SchemaShape inputSchema)
{
Host.CheckValue(inputSchema, nameof(inputSchema));
var result = inputSchema.ToDictionary(x => x.Name);
foreach (var colPair in Transformer.Columns)
{
if (!inputSchema.TryFindColumn(colPair.inputColumnName, out var col) || !Data.Conversion.Conversions.DefaultInstance.TryGetIsNAPredicate(col.ItemType, out Delegate del))
throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", colPair.inputColumnName);
var metadata = new List<SchemaShape.Column>();
if (col.Annotations.TryFindColumn(AnnotationUtils.Kinds.SlotNames, out var slotMeta))
metadata.Add(slotMeta);
metadata.Add(new SchemaShape.Column(AnnotationUtils.Kinds.IsNormalized, SchemaShape.Column.VectorKind.Scalar, BooleanDataViewType.Instance, false));
DataViewType type = !(col.ItemType is VectorDataViewType vectorType) ?
(DataViewType)BooleanDataViewType.Instance :
new VectorDataViewType(BooleanDataViewType.Instance, vectorType.Dimensions);
result[colPair.outputColumnName] = new SchemaShape.Column(colPair.outputColumnName, col.Kind, type, false, new SchemaShape(metadata.ToArray()));
}
return new SchemaShape(result.Values);
}
}
}
|
MissingValueIndicatorEstimator
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Redis/tests/ServiceStack.Redis.Tests/Shared/Movie.cs
|
{
"start": 180,
"end": 2173
}
|
public class ____
{
public Movie()
{
this.Genres = new List<string>();
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public decimal Rating { get; set; }
[DataMember]
public string Director { get; set; }
[DataMember]
public DateTime ReleaseDate { get; set; }
[DataMember]
public string TagLine { get; set; }
[DataMember]
public List<string> Genres { get; set; }
public bool Equals(Movie other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Id, Id) && Equals(other.Title, Title) && other.Rating == Rating && Equals(other.Director, Director) && other.ReleaseDate.Equals(ReleaseDate) && Equals(other.TagLine, TagLine) && Genres.EquivalentTo(other.Genres);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Movie)) return false;
return Equals((Movie)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (Id != null ? Id.GetHashCode() : 0);
result = (result * 397) ^ (Title != null ? Title.GetHashCode() : 0);
result = (result * 397) ^ Rating.GetHashCode();
result = (result * 397) ^ (Director != null ? Director.GetHashCode() : 0);
result = (result * 397) ^ ReleaseDate.GetHashCode();
result = (result * 397) ^ (TagLine != null ? TagLine.GetHashCode() : 0);
result = (result * 397) ^ (Genres != null ? Genres.GetHashCode() : 0);
return result;
}
}
}
}
|
Movie
|
csharp
|
dotnet__orleans
|
src/Orleans.TestingHost/TestStorageProviders/StorageFaultGrain.cs
|
{
"start": 345,
"end": 2783
}
|
public class ____ : Grain, IStorageFaultGrain
{
private ILogger logger;
private Dictionary<GrainId, Exception> readFaults;
private Dictionary<GrainId, Exception> writeFaults;
private Dictionary<GrainId, Exception> clearfaults;
/// <inheritdoc />
public override async Task OnActivateAsync(CancellationToken cancellationToken)
{
await base.OnActivateAsync(cancellationToken);
logger = this.ServiceProvider.GetService<ILoggerFactory>().CreateLogger($"{typeof (StorageFaultGrain).FullName}-{IdentityString}-{RuntimeIdentity}");
readFaults = new();
writeFaults = new();
clearfaults = new();
logger.LogInformation("Activate.");
}
/// <inheritdoc />
public Task AddFaultOnRead(GrainId grainId, Exception exception)
{
readFaults.Add(grainId, exception);
logger.LogInformation("Added ReadState fault for {GrainId}.", GrainId);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task AddFaultOnWrite(GrainId grainId, Exception exception)
{
writeFaults.Add(grainId, exception);
logger.LogInformation("Added WriteState fault for {GrainId}.", GrainId);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task AddFaultOnClear(GrainId grainId, Exception exception)
{
clearfaults.Add(grainId, exception);
logger.LogInformation("Added ClearState fault for {GrainId}.", GrainId);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task OnRead(GrainId grainId)
{
if (readFaults.Remove(grainId, out var exception))
{
throw exception;
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task OnWrite(GrainId grainId)
{
if (writeFaults.Remove(grainId, out var exception))
{
throw exception;
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task OnClear(GrainId grainId)
{
if (clearfaults.Remove(grainId, out var exception))
{
throw exception;
}
return Task.CompletedTask;
}
}
}
|
StorageFaultGrain
|
csharp
|
dotnet__machinelearning
|
docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/Conversion/MapValueToArray.cs
|
{
"start": 3093,
"end": 3195
}
|
public class ____
{
public string Timeframe { get; set; }
}
|
DataPoint
|
csharp
|
spectreconsole__spectre.console
|
docs/src/Shortcodes/ExampleSnippet.cs
|
{
"start": 230,
"end": 1592
}
|
public class ____ : Shortcode
{
protected const string Solution = nameof(Solution);
protected const string Project = nameof(Project);
protected const string Symbol = nameof(Symbol);
protected const string BodyOnly = nameof(BodyOnly);
public override async Task<ShortcodeResult> ExecuteAsync(KeyValuePair<string, string>[] args, string content,
IDocument document, IExecutionContext context)
{
var props = args.ToDictionary(Solution, Project, Symbol, BodyOnly);
var symbolName = props.GetString(Symbol);
var bodyOnly = props.Get<bool?>(BodyOnly) ?? symbolName.StartsWith("m:", StringComparison.InvariantCultureIgnoreCase);
if (!context.TryGetCommentIdDocument(symbolName, out var apiDocument, out _))
{
return string.Empty;
}
var options = HighlightService.HighlightOption.All;
if (bodyOnly)
{
options = HighlightService.HighlightOption.Body;
}
var comp = apiDocument.Get<Compilation>(CodeAnalysisKeys.Compilation);
var symbol = apiDocument.Get<ISymbol>(CodeAnalysisKeys.Symbol);
var highlightElement = await HighlightService.Highlight(comp, symbol, options);
ShortcodeResult shortcodeResult = $"<pre><code>{highlightElement}</code></pre>";
return shortcodeResult;
}
}
|
ExampleSnippet
|
csharp
|
protobuf-net__protobuf-net
|
src/Examples/Rpc/HttpBasic.cs
|
{
"start": 3883,
"end": 6626
}
|
class ____ { }
// [Fact, ExpectedException(typeof(ArgumentException))]
// public void TestNotAContract() {
// new ProtoClient<NotAContract>(ViaHttp());
// }
// [Fact]
// public void TestCreationAndDispoesWithBoth() {
// using(ClientViaHttp<IBasicService>()) {}
// }
// [Fact]
// public void TestCreateDisposeClient()
// {
// using (var client = new BasicServiceHttpClient()) { }
// }
// [Fact]
// public void StartStopServer()
// {
// using (var server = CreateServer())
// {
// server.Start();
// server.Close();
// }
// }
// static HttpServer CreateServer() { return CreateServer(new BasicService()); }
// static HttpServer CreateServer(IBasicService service)
// {
// HttpServer server = new HttpServer(HTTP_PREFIX);
// server.Add<IBasicService>(service);
// return server;
// }
// [Fact]
// public void TestCallTestMethodWithNull()
// {
// using (var server = CreateServer())
// using (var client = new BasicServiceHttpClient())
// {
// server.Start();
// var result = client.TestMethod(null);
// Assert.Null(result);
// }
// }
// [Fact]
// public void TestCallTestMethodWithDatabase()
// {
// using (var server = CreateServer())
// using (var client = new BasicServiceHttpClient())
// {
// server.Start();
// DAL.Database request = NWindTests.LoadDatabaseFromFile<DAL.Database>();
// DAL.Database response = client.TestMethod(request);
// Assert.NotNull(response);
// Assert.NotSame(request, response);
// Assert.Equal(request.Orders.Count, response.Orders.Count, "Orders");
// Assert.Equal(
// request.Orders.SelectMany(ord => ord.Lines).Count(),
// response.Orders.SelectMany(ord => ord.Lines).Count(), "Lines");
// Assert.Equal(
// request.Orders.SelectMany(ord => ord.Lines).Sum(line => line.Quantity),
// response.Orders.SelectMany(ord => ord.Lines).Sum(line => line.Quantity), "Quantity");
// Assert.Equal(
// request.Orders.SelectMany(ord => ord.Lines).Sum(line => line.Quantity * line.UnitPrice),
// response.Orders.SelectMany(ord => ord.Lines).Sum(line => line.Quantity * line.UnitPrice), "Value");
// }
// }
// }
//}
|
NotAContract
|
csharp
|
dotnet__maui
|
src/Essentials/src/WebAuthenticator/AppleSignInAuthenticator.netstandard.android.tvos.watchos.windows.tizen.macos.cs
|
{
"start": 113,
"end": 363
}
|
partial class ____ : IAppleSignInAuthenticator
{
public Task<WebAuthenticatorResult> AuthenticateAsync(AppleSignInAuthenticator.Options options) =>
throw ExceptionUtils.NotSupportedOrImplementedException;
}
}
|
AppleSignInAuthenticatorImplementation
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit.TestFramework/Logging/TestOutputLoggerFactory.cs
|
{
"start": 128,
"end": 687
}
|
public class ____ :
ILoggerFactory
{
readonly bool _enabled;
public TestOutputLoggerFactory(bool enabled)
{
_enabled = enabled;
}
public TestExecutionContext Current { get; set; }
public Microsoft.Extensions.Logging.ILogger CreateLogger(string name)
{
return new TestOutputLogger(this, _enabled);
}
public void AddProvider(ILoggerProvider provider)
{
}
public void Dispose()
{
}
}
}
|
TestOutputLoggerFactory
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/CheckWeb/Test.dtos.cs
|
{
"start": 4623,
"end": 4739
}
|
public partial class ____
: IReturn<CustomUserSession>
{
}
[Route("/info/{Id}")]
|
GetUserSession
|
csharp
|
nuke-build__nuke
|
source/Nuke.Common/Tools/GitLink/GitLink.Generated.cs
|
{
"start": 29400,
"end": 29821
}
|
public partial class ____ : Enumeration
{
public static GitLinkSourceCodeRetrieval Http = (GitLinkSourceCodeRetrieval) "Http";
public static GitLinkSourceCodeRetrieval Powershell = (GitLinkSourceCodeRetrieval) "Powershell";
public static implicit operator GitLinkSourceCodeRetrieval(string value)
{
return new GitLinkSourceCodeRetrieval { Value = value };
}
}
#endregion
|
GitLinkSourceCodeRetrieval
|
csharp
|
exceptionless__Exceptionless
|
src/Exceptionless.Core/Repositories/Configuration/Indexes/StackIndex.cs
|
{
"start": 4713,
"end": 5743
}
|
public class ____
{
public const string Stack = "stack";
public const string Status = "status";
public const string OrganizationId = "organization";
public const string ProjectId = "project";
public const string SignatureHash = "signature";
public const string Type = "type";
public const string FirstOccurrence = "first";
public const string LastOccurrence = "last";
public const string Title = "title";
public const string Description = "description";
public const string Tags = "tag";
public const string References = "links";
public const string DateFixed = "fixedon";
public const string IsFixed = "fixed";
public const string FixedInVersion = "version_fixed";
public const string IsHidden = "hidden";
public const string IsRegressed = "regressed";
public const string OccurrencesAreCritical = "critical";
public const string TotalOccurrences = "occurrences";
}
}
|
Alias
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Bugzilla/Bugzilla37841.cs
|
{
"start": 115,
"end": 871
}
|
public class ____ : _IssuesUITest
{
const string Generate = "Generate";
const string entrycell = "entrycell";
const string textcell = "textcell";
public Bugzilla37841(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "TableView EntryCells and TextCells cease to update after focus change";
[Test]
[Category(UITestCategories.TableView)]
public void TextAndEntryCellsDataBindInTableView()
{
App.WaitForElement(Generate);
App.Tap(Generate);
App.WaitForTextToBePresentInElement(entrycell, "12345");
App.WaitForTextToBePresentInElement(textcell, "6789");
App.Tap(Generate);
App.WaitForTextToBePresentInElement(entrycell, "112358");
App.WaitForTextToBePresentInElement(textcell, "48151623");
}
}
|
Bugzilla37841
|
csharp
|
dotnet__maui
|
src/Compatibility/Core/src/Windows/CollectionView/StructuredItemsViewRenderer.cs
|
{
"start": 557,
"end": 7729
}
|
public partial class ____<TItemsView> : ItemsViewRenderer<TItemsView>
where TItemsView : StructuredItemsView
{
View _currentHeader;
View _currentFooter;
protected override IItemsLayout Layout { get => ItemsView?.ItemsLayout; }
protected override void SetUpNewElement(ItemsView newElement)
{
base.SetUpNewElement(newElement);
if (newElement == null)
{
return;
}
UpdateHeader();
UpdateFooter();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs changedProperty)
{
base.OnElementPropertyChanged(sender, changedProperty);
if (changedProperty.IsOneOf(StructuredItemsView.HeaderProperty, StructuredItemsView.HeaderTemplateProperty))
{
UpdateHeader();
}
else if (changedProperty.IsOneOf(StructuredItemsView.FooterProperty, StructuredItemsView.FooterTemplateProperty))
{
UpdateFooter();
}
else if (changedProperty.Is(StructuredItemsView.ItemsLayoutProperty))
{
UpdateItemsLayout();
}
}
protected override ListViewBase SelectListViewBase()
{
switch (Layout)
{
case GridItemsLayout gridItemsLayout:
return CreateGridView(gridItemsLayout);
case LinearItemsLayout listItemsLayout when listItemsLayout.Orientation == ItemsLayoutOrientation.Vertical:
return CreateVerticalListView(listItemsLayout);
case LinearItemsLayout listItemsLayout when listItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal:
return CreateHorizontalListView(listItemsLayout);
}
throw new NotImplementedException("The layout is not implemented");
}
protected virtual void UpdateHeader()
{
if (ListViewBase == null)
{
return;
}
if (_currentHeader != null)
{
Element.RemoveLogicalChild(_currentHeader);
_currentHeader = null;
}
var header = ItemsView.Header;
switch (header)
{
case null:
ListViewBase.Header = null;
break;
case string text:
ListViewBase.HeaderTemplate = null;
ListViewBase.Header = new TextBlock { Text = text };
break;
case View view:
ListViewBase.HeaderTemplate = ViewTemplate;
_currentHeader = view;
Element.AddLogicalChild(_currentHeader);
ListViewBase.Header = view;
break;
default:
var headerTemplate = ItemsView.HeaderTemplate;
if (headerTemplate != null)
{
ListViewBase.HeaderTemplate = ItemsViewTemplate;
ListViewBase.Header = new ItemTemplateContext(headerTemplate, header, Element);
}
else
{
ListViewBase.HeaderTemplate = null;
ListViewBase.Header = null;
}
break;
}
}
protected virtual void UpdateFooter()
{
if (ListViewBase == null)
{
return;
}
if (_currentFooter != null)
{
Element.RemoveLogicalChild(_currentFooter);
_currentFooter = null;
}
var footer = ItemsView.Footer;
switch (footer)
{
case null:
ListViewBase.Footer = null;
break;
case string text:
ListViewBase.FooterTemplate = null;
ListViewBase.Footer = new TextBlock { Text = text };
break;
case View view:
ListViewBase.FooterTemplate = ViewTemplate;
_currentFooter = view;
Element.AddLogicalChild(_currentFooter);
ListViewBase.Footer = view;
break;
default:
var footerTemplate = ItemsView.FooterTemplate;
if (footerTemplate != null)
{
ListViewBase.FooterTemplate = ItemsViewTemplate;
ListViewBase.Footer = new ItemTemplateContext(footerTemplate, footer, Element);
}
else
{
ListViewBase.FooterTemplate = null;
ListViewBase.Footer = null;
}
break;
}
}
protected override void HandleLayoutPropertyChanged(PropertyChangedEventArgs property)
{
if (property.Is(GridItemsLayout.SpanProperty))
{
if (ListViewBase is FormsGridView formsGridView)
{
formsGridView.Span = ((GridItemsLayout)Layout).Span;
}
}
else if (property.Is(GridItemsLayout.HorizontalItemSpacingProperty) || property.Is(GridItemsLayout.VerticalItemSpacingProperty))
{
if (ListViewBase is FormsGridView formsGridView)
{
formsGridView.ItemContainerStyle = GetItemContainerStyle((GridItemsLayout)Layout);
}
}
else if (property.Is(LinearItemsLayout.ItemSpacingProperty))
{
switch (ListViewBase)
{
case FormsListView formsListView:
formsListView.ItemContainerStyle = GetVerticalItemContainerStyle((LinearItemsLayout)Layout);
break;
case WListView listView:
listView.ItemContainerStyle = GetHorizontalItemContainerStyle((LinearItemsLayout)Layout);
break;
}
}
}
static ListViewBase CreateGridView(GridItemsLayout gridItemsLayout)
{
return new FormsGridView
{
Orientation = gridItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal
? Orientation.Horizontal
: Orientation.Vertical,
Span = gridItemsLayout.Span,
ItemContainerStyle = GetItemContainerStyle(gridItemsLayout)
};
}
static ListViewBase CreateVerticalListView(LinearItemsLayout listItemsLayout)
{
return new FormsListView()
{
ItemContainerStyle = GetVerticalItemContainerStyle(listItemsLayout)
};
}
static ListViewBase CreateHorizontalListView(LinearItemsLayout listItemsLayout)
{
var horizontalListView = new FormsListView()
{
ItemsPanel = (ItemsPanelTemplate)UWPApp.Current.Resources["HorizontalListItemsPanel"],
ItemContainerStyle = GetHorizontalItemContainerStyle(listItemsLayout)
};
ScrollViewer.SetVerticalScrollBarVisibility(horizontalListView, Microsoft.UI.Xaml.Controls.ScrollBarVisibility.Hidden);
ScrollViewer.SetVerticalScrollMode(horizontalListView, WScrollMode.Disabled);
ScrollViewer.SetHorizontalScrollMode(horizontalListView, WScrollMode.Auto);
ScrollViewer.SetHorizontalScrollBarVisibility(horizontalListView, Microsoft.UI.Xaml.Controls.ScrollBarVisibility.Auto);
return horizontalListView;
}
static WStyle GetItemContainerStyle(GridItemsLayout layout)
{
var h = layout?.HorizontalItemSpacing ?? 0;
var v = layout?.VerticalItemSpacing ?? 0;
var margin = WinUIHelpers.CreateThickness(h, v, h, v);
var style = new WStyle(typeof(GridViewItem));
style.Setters.Add(new WSetter(GridViewItem.MarginProperty, margin));
style.Setters.Add(new WSetter(GridViewItem.PaddingProperty, WinUIHelpers.CreateThickness(0)));
return style;
}
static WStyle GetVerticalItemContainerStyle(LinearItemsLayout layout)
{
var v = layout?.ItemSpacing ?? 0;
var margin = WinUIHelpers.CreateThickness(0, v, 0, v);
var style = new WStyle(typeof(ListViewItem));
style.Setters.Add(new WSetter(ListViewItem.MarginProperty, margin));
style.Setters.Add(new WSetter(GridViewItem.PaddingProperty, WinUIHelpers.CreateThickness(0)));
return style;
}
static WStyle GetHorizontalItemContainerStyle(LinearItemsLayout layout)
{
var h = layout?.ItemSpacing ?? 0;
var padding = WinUIHelpers.CreateThickness(h, 0, h, 0);
var style = new WStyle(typeof(ListViewItem));
style.Setters.Add(new WSetter(ListViewItem.PaddingProperty, padding));
return style;
}
}
}
|
StructuredItemsViewRenderer
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaConfigurationTests.cs
|
{
"start": 107,
"end": 1623
}
|
public class ____
{
[Fact]
public void BindResolverCollectionToObjectTypeImplicitly()
{
// arrange
// act
var schema = SchemaBuilder.New()
.AddQueryType(d =>
{
d.Name("TestObjectA");
d.Field("a").Type<StringType>();
d.Field("b").Type<StringType>();
})
.AddResolver<TestResolverCollectionA>("TestObjectA")
.Create();
// assert
var type = schema.Types.GetType<ObjectType>("TestObjectA");
Assert.NotNull(type.Fields["a"].Resolver);
Assert.NotNull(type.Fields["b"].Resolver);
}
[Fact]
public async Task DeriveResolverFromObjectTypeMethod()
{
// arrange
var dummyObjectType = new TestObjectB();
var resolverContext = new Mock<IResolverContext>();
resolverContext.Setup(t => t.Parent<TestObjectB>()).Returns(dummyObjectType);
const string source = "type Dummy { bar2: String }";
// act
var schema = SchemaBuilder.New()
.AddQueryType<DummyQuery>()
.AddDocumentFromString(source)
.BindRuntimeType<TestObjectB>("Dummy")
.Create();
// assert
var dummy = schema.Types.GetType<ObjectType>("Dummy");
var fieldResolver = dummy.Fields["bar2"].Resolver;
var result = await fieldResolver!(resolverContext.Object);
Assert.Equal(dummyObjectType.GetBar2(), result);
}
}
|
SchemaConfigurationTests
|
csharp
|
dotnet__BenchmarkDotNet
|
src/BenchmarkDotNet/Toolchains/GeneratorBase.cs
|
{
"start": 419,
"end": 7538
}
|
public abstract class ____ : IGenerator
{
public GenerateResult GenerateProject(BuildPartition buildPartition, ILogger logger, string rootArtifactsFolderPath)
{
var artifactsPaths = ArtifactsPaths.Empty;
try
{
artifactsPaths = GetArtifactsPaths(buildPartition, rootArtifactsFolderPath);
CopyAllRequiredFiles(artifactsPaths);
GenerateCode(buildPartition, artifactsPaths);
GenerateAppConfig(buildPartition, artifactsPaths);
GenerateNuGetConfig(artifactsPaths);
GenerateProject(buildPartition, artifactsPaths, logger);
GenerateBuildScript(buildPartition, artifactsPaths);
return GenerateResult.Success(artifactsPaths, GetArtifactsToCleanup(artifactsPaths));
}
catch (Exception ex)
{
return GenerateResult.Failure(artifactsPaths, GetArtifactsToCleanup(artifactsPaths), ex);
}
}
/// <summary>
/// returns a path to the folder where auto-generated project and code are going to be placed
/// </summary>
[PublicAPI] protected abstract string GetBuildArtifactsDirectoryPath(BuildPartition assemblyLocation, string programName);
/// <summary>
/// returns a path where executable should be found after the build (usually \bin)
/// </summary>
[PublicAPI] protected virtual string GetBinariesDirectoryPath(string buildArtifactsDirectoryPath, string configuration)
=> buildArtifactsDirectoryPath;
/// <summary>
/// returns a path where the publish directory should be found after the build (usually \publish)
/// </summary>
[PublicAPI]
protected virtual string GetPublishDirectoryPath(string buildArtifactsDirectoryPath, string configuration)
=> Path.Combine(buildArtifactsDirectoryPath, "publish");
/// <summary>
/// returns OS-specific executable extension
/// </summary>
[PublicAPI] protected virtual string GetExecutableExtension()
=> OsDetector.ExecutableExtension;
/// <summary>
/// returns a path to the auto-generated .csproj file
/// </summary>
[PublicAPI] protected virtual string GetProjectFilePath(string buildArtifactsDirectoryPath)
=> string.Empty;
/// <summary>
/// returns a list of artifacts that should be removed after running the benchmarks
/// </summary>
[PublicAPI] protected abstract string[] GetArtifactsToCleanup(ArtifactsPaths artifactsPaths);
/// <summary>
/// if you need to copy some extra files to make the benchmarks work you should override this method
/// </summary>
[PublicAPI] protected virtual void CopyAllRequiredFiles(ArtifactsPaths artifactsPaths) { }
/// <summary>
/// generates NuGet.Config file to make sure that BDN is using the right NuGet feeds
/// </summary>
[PublicAPI] protected virtual void GenerateNuGetConfig(ArtifactsPaths artifactsPaths) { }
/// <summary>
/// generates .csproj file with a reference to the project with benchmarks
/// </summary>
[PublicAPI] protected virtual void GenerateProject(BuildPartition buildPartition, ArtifactsPaths artifactsPaths, ILogger logger) { }
/// <summary>
/// generates a script can be used when debugging compilation issues
/// </summary>
[PublicAPI] protected abstract void GenerateBuildScript(BuildPartition buildPartition, ArtifactsPaths artifactsPaths);
/// <summary>
/// returns a path to the folder where NuGet packages should be restored
/// </summary>
[PublicAPI] protected virtual string GetPackagesDirectoryPath(string buildArtifactsDirectoryPath) => default;
/// <summary>
/// generates an app.config file next to the executable with benchmarks
/// </summary>
[PublicAPI] protected virtual void GenerateAppConfig(BuildPartition buildPartition, ArtifactsPaths artifactsPaths)
{
string sourcePath = buildPartition.AssemblyLocation + ".config";
artifactsPaths.AppConfigPath.EnsureFolderExists();
using (var source = File.Exists(sourcePath) ? new StreamReader(File.OpenRead(sourcePath)) : TextReader.Null)
using (var destination = new StreamWriter(File.Create(artifactsPaths.AppConfigPath), Encoding.UTF8))
{
AppConfigGenerator.Generate(buildPartition.RepresentativeBenchmarkCase.Job, source, destination, buildPartition.Resolver);
}
}
/// <summary>
/// generates the C# source code with all required boilerplate.
/// <remarks>You most probably do NOT need to override this method!!</remarks>
/// </summary>
[PublicAPI] protected virtual void GenerateCode(BuildPartition buildPartition, ArtifactsPaths artifactsPaths)
=> File.WriteAllText(artifactsPaths.ProgramCodePath, CodeGenerator.Generate(buildPartition));
protected virtual string GetExecutablePath(string binariesDirectoryPath, string programName) => Path.Combine(binariesDirectoryPath, $"{programName}{GetExecutableExtension()}");
private ArtifactsPaths GetArtifactsPaths(BuildPartition buildPartition, string rootArtifactsFolderPath)
{
// its not ".cs" in order to avoid VS from displaying and compiling it with xprojs/csprojs that include all *.cs by default
const string codeFileExtension = ".notcs";
string programName = buildPartition.ProgramName;
string buildArtifactsDirectoryPath = GetBuildArtifactsDirectoryPath(buildPartition, programName);
string binariesDirectoryPath = GetBinariesDirectoryPath(buildArtifactsDirectoryPath, buildPartition.BuildConfiguration);
string executablePath = GetExecutablePath(binariesDirectoryPath, programName);
return new ArtifactsPaths(
rootArtifactsFolderPath: rootArtifactsFolderPath,
buildArtifactsDirectoryPath: buildArtifactsDirectoryPath,
binariesDirectoryPath: binariesDirectoryPath,
publishDirectoryPath: GetPublishDirectoryPath(buildArtifactsDirectoryPath, buildPartition.BuildConfiguration),
programCodePath: Path.Combine(buildArtifactsDirectoryPath, $"{programName}{codeFileExtension}"),
appConfigPath: $"{executablePath}.config",
nuGetConfigPath: Path.Combine(buildArtifactsDirectoryPath, "NuGet.config"),
projectFilePath: GetProjectFilePath(buildArtifactsDirectoryPath),
buildScriptFilePath: Path.Combine(buildArtifactsDirectoryPath, $"{programName}{OsDetector.ScriptFileExtension}"),
executablePath: executablePath,
programName: programName,
packagesDirectoryName: GetPackagesDirectoryPath(buildArtifactsDirectoryPath));
}
}
}
|
GeneratorBase
|
csharp
|
graphql-dotnet__graphql-dotnet
|
src/GraphQL.Tests/Bugs/ScalarsInputTest.cs
|
{
"start": 5270,
"end": 5431
}
|
public class ____ : Schema
{
public SchemaForScalars()
{
Query = new DummyType();
Mutation = new ScalarsMutation();
}
}
|
SchemaForScalars
|
csharp
|
icsharpcode__ILSpy
|
ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs
|
{
"start": 2095,
"end": 4271
}
|
internal struct ____
{
readonly MetadataFile metadataFile;
readonly GenericParameterConstraintHandle handle;
readonly GenericParameterConstraint genericParamConstraint;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.GenericParamConstraint)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.GenericParamConstraint) * (RID - 1);
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Owner => MetadataTokens.GetToken(genericParamConstraint.Parameter);
public void OnOwnerClick()
{
MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, genericParamConstraint.Parameter, protocol: "metadata")));
}
string ownerTooltip;
public string OwnerTooltip {
get {
if (ownerTooltip == null)
{
ITextOutput output = new PlainTextOutput();
var p = metadataFile.Metadata.GetGenericParameter(genericParamConstraint.Parameter);
output.Write("parameter " + p.Index + (p.Name.IsNil ? "" : " (" + metadataFile.Metadata.GetString(p.Name) + ")") + " of ");
p.Parent.WriteTo(metadataFile, output, default);
ownerTooltip = output.ToString();
}
return ownerTooltip;
}
}
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Type => MetadataTokens.GetToken(genericParamConstraint.Type);
public void OnTypeClick()
{
MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, genericParamConstraint.Type, protocol: "metadata")));
}
string typeTooltip;
public string TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, genericParamConstraint.Type);
public GenericParamConstraintEntry(MetadataFile metadataFile, GenericParameterConstraintHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.genericParamConstraint = metadataFile.Metadata.GetGenericParameterConstraint(handle);
this.ownerTooltip = null;
this.typeTooltip = null;
}
}
}
}
|
GenericParamConstraintEntry
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/AspNetCore/src/AspNetCore/Extensions/HotChocolateAspNetCoreServiceCollectionExtensions.Warmup.cs
|
{
"start": 229,
"end": 5113
}
|
partial class ____
{
/// <summary>
/// Adds a warmup task that will be executed on each newly created request executor.
/// </summary>
/// <param name="builder">
/// The <see cref="IRequestExecutorBuilder"/>.
/// </param>
/// <param name="warmupFunc">
/// The warmup delegate to execute.
/// </param>
/// <param name="skipIf">
/// If <c>true</c>, the warmup task will not be registered.
/// </param>
/// <returns>
/// Returns the <see cref="IRequestExecutorBuilder"/> so that configuration can be chained.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The <paramref name="builder"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <paramref name="warmupFunc"/> is <c>null</c>.
/// </exception>
public static IRequestExecutorBuilder AddWarmupTask(
this IRequestExecutorBuilder builder,
Func<IRequestExecutor, CancellationToken, Task> warmupFunc,
bool skipIf = false)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(warmupFunc);
return builder.AddWarmupTask(new DelegateRequestExecutorWarmupTask(warmupFunc), skipIf);
}
/// <summary>
/// Adds a warmup task that will be executed on each newly created request executor.
/// </summary>
/// <param name="builder">
/// The <see cref="IRequestExecutorBuilder"/>.
/// </param>
/// <param name="warmupTask">
/// The warmup task to execute.
/// </param>
/// <param name="skipIf">
/// If <c>true</c>, the warmup task will not be registered.
/// </param>
/// <returns>
/// Returns the <see cref="IRequestExecutorBuilder"/> so that configuration can be chained.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The <paramref name="builder"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <paramref name="warmupTask"/> is <c>null</c>.
/// </exception>
public static IRequestExecutorBuilder AddWarmupTask(
this IRequestExecutorBuilder builder,
IRequestExecutorWarmupTask warmupTask,
bool skipIf = false)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(warmupTask);
if (skipIf)
{
return builder;
}
return builder.ConfigureSchemaServices((_, sc) => sc.AddSingleton(warmupTask));
}
/// <summary>
/// Adds a warmup task for the request executor.
/// </summary>
/// <param name="builder">
/// The <see cref="IRequestExecutorBuilder"/>.
/// </param>
/// <param name="skipIf">
/// If <c>true</c>, the warmup task will not be registered.
/// </param>
/// <typeparam name="T">
/// The warmup task to execute.
/// </typeparam>
/// <returns>
/// Returns the <see cref="IRequestExecutorBuilder"/> so that configuration can be chained.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The <paramref name="builder"/> is <c>null</c>.
/// </exception>
public static IRequestExecutorBuilder AddWarmupTask<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(
this IRequestExecutorBuilder builder,
bool skipIf = false)
where T : class, IRequestExecutorWarmupTask
{
ArgumentNullException.ThrowIfNull(builder);
if (skipIf)
{
return builder;
}
builder.ConfigureSchemaServices(
static (_, sc) => sc.AddSingleton<IRequestExecutorWarmupTask, T>());
return builder;
}
/// <summary>
/// Exports the GraphQL schema to a file on startup or when the schema changes.
/// </summary>
/// <param name="builder">
/// The <see cref="IRequestExecutorBuilder"/>.
/// </param>
/// <param name="schemaFileName">
/// The file name of the schema file.
/// </param>
/// <param name="skipIf">
/// If <c>true</c>, the schema file will not be exported.
/// </param>
/// <returns>
/// Returns the <see cref="IRequestExecutorBuilder"/> so that configuration can be chained.
/// </returns>
/// <exception cref="ArgumentNullException">
/// The <paramref name="builder"/> is <c>null</c>.
/// </exception>
public static IRequestExecutorBuilder ExportSchemaOnStartup(
this IRequestExecutorBuilder builder,
string? schemaFileName = null,
bool skipIf = false)
{
ArgumentNullException.ThrowIfNull(builder);
schemaFileName ??= System.IO.Path.Combine(Environment.CurrentDirectory, "schema.graphqls");
return builder.AddWarmupTask(new SchemaFileExporterWarmupTask(schemaFileName), skipIf);
}
}
|
HotChocolateAspNetCoreServiceCollectionExtensions
|
csharp
|
dotnet__aspnetcore
|
src/Http/Http/src/DefaultHttpContext.cs
|
{
"start": 9629,
"end": 9983
}
|
struct ____
{
public IItemsFeature? Items;
public IServiceProvidersFeature? ServiceProviders;
public IHttpAuthenticationFeature? Authentication;
public IHttpRequestLifetimeFeature? Lifetime;
public ISessionFeature? Session;
public IHttpRequestIdentifierFeature? RequestIdentifier;
}
}
|
FeatureInterfaces
|
csharp
|
ShareX__ShareX
|
ShareX.UploadersLib/FileUploaders/GoogleDrive.cs
|
{
"start": 10087,
"end": 10360
}
|
public class ____
{
public string id { get; set; }
public string webViewLink { get; set; }
public string webContentLink { get; set; }
public string name { get; set; }
public string description { get; set; }
}
|
GoogleDriveFile
|
csharp
|
abpframework__abp
|
modules/background-jobs/src/Volo.Abp.BackgroundJobs.EntityFrameworkCore/Volo/Abp/BackgroundJobs/EntityFrameworkCore/IBackgroundJobsDbContext.cs
|
{
"start": 277,
"end": 397
}
|
public interface ____ : IEfCoreDbContext
{
DbSet<BackgroundJobRecord> BackgroundJobs { get; }
}
|
IBackgroundJobsDbContext
|
csharp
|
dotnet__efcore
|
test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs
|
{
"start": 144214,
"end": 144347
}
|
private class ____
{
public int Id { get; set; }
public DependentNG? DependentNG { get; set; }
}
|
PrincipalNG
|
csharp
|
cake-build__cake
|
src/Cake.Frosting/IFrostingLifetime.cs
|
{
"start": 322,
"end": 815
}
|
public interface ____
{
/// <summary>
/// This method is executed before any tasks are run.
/// If setup fails, no tasks will be executed but teardown will be performed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="info">The setup information.</param>
void Setup(ICakeContext context, ISetupContext info);
}
/// <summary>
/// Represents teardown logic.
/// </summary>
|
IFrostingSetup
|
csharp
|
spectreconsole__spectre.console
|
src/Spectre.Console/Live/Progress/Spinner.Generated.cs
|
{
"start": 37093,
"end": 37620
}
|
private sealed class ____ : Spinner
{
public override TimeSpan Interval => TimeSpan.FromMilliseconds(80);
public override bool IsUnicode => true;
public override IReadOnlyList<string> Frames => new List<string>
{
"⬆️ ",
"↗️ ",
"➡️ ",
"↘️ ",
"⬇️ ",
"↙️ ",
"⬅️ ",
"↖️ ",
};
}
|
Arrow2Spinner
|
csharp
|
dotnetcore__FreeSql
|
FreeSql/Internal/Model/HzyTuple.cs
|
{
"start": 2258,
"end": 2796
}
|
public class ____<T1, T2, T3, T4, T5, T6, T7, T8>
{
public HzyTuple(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8)
{
this.t1 = t1; this.t2 = t2; this.t3 = t3; this.t4 = t4; this.t5 = t5; this.t6 = t6; this.t7 = t7; this.t8 = t8;
}
public T1 t1 { get; }
public T2 t2 { get; }
public T3 t3 { get; }
public T4 t4 { get; }
public T5 t5 { get; }
public T6 t6 { get; }
public T7 t7 { get; }
public T8 t8 { get; }
}
|
HzyTuple
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/src/ServiceStack.Common/CachedExpressionCompiler.cs
|
{
"start": 36401,
"end": 37413
}
|
internal sealed class ____ : ExpressionFingerprint
{
public MemberExpressionFingerprint(ExpressionType nodeType, Type type, MemberInfo member)
: base(nodeType, type)
{
Member = member;
}
// http://msdn.microsoft.com/en-us/library/system.linq.expressions.memberexpression.member.aspx
public MemberInfo Member { get; private set; }
public override bool Equals(object obj)
{
MemberExpressionFingerprint other = obj as MemberExpressionFingerprint;
return (other != null)
&& Equals(this.Member, other.Member)
&& this.Equals(other);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)
{
combiner.AddObject(Member);
base.AddToHashCodeCombiner(combiner);
}
}
|
MemberExpressionFingerprint
|
csharp
|
GtkSharp__GtkSharp
|
Source/Libs/CairoSharp/SubpixelOrder.cs
|
{
"start": 1247,
"end": 1322
}
|
public enum ____
{
Default,
Rgb,
Bgr,
Vrgb,
Vbgr,
}
}
|
SubpixelOrder
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Text/tests/ServiceStack.Text.Tests/JsonTests/PolymorphicListTests.cs
|
{
"start": 14611,
"end": 14753
}
|
public class ____
{
public Cat Cat { get; set; }
public OtherDog Dog { get; set; }
}
|
ExplicitPets
|
csharp
|
dotnet__efcore
|
src/EFCore/Diagnostics/ConcurrencyExceptionEventData.cs
|
{
"start": 579,
"end": 2173
}
|
public class ____ : DbContextErrorEventData
{
private readonly IReadOnlyList<IUpdateEntry> _internalEntries;
/// <summary>
/// Constructs the event payload.
/// </summary>
/// <param name="eventDefinition">The event definition.</param>
/// <param name="messageGenerator">A delegate that generates a log message for this event.</param>
/// <param name="context">The current <see cref="DbContext" />.</param>
/// <param name="entries">The entries that were involved in the concurrency violation.</param>
/// <param name="exception">The exception that will be thrown, unless throwing is suppressed.</param>
public ConcurrencyExceptionEventData(
EventDefinitionBase eventDefinition,
Func<EventDefinitionBase, EventData, string> messageGenerator,
DbContext context,
IReadOnlyList<IUpdateEntry> entries,
DbUpdateConcurrencyException exception)
: base(eventDefinition, messageGenerator, context, exception)
=> _internalEntries = entries;
/// <summary>
/// The exception that will be thrown, unless throwing is suppressed.
/// </summary>
public new virtual DbUpdateConcurrencyException Exception
=> (DbUpdateConcurrencyException)base.Exception;
/// <summary>
/// The entries that were involved in the concurrency violation.
/// </summary>
[field: AllowNull, MaybeNull]
public virtual IReadOnlyList<EntityEntry> Entries
=> field ??= _internalEntries.Select(e => new EntityEntry((InternalEntityEntry)e)).ToList();
}
|
ConcurrencyExceptionEventData
|
csharp
|
moq__moq4
|
src/Moq.Tests/RecursiveMocksFixture.cs
|
{
"start": 14088,
"end": 14329
}
|
public interface ____
{
int Value { get; set; }
int OtherValue { get; set; }
string Do(string command);
IBaz Baz { get; set; }
IBaz GetBaz(string value);
}
|
IBar
|
csharp
|
dotnet__maui
|
src/Graphics/samples/GraphicsTester.Skia.Gtk/MainWindow.cs
|
{
"start": 308,
"end": 2951
}
|
class ____ : Window
{
private TreeView _treeView;
private TreeStore _store;
private Dictionary<string, AbstractScenario> _items;
private GtkSkiaGraphicsView _skiaGraphicsView;
public MainWindow() : base(WindowType.Toplevel)
{
// Setup GUI
WindowPosition = WindowPosition.Center;
DefaultSize = new Gdk.Size(800, 600);
var headerBar = new HeaderBar
{
ShowCloseButton = true,
Title = $"{nameof(GtkSkiaGraphicsView)} Sample Application"
};
var btnClickMe = new Button
{
AlwaysShowImage = true,
Image = Image.NewFromIconName("document-new-symbolic", IconSize.Button)
};
headerBar.PackStart(btnClickMe);
Titlebar = headerBar;
var hpanned = new Paned(Orientation.Horizontal)
{
Position = 300
};
_treeView = new TreeView
{
HeadersVisible = false
};
var scroll0 = new ScrolledWindow
{
Child = _treeView
};
hpanned.Pack1(scroll0, true, true);
_skiaGraphicsView = new GtkSkiaGraphicsView();
var skiaGraphicsRenderer = new GtkSkiaDirectRenderer
{
BackgroundColor = Colors.White
};
_skiaGraphicsView.Renderer = skiaGraphicsRenderer;
var scroll1 = new ScrolledWindow
{
Child = _skiaGraphicsView
};
hpanned.Pack2(scroll1, true, true);
Child = hpanned;
// Fill up data
FillUpTreeView();
// Connect events
_treeView.Selection.Changed += Selection_Changed;
Destroyed += (sender, e) => this.Close();
var scenario = ScenarioList.Scenarios[0];
_skiaGraphicsView.Drawable = scenario;
}
private void Selection_Changed(object sender, EventArgs e)
{
if (_treeView.Selection.GetSelected(out TreeIter iter))
{
var s = _store.GetValue(iter, 0).ToString();
if (_items.TryGetValue(s, out var scenario))
{
_skiaGraphicsView.Drawable = scenario;
_skiaGraphicsView.HeightRequest = (int)scenario.Height;
_skiaGraphicsView.WidthRequest = (int)scenario.Width;
}
}
}
private void FillUpTreeView()
{
// Init cells
var cellName = new CellRendererText();
// Init columns
var columeSections = new TreeViewColumn
{
Title = "Sections"
};
columeSections.PackStart(cellName, true);
columeSections.AddAttribute(cellName, "text", 0);
_treeView.AppendColumn(columeSections);
// Init treeview
_store = new TreeStore(typeof(string));
_treeView.Model = _store;
_items = new Dictionary<string, AbstractScenario>();
foreach (var scenario in ScenarioList.Scenarios)
{
_store.AppendValues(scenario.ToString());
_items[scenario.ToString()] = scenario;
}
_treeView.ExpandAll();
}
}
}
|
MainWindow
|
csharp
|
unoplatform__uno
|
src/Uno.UI/UI/Xaml/Window/WindowManagerInterop.wasm.cs
|
{
"start": 14111,
"end": 14612
}
|
private struct ____
{
public double X;
public double Y;
public double Width;
public double Height;
}
#endregion
#region SetContentHtml
internal static void SetContentHtml(IntPtr htmlId, string html)
{
var parms = new WindowManagerSetContentHtmlParams()
{
HtmlId = htmlId,
Html = html,
};
TSInteropMarshaller.InvokeJS("Uno:setHtmlContentNative", parms);
}
[TSInteropMessage]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
WindowManagerGetBBoxReturn
|
csharp
|
jasontaylordev__CleanArchitecture
|
src/Application/Common/Behaviours/ValidationBehaviour.cs
|
{
"start": 159,
"end": 1159
}
|
public class ____<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
if (_validators.Any())
{
var validationResults = await Task.WhenAll(
_validators.Select(v =>
v.ValidateAsync(new ValidationContext<TRequest>(request), cancellationToken)));
var failures = validationResults
.Where(r => r.Errors.Any())
.SelectMany(r => r.Errors)
.ToList();
if (failures.Count != 0)
throw new ValidationException(failures);
}
return await next();
}
}
|
ValidationBehaviour
|
csharp
|
microsoft__PowerToys
|
src/settings-ui/Settings.UI/SettingsXAML/Controls/SettingsGroup/SettingsGroupAutomationPeer.cs
|
{
"start": 285,
"end": 671
}
|
public partial class ____ : FrameworkElementAutomationPeer
{
public SettingsGroupAutomationPeer(SettingsGroup owner)
: base(owner)
{
}
protected override string GetNameCore()
{
var selectedSettingsGroup = (SettingsGroup)Owner;
return selectedSettingsGroup.Header;
}
}
}
|
SettingsGroupAutomationPeer
|
csharp
|
dotnet__machinelearning
|
test/Microsoft.ML.Tests/FeatureContributionTests.cs
|
{
"start": 16309,
"end": 16500
}
|
private enum ____
{
Regression,
BinaryClassification,
MulticlassClassification,
Ranking,
Clustering
}
|
TaskType
|
csharp
|
unoplatform__uno
|
src/SourceGenerators/XamlGenerationTests.Core/ControlWithObservableCollectionContent.cs
|
{
"start": 283,
"end": 900
}
|
public partial class ____ : Control
{
public ObservableCollection<object> Items
{
get { return (ObservableCollection<object>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
// Using a DependencyProperty as the backing store for Items. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<object>), typeof(ControlWithObservableCollectionContent), new FrameworkPropertyMetadata(new ObservableCollection<object>()));
}
}
|
ControlWithObservableCollectionContent
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/Activities/UserTaskEvent.cs
|
{
"start": 269,
"end": 1763
}
|
public class ____ : EventActivity
{
protected readonly IStringLocalizer S;
public UserTaskEvent(IStringLocalizer<UserTaskEvent> localizer)
{
S = localizer;
}
public override string Name => nameof(UserTaskEvent);
public override LocalizedString DisplayText => S["User Task Event"];
public override LocalizedString Category => S["Content"];
public IList<string> Actions
{
get => GetProperty(() => new List<string>());
set => SetProperty(value);
}
public IList<string> Roles
{
get => GetProperty(() => new List<string>());
set => SetProperty(value);
}
public override bool CanExecute(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var action = GetProvidedAction(workflowContext);
return Actions.Contains(action);
}
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Actions.Select(x => Outcome(S[x]));
}
public override ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var action = GetProvidedAction(workflowContext);
return Outcomes(action);
}
private static string GetProvidedAction(WorkflowExecutionContext workflowContext)
{
return (string)workflowContext.Input[ContentEventConstants.UserActionInputKey];
}
}
|
UserTaskEvent
|
csharp
|
CommunityToolkit__WindowsCommunityToolkit
|
Microsoft.Toolkit.Uwp.Notifications/Adaptive/Elements/Element_AdaptiveImage.cs
|
{
"start": 309,
"end": 3057
}
|
internal sealed class ____ : IElement_TileBindingChild, IElement_ToastBindingChild, IElement_AdaptiveSubgroupChild, IHaveXmlName, IHaveXmlNamedProperties
{
internal const AdaptiveImagePlacement DEFAULT_PLACEMENT = AdaptiveImagePlacement.Inline;
internal const AdaptiveImageCrop DEFAULT_CROP = AdaptiveImageCrop.Default;
internal const AdaptiveImageAlign DEFAULT_ALIGN = AdaptiveImageAlign.Default;
public int? Id { get; set; }
public string Src { get; set; }
public string Alt { get; set; }
public bool? AddImageQuery { get; set; }
public AdaptiveImagePlacement Placement { get; set; } = DEFAULT_PLACEMENT;
public AdaptiveImageAlign Align { get; set; } = DEFAULT_ALIGN;
public AdaptiveImageCrop Crop { get; set; } = DEFAULT_CROP;
public bool? RemoveMargin { get; set; }
private int? _overlay;
public int? Overlay
{
get
{
return _overlay;
}
set
{
if (value != null)
{
Element_TileBinding.CheckOverlayValue(value.Value);
}
_overlay = value;
}
}
public string SpriteSheetSrc { get; set; }
public uint? SpriteSheetHeight { get; set; }
public uint? SpriteSheetFps { get; set; }
public uint? SpriteSheetStartingFrame { get; set; }
/// <inheritdoc/>
string IHaveXmlName.Name => "image";
/// <inheritdoc/>
IEnumerable<KeyValuePair<string, object>> IHaveXmlNamedProperties.EnumerateNamedProperties()
{
yield return new("id", Id);
yield return new("src", Src);
yield return new("alt", Alt);
yield return new("addImageQuery", AddImageQuery);
if (Placement != DEFAULT_PLACEMENT)
{
yield return new("placement", Placement.ToPascalCaseString());
}
if (Align != DEFAULT_ALIGN)
{
yield return new("hint-align", Align.ToPascalCaseString());
}
if (Crop != DEFAULT_CROP)
{
yield return new("hint-crop", Crop.ToPascalCaseString());
}
yield return new("hint-removeMargin", RemoveMargin);
yield return new("hint-overlay", Overlay);
yield return new("spritesheet-src", SpriteSheetSrc);
yield return new("spritesheet-height", SpriteSheetHeight);
yield return new("spritesheet-fps", SpriteSheetFps);
yield return new("spritesheet-startingFrame", SpriteSheetStartingFrame);
}
}
}
|
Element_AdaptiveImage
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
|
{
"start": 425277,
"end": 425497
}
|
public class ____
{
public int Id { get; set; }
public RelatedEntity1947 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1949> ChildEntities { get; set; }
}
|
RelatedEntity1948
|
csharp
|
npgsql__npgsql
|
test/Npgsql.Tests/PoolManagerTests.cs
|
{
"start": 70,
"end": 2392
}
|
class ____ : TestBase
{
[Test]
public void With_canonical_connection_string()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString).ToString();
using (var conn = new NpgsqlConnection(connString))
conn.Open();
var connString2 = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = "Another connstring"
}.ToString();
using (var conn = new NpgsqlConnection(connString2))
conn.Open();
}
#if DEBUG
[Test]
public void Many_pools()
{
PoolManager.Reset();
for (var i = 0; i < 15; i++)
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = "App" + i
}.ToString();
using var conn = new NpgsqlConnection(connString);
conn.Open();
}
PoolManager.Reset();
}
#endif
[Test]
public void ClearAllPools()
{
using (var conn = new NpgsqlConnection(ConnectionString))
conn.Open();
// Now have one connection in the pool
Assert.That(PoolManager.Pools.TryGetValue(ConnectionString, out var pool), Is.True);
Assert.That(pool!.Statistics.Idle, Is.EqualTo(1));
NpgsqlConnection.ClearAllPools();
Assert.That(pool.Statistics.Idle, Is.Zero);
Assert.That(pool.Statistics.Total, Is.Zero);
}
[Test]
public void ClearAllPools_with_busy()
{
NpgsqlDataSource? pool;
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
using (var anotherConn = new NpgsqlConnection(ConnectionString))
anotherConn.Open();
// We have one idle, one busy
NpgsqlConnection.ClearAllPools();
Assert.That(PoolManager.Pools.TryGetValue(ConnectionString, out pool), Is.True);
Assert.That(pool!.Statistics.Idle, Is.Zero);
Assert.That(pool.Statistics.Total, Is.EqualTo(1));
}
Assert.That(pool.Statistics.Idle, Is.Zero);
Assert.That(pool.Statistics.Total, Is.Zero);
}
[SetUp]
public void Setup() => PoolManager.Reset();
[TearDown]
public void Teardown() => PoolManager.Reset();
}
|
PoolManagerTests
|
csharp
|
nopSolutions__nopCommerce
|
src/Presentation/Nop.Web/Areas/Admin/Models/Orders/RecurringPaymentHistoryModel.cs
|
{
"start": 200,
"end": 1026
}
|
public partial record ____ : BaseNopEntityModel
{
#region Properties
public int OrderId { get; set; }
[NopResourceDisplayName("Admin.RecurringPayments.History.CustomOrderNumber")]
public string CustomOrderNumber { get; set; }
public int RecurringPaymentId { get; set; }
[NopResourceDisplayName("Admin.RecurringPayments.History.OrderStatus")]
public string OrderStatus { get; set; }
[NopResourceDisplayName("Admin.RecurringPayments.History.PaymentStatus")]
public string PaymentStatus { get; set; }
[NopResourceDisplayName("Admin.RecurringPayments.History.ShippingStatus")]
public string ShippingStatus { get; set; }
[NopResourceDisplayName("Admin.RecurringPayments.History.CreatedOn")]
public DateTime CreatedOn { get; set; }
#endregion
}
|
RecurringPaymentHistoryModel
|
csharp
|
dotnet__extensions
|
src/Libraries/Microsoft.Extensions.Http.Resilience/Internal/ResilienceKeys.cs
|
{
"start": 340,
"end": 900
}
|
internal static class ____
{
public static readonly ResiliencePropertyKey<HttpRequestMessage?> RequestMessage = new("Resilience.Http.RequestMessage");
public static readonly ResiliencePropertyKey<RequestRoutingStrategy> RoutingStrategy = new("Resilience.Http.RequestRoutingStrategy");
public static readonly ResiliencePropertyKey<RequestMessageSnapshot> RequestSnapshot = new("Resilience.Http.Snapshot");
public static readonly ResiliencePropertyKey<RequestMetadata> RequestMetadata = new(TelemetryConstants.RequestMetadataKey);
}
|
ResilienceKeys
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit/SagaStateMachine/SagaStateMachine/Activities/FaultedActionActivity.cs
|
{
"start": 100,
"end": 1561
}
|
public class ____<TSaga, TException> :
IStateMachineActivity<TSaga>
where TException : Exception
where TSaga : class, SagaStateMachineInstance
{
readonly Action<BehaviorExceptionContext<TSaga, TException>> _action;
public FaultedActionActivity(Action<BehaviorExceptionContext<TSaga, TException>> action)
{
_action = action;
}
public void Accept(StateMachineVisitor visitor)
{
visitor.Visit(this);
}
public void Probe(ProbeContext context)
{
context.CreateScope("then-faulted");
}
public Task Execute(BehaviorContext<TSaga> context, IBehavior<TSaga> next)
{
return next.Execute(context);
}
public Task Execute<TData>(BehaviorContext<TSaga, TData> context, IBehavior<TSaga, TData> next)
where TData : class
{
return next.Execute(context);
}
public Task Faulted<T>(BehaviorExceptionContext<TSaga, T> context, IBehavior<TSaga> next)
where T : Exception
{
if (context is BehaviorExceptionContext<TSaga, TException> exceptionContext)
_action(exceptionContext);
return next.Faulted(context);
}
public Task Faulted<TData, T>(BehaviorExceptionContext<TSaga, TData, T> context, IBehavior<TSaga, TData> next)
where TData :
|
FaultedActionActivity
|
csharp
|
dotnetcore__CAP
|
src/DotNetCore.CAP.RedisStreams/IConnectionPool.Default.cs
|
{
"start": 421,
"end": 3001
}
|
internal class ____ : IRedisConnectionPool, IDisposable
{
private readonly ConcurrentBag<AsyncLazyRedisConnection> _connections = [];
private readonly ILoggerFactory _loggerFactory;
private readonly SemaphoreSlim _poolLock = new(1);
private readonly CapRedisOptions _redisOptions;
private bool _isDisposed;
private bool _poolAlreadyConfigured;
public RedisConnectionPool(IOptions<CapRedisOptions> options, ILoggerFactory loggerFactory)
{
_redisOptions = options.Value;
_loggerFactory = loggerFactory;
Init().GetAwaiter().GetResult();
}
private AsyncLazyRedisConnection? QuietConnection
{
get
{
return _poolAlreadyConfigured ? _connections.OrderBy(static c => c.CreatedConnection?.ConnectionCapacity ?? int.MaxValue)
.First() : null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public async Task<IConnectionMultiplexer> ConnectAsync()
{
if (QuietConnection == null)
{
_poolAlreadyConfigured =
_connections.Count(static c => c.IsValueCreated) == _redisOptions.ConnectionPoolSize;
if (QuietConnection != null) return QuietConnection.CreatedConnection!.Connection;
}
foreach (var lazy in _connections)
{
if (!lazy.IsValueCreated) return (await lazy).Connection;
if (lazy.CreatedConnection!.ConnectionCapacity == default) return lazy.CreatedConnection.Connection;
}
return (await _connections.OrderBy(static c => c.CreatedConnection!.ConnectionCapacity).First()).Connection;
}
private async Task Init()
{
try
{
await _poolLock.WaitAsync();
if (!_connections.IsEmpty) return;
for (var i = 0; i < _redisOptions.ConnectionPoolSize; i++)
{
var connection = new AsyncLazyRedisConnection(_redisOptions,
_loggerFactory.CreateLogger<AsyncLazyRedisConnection>());
_connections.Add(connection);
}
}
finally
{
_poolLock.Release();
}
}
private void Dispose(bool disposing)
{
if (_isDisposed) return;
if (disposing)
foreach (var connection in _connections)
{
if (!connection.IsValueCreated) continue;
connection.CreatedConnection!.Dispose();
}
_isDisposed = true;
}
}
|
RedisConnectionPool
|
csharp
|
dotnet__aspnetcore
|
src/Identity/test/InMemory.Test/FunctionalTest.cs
|
{
"start": 802,
"end": 21500
}
|
public class ____ : LoggedTest
{
const string TestPassword = "[PLACEHOLDER]-1a";
[Fact]
public async Task CanChangePasswordOptions()
{
var server = await CreateServer(services => services.Configure<IdentityOptions>(options =>
{
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireDigit = false;
}));
var transaction1 = await SendAsync(server, "http://example.com/createSimple");
// Assert
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
}
[Fact]
public async Task CookieContainsRoleClaim()
{
var server = await CreateServer(null, null, null, testCore: true);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false");
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
Assert.NotNull(transaction2.SetCookie);
Assert.DoesNotContain("; expires=", transaction2.SetCookie);
var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
Assert.Equal("role", FindClaimValue(transaction3, ClaimTypes.Role));
Assert.Null(transaction3.SetCookie);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCreateMeLoginAndCookieStopsWorkingAfterExpiration(bool testCore)
{
var timeProvider = new FakeTimeProvider();
var server = await CreateServer(services =>
{
services.ConfigureApplicationCookie(options =>
{
options.TimeProvider = timeProvider;
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
options.SlidingExpiration = false;
});
services.Configure<SecurityStampValidatorOptions>(options =>
{
options.TimeProvider = timeProvider;
});
}, testCore: testCore);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false");
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
Assert.NotNull(transaction2.SetCookie);
Assert.DoesNotContain("; expires=", transaction2.SetCookie);
var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
Assert.Null(transaction3.SetCookie);
timeProvider.Advance(TimeSpan.FromMinutes(7));
var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
Assert.Null(transaction4.SetCookie);
timeProvider.Advance(TimeSpan.FromMinutes(7));
var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
Assert.Null(transaction5.SetCookie);
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task CanCreateMeLoginAndSecurityStampExtendsExpiration(bool rememberMe, bool testCore)
{
var timeProvider = new FakeTimeProvider();
var server = await CreateServer(services =>
{
services.AddSingleton<TimeProvider>(timeProvider);
}, testCore: testCore);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/" + rememberMe);
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
Assert.NotNull(transaction2.SetCookie);
if (rememberMe)
{
Assert.Contains("; expires=", transaction2.SetCookie);
}
else
{
Assert.DoesNotContain("; expires=", transaction2.SetCookie);
}
var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
Assert.Null(transaction3.SetCookie);
// Make sure we don't get a new cookie yet
timeProvider.Advance(TimeSpan.FromMinutes(10));
var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
Assert.Null(transaction4.SetCookie);
// Go past SecurityStampValidation interval and ensure we get a new cookie
timeProvider.Advance(TimeSpan.FromMinutes(21));
var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.NotNull(transaction5.SetCookie);
Assert.Equal("hao", FindClaimValue(transaction5, ClaimTypes.Name));
// Make sure new cookie is valid
var transaction6 = await SendAsync(server, "http://example.com/me", transaction5.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction6, ClaimTypes.Name));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanAccessOldPrincipalDuringSecurityStampReplacement(bool testCore)
{
var timeProvider = new FakeTimeProvider();
var server = await CreateServer(services =>
{
services.AddSingleton<TimeProvider>(timeProvider);
services.Configure<SecurityStampValidatorOptions>(options =>
{
options.OnRefreshingPrincipal = c =>
{
var newId = new ClaimsIdentity();
newId.AddClaim(new Claim("PreviousName", c.CurrentPrincipal.Identity.Name));
c.NewPrincipal.AddIdentity(newId);
return Task.FromResult(0);
};
});
}, testCore: testCore);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false");
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
Assert.NotNull(transaction2.SetCookie);
Assert.DoesNotContain("; expires=", transaction2.SetCookie);
var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
Assert.Null(transaction3.SetCookie);
// Make sure we don't get a new cookie yet
timeProvider.Advance(TimeSpan.FromMinutes(10));
var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
Assert.Null(transaction4.SetCookie);
// Go past SecurityStampValidation interval and ensure we get a new cookie
timeProvider.Advance(TimeSpan.FromMinutes(21));
var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);
Assert.NotNull(transaction5.SetCookie);
Assert.Equal("hao", FindClaimValue(transaction5, ClaimTypes.Name));
Assert.Equal("hao", FindClaimValue(transaction5, "PreviousName"));
// Make sure new cookie is valid
var transaction6 = await SendAsync(server, "http://example.com/me", transaction5.CookieNameValue);
Assert.Equal("hao", FindClaimValue(transaction6, ClaimTypes.Name));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TwoFactorRememberCookieVerification(bool testCore)
{
var timeProvider = new FakeTimeProvider();
var server = await CreateServer(services => services.AddSingleton<TimeProvider>(timeProvider), testCore: testCore);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/twofactorRememeber");
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
var setCookie = transaction2.SetCookie;
Assert.Contains(IdentityConstants.TwoFactorRememberMeScheme + "=", setCookie);
Assert.Contains("; expires=", setCookie);
var transaction3 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.OK, transaction3.Response.StatusCode);
// Wait for validation interval
timeProvider.Advance(TimeSpan.FromMinutes(30));
var transaction4 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.OK, transaction4.Response.StatusCode);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TwoFactorRememberCookieClearedBySecurityStampChange(bool testCore)
{
var timeProvider = new FakeTimeProvider();
var server = await CreateServer(services => services.AddSingleton<TimeProvider>(timeProvider), testCore: testCore);
var transaction1 = await SendAsync(server, "http://example.com/createMe");
Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
Assert.Null(transaction1.SetCookie);
var transaction2 = await SendAsync(server, "http://example.com/twofactorRememeber");
Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
var setCookie = transaction2.SetCookie;
Assert.Contains(IdentityConstants.TwoFactorRememberMeScheme + "=", setCookie);
Assert.Contains("; expires=", setCookie);
var transaction3 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.OK, transaction3.Response.StatusCode);
var transaction4 = await SendAsync(server, "http://example.com/signoutEverywhere", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.OK, transaction4.Response.StatusCode);
// Doesn't validate until after interval has passed
var transaction5 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.OK, transaction5.Response.StatusCode);
// Wait for validation interval
timeProvider.Advance(TimeSpan.FromMinutes(30) + TimeSpan.FromMilliseconds(1));
var transaction6 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);
Assert.Equal(HttpStatusCode.InternalServerError, transaction6.Response.StatusCode);
}
private static string FindClaimValue(Transaction transaction, string claimType)
{
var claim = transaction.ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
if (claim == null)
{
return null;
}
return claim.Attribute("value").Value;
}
private async Task<TestServer> CreateServer(Action<IServiceCollection> configureServices = null, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, bool testCore = false)
{
var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.Configure(app =>
{
app.UseAuthentication();
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
var userManager = context.RequestServices.GetRequiredService<UserManager<PocoUser>>();
var roleManager = context.RequestServices.GetRequiredService<RoleManager<PocoRole>>();
var signInManager = context.RequestServices.GetRequiredService<SignInManager<PocoUser>>();
PathString remainder;
if (req.Path == new PathString("/normal"))
{
res.StatusCode = 200;
}
else if (req.Path == new PathString("/createMe"))
{
var user = new PocoUser("hao");
var result = await userManager.CreateAsync(user, TestPassword);
if (result.Succeeded)
{
result = await roleManager.CreateAsync(new PocoRole("role"));
}
if (result.Succeeded)
{
result = await userManager.AddToRoleAsync(user, "role");
}
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/createSimple"))
{
var result = await userManager.CreateAsync(new PocoUser("simple"), "aaaaaa");
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/signoutEverywhere"))
{
var user = await userManager.FindByNameAsync("hao");
var result = await userManager.UpdateSecurityStampAsync(user);
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path.StartsWithSegments(new PathString("/pwdLogin"), out remainder))
{
var isPersistent = bool.Parse(remainder.Value.AsSpan(1));
var result = await signInManager.PasswordSignInAsync("hao", TestPassword, isPersistent, false);
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/twofactorRememeber"))
{
var user = await userManager.FindByNameAsync("hao");
await signInManager.RememberTwoFactorClientAsync(user);
res.StatusCode = 200;
}
else if (req.Path == new PathString("/isTwoFactorRememebered"))
{
var user = await userManager.FindByNameAsync("hao");
var result = await signInManager.IsTwoFactorClientRememberedAsync(user);
res.StatusCode = result ? 200 : 500;
}
else if (req.Path == new PathString("/hasTwoFactorUserId"))
{
var result = await context.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme);
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/me"))
{
await DescribeAsync(res, AuthenticateResult.Success(new AuthenticationTicket(context.User, null, "Application")));
}
else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder))
{
var auth = await context.AuthenticateAsync(remainder.Value.Substring(1));
await DescribeAsync(res, auth);
}
else if (req.Path == new PathString("/testpath") && testpath != null)
{
await testpath(context);
}
else
{
await next(context);
}
});
})
.ConfigureServices(services =>
{
if (testCore)
{
services.AddIdentityCore<PocoUser>()
.AddRoles<PocoRole>()
.AddSignInManager()
.AddDefaultTokenProviders();
services.AddAuthentication(IdentityConstants.ApplicationScheme).AddIdentityCookies();
}
else
{
services.AddIdentity<PocoUser, PocoRole>().AddDefaultTokenProviders();
}
var store = new InMemoryStore<PocoUser, PocoRole>();
services.AddSingleton<IUserStore<PocoUser>>(store);
services.AddSingleton<IRoleStore<PocoRole>>(store);
configureServices?.Invoke(services);
AddTestLogging(services);
})
.UseTestServer())
.Build();
await host.StartAsync();
var server = host.GetTestServer();
server.BaseAddress = baseAddress;
return server;
}
private static async Task DescribeAsync(HttpResponse res, AuthenticateResult result)
{
res.StatusCode = 200;
res.ContentType = "text/xml";
var xml = new XElement("xml");
if (result != null && result.Principal != null)
{
xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value))));
}
if (result != null && result.Properties != null)
{
xml.Add(result.Properties.Items.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value))));
}
using (var memory = new MemoryStream())
{
using (var writer = XmlWriter.Create(memory, new XmlWriterSettings { Encoding = Encoding.UTF8 }))
{
xml.WriteTo(writer);
}
await res.Body.WriteAsync(memory.ToArray(), 0, memory.ToArray().Length);
}
}
private static async Task<Transaction> SendAsync(TestServer server, string uri, string cookieHeader = null, bool ajaxRequest = false)
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (!string.IsNullOrEmpty(cookieHeader))
{
request.Headers.Add("Cookie", cookieHeader);
}
if (ajaxRequest)
{
request.Headers.Add(HeaderNames.XRequestedWith, "XMLHttpRequest");
}
var transaction = new Transaction
{
Request = request,
Response = await server.CreateClient().SendAsync(request),
};
if (transaction.Response.Headers.Contains("Set-Cookie"))
{
transaction.SetCookie = transaction.Response.Headers.GetValues("Set-Cookie").FirstOrDefault();
}
if (!string.IsNullOrEmpty(transaction.SetCookie))
{
transaction.CookieNameValue = transaction.SetCookie.Split(new[] { ';' }, 2).First();
}
transaction.ResponseText = await transaction.Response.Content.ReadAsStringAsync();
if (transaction.Response.Content != null &&
transaction.Response.Content.Headers.ContentType != null &&
transaction.Response.Content.Headers.ContentType.MediaType == "text/xml")
{
transaction.ResponseElement = XElement.Parse(transaction.ResponseText);
}
return transaction;
}
|
FunctionalTest
|
csharp
|
Cysharp__MemoryPack
|
sandbox/SandboxConsoleApp/SystemTextJsonChecker.cs
|
{
"start": 2814,
"end": 3101
}
|
public class ____
{
public int X { get; }
public int Y { get; }
public Three()
{
Console.WriteLine("Called Three One");
}
public Three(int x, int y)
{
Console.WriteLine("Called Three Two");
this.X = x;
this.Y = y;
}
}
|
Three
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.