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 | neuecc__MessagePack-CSharp | src/MessagePack.Annotations/Attributes.cs | {
"start": 3771,
"end": 5231
} | public class ____ : Attribute
{
/// <summary>
/// Gets the distinguishing value that identifies a particular subtype.
/// </summary>
public int Key { get; }
/// <summary>
/// Gets the derived or implementing type.
/// </summary>
public Type SubType { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UnionAttribute"/> class.
/// </summary>
/// <param name="key">The distinguishing value that identifies a particular subtype.</param>
/// <param name="subType">The derived or implementing type.</param>
public UnionAttribute(int key, Type subType)
{
this.Key = key;
this.SubType = subType ?? throw new ArgumentNullException(nameof(subType));
}
/// <summary>
/// Initializes a new instance of the <see cref="UnionAttribute"/> class.
/// </summary>
/// <param name="key">The distinguishing value that identifies a particular subtype.</param>
/// <param name="subType">The full name (should be assembly qualified) of the derived or implementing type.</param>
public UnionAttribute(int key, string subType)
{
this.Key = key;
this.SubType = Type.GetType(subType, throwOnError: true);
}
}
[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = true)]
| UnionAttribute |
csharp | dotnet__efcore | src/EFCore.Relational/Migrations/Operations/AddForeignKeyOperation.cs | {
"start": 528,
"end": 3360
} | public class ____ : MigrationOperation, ITableMigrationOperation
{
/// <summary>
/// The name of the foreign key constraint.
/// </summary>
public virtual string Name { get; set; } = null!;
/// <summary>
/// The schema that contains the table, or <see langword="null" /> if the default schema should be used.
/// </summary>
public virtual string? Schema { get; set; }
/// <summary>
/// The table to which the foreign key should be added.
/// </summary>
public virtual string Table { get; set; } = null!;
/// <summary>
/// The ordered-list of column names for the columns that make up the foreign key.
/// </summary>
public virtual string[] Columns { get; set; } = null!;
/// <summary>
/// The schema that contains the table to which this foreign key is constrained,
/// or <see langword="null" /> if the default schema should be used.
/// </summary>
public virtual string? PrincipalSchema { get; set; }
/// <summary>
/// The table to which the foreign key is constrained.
/// </summary>
public virtual string PrincipalTable { get; set; } = null!;
/// <summary>
/// The ordered-list of column names for the columns to which the columns that make up this foreign key are constrained, or
/// <see langword="null" /> to constrain to the primary key columns.
/// </summary>
public virtual string[]? PrincipalColumns { get; set; }
/// <summary>
/// The <see cref="ReferentialAction" /> to use for updates.
/// </summary>
public virtual ReferentialAction OnUpdate { get; set; }
/// <summary>
/// The <see cref="ReferentialAction" /> to use for deletes.
/// </summary>
public virtual ReferentialAction OnDelete { get; set; }
/// <summary>
/// Creates a new <see cref="AddForeignKeyOperation" /> from the specified foreign key.
/// </summary>
/// <param name="foreignKey">The foreign key.</param>
/// <returns>The operation.</returns>
public static AddForeignKeyOperation CreateFrom(IForeignKeyConstraint foreignKey)
{
Check.NotNull(foreignKey);
var operation = new AddForeignKeyOperation
{
Schema = foreignKey.Table.Schema,
Table = foreignKey.Table.Name,
Name = foreignKey.Name,
Columns = foreignKey.Columns.Select(c => c.Name).ToArray(),
PrincipalSchema = foreignKey.PrincipalTable.Schema,
PrincipalTable = foreignKey.PrincipalTable.Name,
PrincipalColumns = foreignKey.PrincipalColumns.Select(c => c.Name).ToArray(),
OnDelete = foreignKey.OnDeleteAction
};
operation.AddAnnotations(foreignKey.GetAnnotations());
return operation;
}
}
| AddForeignKeyOperation |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.Media/InfiniteCanvas/JsonConverters/SerializableStroke.cs | {
"start": 405,
"end": 638
} | internal class ____
{
[JsonIgnore]
public List<InkPoint> FinalPointList { get; set; }
[JsonIgnore]
public InkDrawingAttributes DrawingAttributesIgnored { get; set; }
// This | SerializableStroke |
csharp | dotnetcore__WTM | src/WalkingTec.Mvvm.Core/Support/ChartData.cs | {
"start": 105,
"end": 417
} | public class ____
{
//一级分类
public string Category { get; set; }
public double Value { get; set; }
//散点图 x值
public double ValueX { get; set; }
//二级分类 不同数据集
public string Series { get; set; }
public double Addition { get; set; }
}
}
| ChartData |
csharp | cake-build__cake | src/Cake.Common.Tests/Fixtures/Tools/Chocolatey/Features/ChocolateyEnableFeatureFixture.cs | {
"start": 320,
"end": 640
} | internal sealed class ____ : ChocolateyFeatureTogglerFixture
{
protected override void RunTool()
{
var tool = new ChocolateyFeatureToggler(FileSystem, Environment, ProcessRunner, Tools, Resolver);
tool.EnableFeature(Name, Settings);
}
}
} | ChocolateyEnableFeatureFixture |
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/DictionaryFillerTest.cs | {
"start": 264,
"end": 5187
} | public class ____
{
[Fact]
public void AddManyToNullSpecimenThrows()
{
// Arrange
var dummyContext = new DelegatingSpecimenContext();
// Act & assert
Assert.Throws<ArgumentNullException>(() =>
DictionaryFiller.AddMany(null, dummyContext));
}
[Fact]
public void AddManyWithNullContextThrows()
{
// Arrange
var dummyDictionary = new Dictionary<object, object>();
// Act & assert
Assert.Throws<ArgumentNullException>(() =>
DictionaryFiller.AddMany(dummyDictionary, null));
}
[Theory]
[InlineData("")]
[InlineData(1)]
[InlineData(true)]
[InlineData(false)]
[InlineData(typeof(object))]
[InlineData(typeof(string))]
[InlineData(typeof(int))]
public void AddManyToNonDictionaryThrows(object specimen)
{
// Arrange
var dummyContext = new DelegatingSpecimenContext();
// Act & assert
Assert.Throws<ArgumentException>(() =>
DictionaryFiller.AddMany(specimen, dummyContext));
}
[Fact]
public void AddManyFillsDictionary()
{
// Arrange
var dictionary = new Dictionary<int, string>();
var expectedRequest = new MultipleRequest(typeof(KeyValuePair<int, string>));
var expectedResult = Enumerable.Range(1, 3).Select(i => new KeyValuePair<int, string>(i, i.ToString()));
var context = new DelegatingSpecimenContext
{
OnResolve = r => expectedRequest.Equals(r) ? (object)expectedResult : new NoSpecimen()
};
// Act
DictionaryFiller.AddMany(dictionary, context);
// Assert
Assert.True(expectedResult.SequenceEqual(dictionary));
}
}
[Fact]
public void SutIsSpecimenCommand()
{
var sut = new DictionaryFiller();
Assert.IsAssignableFrom<ISpecimenCommand>(sut);
}
[Fact]
public void ExecuteNullSpecimenThrows()
{
var sut = new DictionaryFiller();
var dummyContext = new DelegatingSpecimenContext();
Assert.Throws<ArgumentNullException>(() =>
sut.Execute(null, dummyContext));
}
[Fact]
public void ExecuteNullContextThrows()
{
var sut = new DictionaryFiller();
var dummyDictionary = new Dictionary<object, object>();
Assert.Throws<ArgumentNullException>(() =>
sut.Execute(dummyDictionary, null));
}
[Theory]
[InlineData("")]
[InlineData(1)]
[InlineData(true)]
[InlineData(false)]
[InlineData(typeof(object))]
[InlineData(typeof(string))]
[InlineData(typeof(int))]
public void ExecuteNonDictionaryThrows(object specimen)
{
// Arrange
var sut = new DictionaryFiller();
var dummyContext = new DelegatingSpecimenContext();
// Act & assert
Assert.Throws<ArgumentException>(() =>
sut.Execute(specimen, dummyContext));
}
[Fact]
public void ExecuteFillsDictionary()
{
// Arrange
var dictionary = new Dictionary<int, string>();
var expectedRequest = new MultipleRequest(typeof(KeyValuePair<int, string>));
var expectedResult = Enumerable.Range(1, 3).Select(i => new KeyValuePair<int, string>(i, i.ToString()));
var context = new DelegatingSpecimenContext { OnResolve = r => expectedRequest.Equals(r) ? (object)expectedResult : new NoSpecimen() };
var sut = new DictionaryFiller();
// Act
sut.Execute(dictionary, context);
// Assert
Assert.True(expectedResult.SequenceEqual(dictionary));
}
[Fact]
public void DoesNotThrowWithDuplicateEntries()
{
// Arrange
var dictionary = new Dictionary<int, string>();
var request = new MultipleRequest(typeof(KeyValuePair<int, string>));
var sequence = Enumerable.Repeat(0, 3).Select(i => new KeyValuePair<int, string>(i, i.ToString()));
var context = new DelegatingSpecimenContext { OnResolve = r => request.Equals(r) ? (object)sequence : new NoSpecimen() };
var sut = new DictionaryFiller();
// Act & Assert
Assert.Null(Record.Exception(() => sut.Execute(dictionary, context)));
}
}
}
| Obsoleted |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring/Windows/Network/MIB_TCP6TABLE.cs | {
"start": 415,
"end": 516
} | internal struct ____
{
internal uint NumberOfEntries;
internal MIB_TCP6ROW Table;
}
| MIB_TCP6TABLE |
csharp | AvaloniaUI__Avalonia | src/Windows/Avalonia.Win32/Input/Imm32CaretManager.cs | {
"start": 107,
"end": 754
} | internal struct ____
{
private bool _isCaretCreated;
public void TryCreate(IntPtr hwnd)
{
if (!_isCaretCreated)
{
_isCaretCreated = CreateCaret(hwnd, IntPtr.Zero, 2, 2);
}
}
public void TryMove(int x, int y)
{
if (_isCaretCreated)
{
SetCaretPos(x, y);
}
}
public void TryDestroy()
{
if (_isCaretCreated)
{
DestroyCaret();
_isCaretCreated = false;
}
}
}
}
| Imm32CaretManager |
csharp | dotnet__efcore | src/EFCore/Query/LiftableConstantProcessor.cs | {
"start": 14618,
"end": 21458
} | private sealed record ____(ExpressionStatus Status, ParameterExpression? Parameter = null, string? PreferredName = null);
private readonly Dictionary<Expression, ExpressionInfo> _indexedExpressions = new(ExpressionEqualityComparer.Instance);
private LiftedConstant _currentLiftedConstant = null!;
private bool _firstPass;
private int _index;
public void Optimize(List<LiftedConstant> liftedConstants)
{
_liftedConstants = liftedConstants;
_indexedExpressions.Clear();
_firstPass = true;
// Phase 1: recursively seek out tree fragments which appear more than once across the lifted constants. These will be extracted
// out to separate variables.
foreach (var liftedConstant in liftedConstants)
{
_currentLiftedConstant = liftedConstant;
Visit(liftedConstant.Expression);
}
// Filter out fragments which don't appear at least once
foreach (var (expression, expressionInfo) in _indexedExpressions)
{
if (expressionInfo.Status == ExpressionStatus.SeenOnce)
{
_indexedExpressions.Remove(expression);
continue;
}
Check.DebugAssert(
expressionInfo.Status == ExpressionStatus.SeenMultipleTimes);
}
// Second pass: extract common denominator tree fragments to separate variables
_firstPass = false;
for (_index = 0; _index < liftedConstants.Count; _index++)
{
_currentLiftedConstant = _liftedConstants[_index];
if (_indexedExpressions.TryGetValue(_currentLiftedConstant.Expression, out var expressionInfo)
&& expressionInfo.Status == ExpressionStatus.Extracted)
{
// This entire lifted constant has already been extracted before, so we no longer need it as a separate variable.
_liftedConstants[_index] = _currentLiftedConstant with { ReplacingParameter = expressionInfo.Parameter };
continue;
}
var optimizedExpression = Visit(_currentLiftedConstant.Expression);
if (optimizedExpression != _currentLiftedConstant.Expression)
{
_liftedConstants[_index] = _currentLiftedConstant with { Expression = optimizedExpression };
}
}
}
[return: NotNullIfNotNull(nameof(node))]
public override Expression? Visit(Expression? node)
{
if (node is null)
{
return null;
}
if (node is ParameterExpression or ConstantExpression || node.Type.IsAssignableTo(typeof(LambdaExpression)))
{
return node;
}
if (_firstPass)
{
var preferredName = ReferenceEquals(node, _currentLiftedConstant.Expression)
? _currentLiftedConstant.Parameter.Name
: null;
if (!_indexedExpressions.TryGetValue(node, out var expressionInfo))
{
// Unseen expression, add it to the dictionary with a null value, to indicate it's only a candidate at this point.
_indexedExpressions[node] = new ExpressionInfo(ExpressionStatus.SeenOnce, PreferredName: preferredName);
return base.Visit(node);
}
// We've already seen this expression.
if (expressionInfo.Status == ExpressionStatus.SeenOnce
|| expressionInfo.PreferredName is null && preferredName is not null)
{
// This is the 2nd time we're seeing the expression - mark it as a common denominator
_indexedExpressions[node] = _indexedExpressions[node] with
{
Status = ExpressionStatus.SeenMultipleTimes, PreferredName = preferredName
};
}
// We've already seen and indexed this expression, no need to do it again
return node;
}
else
{
// 2nd pass
if (_indexedExpressions.TryGetValue(node, out var expressionInfo) && expressionInfo.Status != ExpressionStatus.SeenOnce)
{
// This fragment is common across multiple lifted constants.
if (expressionInfo.Status == ExpressionStatus.SeenMultipleTimes)
{
// This fragment hasn't yet been extracted out to its own variable in the 2nd pass.
// If this happens to be a top-level node in the lifted constant, no need to extract an additional variable - just
// use that as the "extracted" parameter further down.
if (ReferenceEquals(node, _currentLiftedConstant.Expression))
{
_indexedExpressions[node] = new ExpressionInfo(ExpressionStatus.Extracted, _currentLiftedConstant.Parameter);
return base.Visit(node);
}
// Otherwise, we need to extract a new variable, integrating it just before this one.
var parameter = Expression.Parameter(
node.Type, node switch
{
_ when expressionInfo.PreferredName is not null => expressionInfo.PreferredName,
MemberExpression me => char.ToLowerInvariant(me.Member.Name[0]) + me.Member.Name[1..],
MethodCallExpression mce => char.ToLowerInvariant(mce.Method.Name[0]) + mce.Method.Name[1..],
_ => "unknown"
});
var visitedNode = base.Visit(node);
_liftedConstants.Insert(_index++, new LiftedConstant(parameter, visitedNode));
// Mark this node as having been extracted, to prevent it from getting extracted again
expressionInfo = _indexedExpressions[node] = new ExpressionInfo(ExpressionStatus.Extracted, parameter);
}
Check.DebugAssert(expressionInfo.Parameter is not null);
return expressionInfo.Parameter;
}
// This specific fragment only appears once across the lifted constants; keep going down.
return base.Visit(node);
}
}
| ExpressionInfo |
csharp | dotnet__aspire | src/Aspire.Hosting/ApplicationModel/ConnectionStringAvailableEvent.cs | {
"start": 531,
"end": 880
} | public class ____(IResource resource, IServiceProvider services) : IDistributedApplicationResourceEvent
{
/// <inheritdoc />
public IResource Resource => resource;
/// <summary>
/// The <see cref="IServiceProvider"/> for the app host.
/// </summary>
public IServiceProvider Services => services;
}
| ConnectionStringAvailableEvent |
csharp | dotnet__machinelearning | src/Microsoft.Data.Analysis/PrimitiveDataFrameColumn.BinaryOperationAPIs.ExplodedColumns.cs | {
"start": 834518,
"end": 834854
} | public partial class ____
{
public new UInt32DataFrameColumn LeftShift(int value, bool inPlace = false)
{
var result = (PrimitiveDataFrameColumn<uint>)base.LeftShift(value, inPlace);
return new UInt32DataFrameColumn(result.Name, result.ColumnContainer);
}
}
| UInt32DataFrameColumn |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Saga/InitiateSaga_Specs.cs | {
"start": 5132,
"end": 5996
} | public class ____ :
InMemoryTestFixture
{
[Test]
public async Task An_exception_should_be_thrown()
{
var message = new InitiateSimpleSaga(_sagaId);
await BusSendEndpoint.Send(message);
try
{
await BusSendEndpoint.Send(message);
}
catch (SagaException sex)
{
Assert.That(sex.MessageType, Is.EqualTo(typeof(InitiateSimpleSaga)));
}
}
[OneTimeSetUp]
public void SetUp()
{
_sagaId = Guid.NewGuid();
_repository = new InMemorySagaRepository<SimpleSaga>();
Bus.ConnectSaga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
}
| When_an_existing_saga_receives_an_initiating_message |
csharp | duplicati__duplicati | Duplicati/Library/Main/Enums.cs | {
"start": 3514,
"end": 4122
} | public enum ____
{
/// <summary>
/// The actual type of the entry could not be determined
/// </summary>
Unknown,
/// <summary>
/// The entry is a plain file
/// </summary>
File,
/// <summary>
/// The entry is a folder
/// </summary>
Folder,
/// <summary>
/// The entry is an alternate data stream, or resource/data fork
/// </summary>
AlternateStream,
/// <summary>
/// The entry is a symbolic link
/// </summary>
Symlink
}
}
| FilelistEntryType |
csharp | MahApps__MahApps.Metro | src/MahApps.Metro.Samples/MahApps.Metro.Demo/HamburgerMenuRipple/PrivateView.xaml.cs | {
"start": 345,
"end": 494
} | public partial class ____ : UserControl
{
public PrivateView()
{
this.InitializeComponent();
}
}
} | PrivateView |
csharp | dotnet__maui | src/Graphics/src/Graphics/IPdfPage.cs | {
"start": 203,
"end": 1417
} | public interface ____ : IDrawable, IDisposable
{
/// <summary>
/// Gets the width of the PDF page.
/// </summary>
float Width { get; }
/// <summary>
/// Gets the height of the PDF page.
/// </summary>
float Height { get; }
/// <summary>
/// Gets the page number within the PDF document.
/// </summary>
int PageNumber { get; }
/// <summary>
/// Saves the PDF page to the specified stream.
/// </summary>
/// <param name="stream">The stream to which the page will be saved.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="stream"/> is null.</exception>
/// <exception cref="IOException">Thrown when an I/O error occurs.</exception>
void Save(Stream stream);
/// <summary>
/// Asynchronously saves the PDF page to the specified stream.
/// </summary>
/// <param name="stream">The stream to which the page will be saved.</param>
/// <returns>A task representing the asynchronous save operation.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="stream"/> is null.</exception>
/// <exception cref="IOException">Thrown when an I/O error occurs.</exception>
Task SaveAsync(Stream stream);
}
}
| IPdfPage |
csharp | dotnet__aspire | tests/Aspire.Microsoft.EntityFrameworkCore.SqlServer.Tests/AspireSqlServerEFCoreSqlClientExtensionsTests.cs | {
"start": 585,
"end": 15511
} | public class ____
{
private const string ConnectionString = "Data Source=fake;Initial Catalog=master;Encrypt=True";
[Fact]
public void ReadsFromConnectionStringsCorrectly()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection");
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
AssertCorrectConnectionString(ConnectionString, context.Database.GetDbConnection().ConnectionString);
}
[Fact]
public void ConnectionStringCanBeSetInCode()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", "unused")
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection", settings => settings.ConnectionString = ConnectionString);
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
var actualConnectionString = context.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(ConnectionString, actualConnectionString);
// the connection string from config should not be used since code set it explicitly
Assert.DoesNotContain("unused", actualConnectionString);
}
[Fact]
public void ConnectionNameWinsOverConfigSection()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:ConnectionString", "unused"),
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection");
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
var actualConnectionString = context.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(ConnectionString, actualConnectionString);
// the connection string from config should not be used since it was found in ConnectionStrings
Assert.DoesNotContain("unused", actualConnectionString);
}
[Fact]
public void CanConfigureDbContextOptions()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString),
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:DisableRetry", "false"),
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:CommandTimeout", "608")
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection", configureDbContextOptions: optionsBuilder =>
{
optionsBuilder.UseSqlServer(sqlBuilder =>
{
sqlBuilder.MinBatchSize(123);
});
});
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
#pragma warning disable EF1001 // Internal EF Core API usage.
var extension = context.Options.FindExtension<SqlServerOptionsExtension>();
Assert.NotNull(extension);
// ensure the min batch size was respected
Assert.Equal(123, extension.MinBatchSize);
// ensure the connection string from config was respected
var actualConnectionString = context.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(ConnectionString, actualConnectionString);
// ensure the retry strategy is enabled and set to its default value
Assert.NotNull(extension.ExecutionStrategyFactory);
var executionStrategy = extension.ExecutionStrategyFactory(new ExecutionStrategyDependencies(new CurrentDbContext(context), context.Options, null!));
var retryStrategy = Assert.IsType<SqlServerRetryingExecutionStrategy>(executionStrategy);
Assert.Equal(new WorkaroundToReadProtectedField(context).MaxRetryCount, retryStrategy.MaxRetryCount);
// ensure the command timeout from config was respected
Assert.Equal(608, extension.CommandTimeout);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
[Fact]
public void CanConfigureDbContextOptionsWithoutRetry()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString),
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:DisableRetry", "true"),
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection", configureDbContextOptions: optionsBuilder =>
{
optionsBuilder.UseSqlServer(sqlBuilder =>
{
sqlBuilder.CommandTimeout(123);
});
});
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
#pragma warning disable EF1001 // Internal EF Core API usage.
var extension = context.Options.FindExtension<SqlServerOptionsExtension>();
Assert.NotNull(extension);
// ensure the command timeout was respected
Assert.Equal(123, extension.CommandTimeout);
// ensure the connection string from config was respected
var actualConnectionString = context.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(ConnectionString, actualConnectionString);
// ensure no retry strategy was registered
Assert.Null(extension.ExecutionStrategyFactory);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CanConfigureCommandTimeout(bool useSettings)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
if (!useSettings)
{
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:CommandTimeout", "608")
]);
}
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection",
configureDbContextOptions: optionsBuilder => optionsBuilder.UseSqlServer(),
configureSettings: useSettings ? settings => settings.CommandTimeout = 608 : null);
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
#pragma warning disable EF1001 // Internal EF Core API usage.
var extension = context.Options.FindExtension<SqlServerOptionsExtension>();
Assert.NotNull(extension);
// ensure the command timeout was respected
Assert.Equal(608, extension.CommandTimeout);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CommandTimeoutFromBuilderWinsOverOthers(bool useSettings)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
if (!useSettings)
{
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("Aspire:Microsoft:EntityFrameworkCore:SqlServer:CommandTimeout", "400")
]);
}
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection",
configureDbContextOptions: optionsBuilder =>
optionsBuilder.UseSqlServer(builder => builder.CommandTimeout(123)),
configureSettings: useSettings ? settings => settings.CommandTimeout = 300 : null);
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
#pragma warning disable EF1001 // Internal EF Core API usage.
var extension = context.Options.FindExtension<SqlServerOptionsExtension>();
Assert.NotNull(extension);
// ensure the command timeout from builder was respected
Assert.Equal(123, extension.CommandTimeout);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
/// <summary>
/// Verifies that two different DbContexts can be registered with different connection strings.
/// </summary>
[Fact]
public void CanHave2DbContexts()
{
const string connectionString2 = "Data Source=fake2;Initial Catalog=master2;Encrypt=True";
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString),
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection2", connectionString2),
]);
builder.AddSqlServerDbContext<TestDbContext>("sqlconnection");
builder.AddSqlServerDbContext<TestDbContext2>("sqlconnection2");
using var host = builder.Build();
var context = host.Services.GetRequiredService<TestDbContext>();
var context2 = host.Services.GetRequiredService<TestDbContext2>();
var actualConnectionString = context.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(ConnectionString, actualConnectionString);
actualConnectionString = context2.Database.GetDbConnection().ConnectionString;
AssertCorrectConnectionString(connectionString2, actualConnectionString);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ThrowsWhenDbContextIsRegisteredBeforeAspireComponent(bool useServiceType)
{
var builder = Host.CreateEmptyApplicationBuilder(new HostApplicationBuilderSettings { EnvironmentName = Environments.Development });
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
if (useServiceType)
{
builder.Services.AddDbContextPool<ITestDbContext, TestDbContext>(options => options.UseSqlServer(ConnectionString));
}
else
{
builder.Services.AddDbContextPool<TestDbContext>(options => options.UseSqlServer(ConnectionString));
}
var exception = Assert.Throws<InvalidOperationException>(() => builder.AddSqlServerDbContext<TestDbContext>("sqlconnection"));
Assert.Equal("DbContext<TestDbContext> is already registered. Please ensure 'services.AddDbContext<TestDbContext>()' is not used when calling 'AddSqlServerDbContext()' or use the corresponding 'Enrich' method.", exception.Message);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void DoesntThrowWhenDbContextIsRegisteredBeforeAspireComponentProduction(bool useServiceType)
{
var builder = Host.CreateEmptyApplicationBuilder(new HostApplicationBuilderSettings { EnvironmentName = Environments.Production });
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:sqlconnection", ConnectionString)
]);
if (useServiceType)
{
builder.Services.AddDbContextPool<ITestDbContext, TestDbContext>(options => options.UseSqlServer(ConnectionString));
}
else
{
builder.Services.AddDbContextPool<TestDbContext>(options => options.UseSqlServer(ConnectionString));
}
var exception = Record.Exception(() => builder.AddSqlServerDbContext<TestDbContext>("sqlconnection"));
Assert.Null(exception);
}
[Fact]
public void AddSqlServerDbContext_WithConnectionNameAndSettings_AppliesConnectionSpecificSettings()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
var connectionName = "testdb";
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
[$"ConnectionStrings:{connectionName}"] = ConnectionString,
[$"Aspire:Microsoft:EntityFrameworkCore:SqlServer:{connectionName}:CommandTimeout"] = "60",
[$"Aspire:Microsoft:EntityFrameworkCore:SqlServer:{connectionName}:DisableTracing"] = "true"
});
MicrosoftEntityFrameworkCoreSqlServerSettings? capturedSettings = null;
builder.AddSqlServerDbContext<TestDbContext>(connectionName, settings =>
{
capturedSettings = settings;
});
Assert.NotNull(capturedSettings);
Assert.Equal(60, capturedSettings.CommandTimeout);
Assert.True(capturedSettings.DisableTracing);
}
[Fact]
public void AddSqlServerDbContext_WithConnectionSpecificAndContextSpecificSettings_PrefersContextSpecific()
{
// Arrange
var builder = Host.CreateEmptyApplicationBuilder(null);
var connectionName = "testdb";
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
[$"ConnectionStrings:{connectionName}"] = ConnectionString,
// Connection-specific settings
[$"Aspire:Microsoft:EntityFrameworkCore:SqlServer:{connectionName}:CommandTimeout"] = "60",
// Context-specific settings wins
[$"Aspire:Microsoft:EntityFrameworkCore:SqlServer:TestDbContext:CommandTimeout"] = "120"
});
MicrosoftEntityFrameworkCoreSqlServerSettings? capturedSettings = null;
builder.AddSqlServerDbContext<TestDbContext>(connectionName, settings =>
{
capturedSettings = settings;
});
Assert.NotNull(capturedSettings);
Assert.Equal(120, capturedSettings.CommandTimeout);
}
private static void AssertCorrectConnectionString(string expectedConnectionString, string actualConnectionString)
{
#if NET10_0_OR_GREATER
// In .NET 10, the connection string may have additional parameters appended, so we check the start only.
Assert.StartsWith(expectedConnectionString, actualConnectionString);
#else
Assert.Equal(expectedConnectionString, actualConnectionString);
#endif
}
| AspireSqlServerEFCoreSqlClientExtensionsTests |
csharp | dotnet__efcore | src/EFCore/ChangeTracking/Internal/IIdentityMap`.cs | {
"start": 654,
"end": 1243
} | public interface ____<in TKey> : IIdentityMap
{
/// <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>
InternalEntityEntry? TryGetEntryTyped(TKey keyValue);
}
| IIdentityMap |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | {
"start": 1955,
"end": 2920
} | public class ____
{
public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
{
#if !(DNXCORE50)
return type.GetConstructors();
#else
return type.GetTypeInfo().DeclaredConstructors;
#endif
}
public static PropertyInfo GetProperty(Type type, string name)
{
#if !(DNXCORE50)
return type.GetProperty(name);
#else
return type.GetTypeInfo().GetDeclaredProperty(name);
#endif
}
public static FieldInfo GetField(Type type, string name)
{
#if !(DNXCORE50)
return type.GetField(name);
#else
return type.GetTypeInfo().GetDeclaredField(name);
#endif
}
public static MethodInfo GetMethod(Type type, string name)
{
#if !(DNXCORE50)
return type.GetMethod(name);
#else
return type.GetTypeInfo().GetDeclaredMethod(name);
#endif
}
}
#if DNXCORE50
| TestReflectionUtils |
csharp | FastEndpoints__FastEndpoints | Benchmark/FastEndpointsBench/CodeGenEndpoint.cs | {
"start": 262,
"end": 504
} | public class ____
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int Age { get; set; }
public IEnumerable<string>? PhoneNumbers { get; set; }
}
| CodeGenRequest |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.NetFramework/MiniProfiler/Helpers/StackTraceSnippet.cs | {
"start": 269,
"end": 1866
} | public class ____
{
private const string AspNetEntryPointMethodName = "System.Web.HttpApplication.IExecutionStep.Execute";
/// <summary>
/// Gets the current formatted and filted stack trace.
/// </summary>
/// <returns>Space separated list of methods</returns>
public static string Get()
{
var frames = new StackTrace().GetFrames();
if (frames == null)
{
return "";
}
var methods = new List<string>();
foreach (StackFrame t in frames)
{
var method = t.GetMethod();
// no need to continue up the chain
if (method.Name == AspNetEntryPointMethodName)
break;
var assembly = method.Module.Assembly.GetName().Name;
if (!MiniProfiler.Settings.AssembliesToExclude.Contains(assembly) &&
!ShouldExcludeType(method) &&
!MiniProfiler.Settings.MethodsToExclude.Contains(method.Name))
{
methods.Add(method.Name);
}
}
var result = string.Join(" ", methods.ToArray());
if (result.Length > MiniProfiler.Settings.StackMaxLength)
{
var index = result.IndexOf(" ", MiniProfiler.Settings.StackMaxLength);
if (index >= MiniProfiler.Settings.StackMaxLength)
{
result = result.Substring(0, index);
}
}
return result;
}
private static bool ShouldExcludeType(MethodBase method)
{
var t = method.DeclaringType;
while (t != null)
{
if (MiniProfiler.Settings.TypesToExclude.Contains(t.Name))
return true;
t = t.DeclaringType;
}
return false;
}
}
}
#endif
| StackTraceSnippet |
csharp | moq__moq4 | src/Moq.Tests/CallbackDelegateValidationFixture.cs | {
"start": 3093,
"end": 3178
} | public interface ____
{
void Action(int x);
}
}
| IFoo |
csharp | abpframework__abp | modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissions.cs | {
"start": 164,
"end": 553
} | public static class ____
{
public const string Default = GroupName + ".Projects";
public const string Delete = Default + ".Delete";
public const string Update = Default + ".Update";
public const string Create = Default + ".Create";
public const string ManagePdfFiles = Default + ".ManagePdfFiles";
}
| Projects |
csharp | NLog__NLog | src/NLog/Config/DefaultParameterAttribute.cs | {
"start": 1907,
"end": 2181
} | public sealed class ____ : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultParameterAttribute" /> class.
/// </summary>
public DefaultParameterAttribute()
{
}
}
}
| DefaultParameterAttribute |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/DataView/CacheDataView.cs | {
"start": 44756,
"end": 47526
} | private sealed class ____<TWaiter> : IIndex
where TWaiter : struct, IWaiter
{
// -1 means not started, -2 means finished, non-negative is the index into _perm.
private int _curr;
private int _currMax;
private readonly int[] _perm;
private readonly JobScheduler _scheduler;
private readonly TWaiter _waiter;
private long _batch;
public long Batch { get { return _batch; } }
private BlockRandomIndex(TWaiter waiter, JobScheduler scheduler, int[] perm)
{
Contracts.AssertValue(scheduler);
Contracts.AssertValue(perm);
_curr = _currMax = -1;
_batch = -1;
_perm = perm;
_waiter = waiter;
_scheduler = scheduler;
}
public long GetIndex()
{
Contracts.Assert(0 <= _curr && _curr < _perm.Length);
return _perm[_curr];
}
public ValueGetter<DataViewRowId> GetIdGetter()
{
return
(ref DataViewRowId val) =>
{
Contracts.Check(_curr >= 0, "Cannot call ID getter in current state");
val = new DataViewRowId((ulong)_perm[_curr], 0);
};
}
public bool MoveNext()
{
Contracts.Assert(_curr >= -1); // Should not be called when _curr = -2.
if (_curr == _currMax)
{
// Try to get an available block for processing.
_batch = _scheduler.GetAvailableJob(_batch);
_curr = (int)(_batch << _batchShift);
// We've run off the end (possibly by overflowing), exit.
if (_curr >= _perm.Length || _curr < 0)
{
// We're ending.
_curr = -2;
return false;
}
// Try to get the next block length.
_currMax = Math.Min(_perm.Length - 1, _curr + _batchMask);
}
else
_curr++;
Contracts.Assert(0 <= _curr && _curr <= _currMax);
bool result = _waiter.Wait(GetIndex());
Contracts.Assert(result);
return true;
}
public static Wrapper Create(TWaiter waiter, JobScheduler scheduler, int[] perm)
{
return new Wrapper(new BlockRandomIndex<TWaiter>(waiter, scheduler, perm));
}
public readonly | BlockRandomIndex |
csharp | Testably__Testably.Abstractions | Tests/Testably.Abstractions.Tests/FileSystem/Path/GetDirectoryNameTests.cs | {
"start": 74,
"end": 6127
} | public partial class ____
{
[Theory]
[InlineData((string?)null)]
#if !NETFRAMEWORK
[InlineData("")]
#endif
public async Task GetDirectoryName_NullOrEmpty_ShouldReturnNull(string? path)
{
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsNull();
}
#if NETFRAMEWORK
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData(" ")]
[InlineData("\t")]
[InlineData("\n")]
public async Task GetDirectoryName_EmptyOrWhiteSpace_ShouldThrowArgumentException(string path)
{
void Act()
{
_ = FileSystem.Path.GetDirectoryName(path);
}
await That(Act).Throws<ArgumentException>();
}
#endif
#if !NETFRAMEWORK
[Theory]
[InlineData(" ")]
[InlineData(" ")]
public async Task GetDirectoryName_Spaces_ShouldReturnNullOnWindowsOtherwiseEmpty(string? path)
{
string? result = FileSystem.Path.GetDirectoryName(path);
if (Test.RunsOnWindows)
{
await That(result).IsNull();
}
else
{
await That(result).IsEqualTo("");
}
}
#endif
#if !NETFRAMEWORK
[Theory]
[InlineData("\t")]
[InlineData("\n")]
[InlineData(" \t")]
[InlineData("\n ")]
public async Task GetDirectoryName_TabOrNewline_ShouldReturnEmptyString(string? path)
{
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsEqualTo("");
}
#endif
[Theory]
[AutoData]
public async Task GetDirectoryName_ShouldReturnDirectory(
string directory, string filename, string extension)
{
string path = directory + FileSystem.Path.DirectorySeparatorChar + filename +
"." + extension;
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsEqualTo(directory);
}
[Theory]
[AutoData]
public async Task GetDirectoryName_ShouldReplaceAltDirectorySeparator(
string parentDirectory, string directory, string filename)
{
string path = parentDirectory + FileSystem.Path.AltDirectorySeparatorChar + directory +
FileSystem.Path.AltDirectorySeparatorChar + filename;
string expected = parentDirectory + FileSystem.Path.DirectorySeparatorChar + directory;
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsEqualTo(expected);
}
[Theory]
[InlineData("foo//bar/file", "foo/bar", TestOS.All)]
[InlineData("foo///bar/file", "foo/bar", TestOS.All)]
[InlineData("//foo//bar/file", "/foo/bar", TestOS.Linux | TestOS.Mac)]
[InlineData(@"foo\\bar/file", "foo/bar", TestOS.Windows)]
[InlineData(@"foo\\\bar/file", "foo/bar", TestOS.Windows)]
public async Task GetDirectoryName_ShouldNormalizeDirectorySeparators(
string path, string expected, TestOS operatingSystem)
{
Skip.IfNot(Test.RunsOn(operatingSystem));
expected = expected.Replace('/', FileSystem.Path.DirectorySeparatorChar);
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsEqualTo(expected);
}
#if FEATURE_SPAN
[Theory]
[AutoData]
public async Task GetDirectoryName_Span_ShouldReturnDirectory(
string directory, string filename, string extension)
{
string path = directory + FileSystem.Path.DirectorySeparatorChar + filename +
"." + extension;
ReadOnlySpan<char> result = FileSystem.Path.GetDirectoryName(path.AsSpan());
await That(result.ToString()).IsEqualTo(directory);
}
#endif
[Theory]
[InlineData("//", null, TestOS.Windows)]
[InlineData(@"\\", null, TestOS.Windows)]
[InlineData(@"\\", "", TestOS.Linux | TestOS.Mac)]
[InlineData(@"\", "", TestOS.Linux | TestOS.Mac)]
[InlineData(@"/", null, TestOS.Linux | TestOS.Mac)]
[InlineData(@"/a", "/", TestOS.Linux | TestOS.Mac)]
[InlineData(@"/a\b", @"/", TestOS.Linux | TestOS.Mac)]
[InlineData(@"/a\b/c", @"/a\b", TestOS.Linux | TestOS.Mac)]
[InlineData(@"/a/b/c", @"/a/b", TestOS.Linux | TestOS.Mac)]
[InlineData(@"/a/b", "/a", TestOS.Linux | TestOS.Mac)]
[InlineData("//?/G:/", null, TestOS.Windows)]
[InlineData("/??/H:/", @"\??\H:", TestOS.Windows)]
[InlineData("//?/I:/a", @"\\?\I:\", TestOS.Windows)]
[InlineData("/??/J:/a", @"\??\J:", TestOS.Windows)]
[InlineData(@"\\?\K:\", null, TestOS.Windows)]
[InlineData(@"\??\L:\", null, TestOS.Windows)]
[InlineData(@"\\?\M:\a", @"\\?\M:\", TestOS.Windows)]
[InlineData(@"\??\N:\a", @"\??\N:\", TestOS.Windows)]
[InlineData(@"\\?\UNC\", null, TestOS.Windows)]
[InlineData(@"//?/UNC/", null, TestOS.Windows)]
[InlineData(@"\??\UNC\", null, TestOS.Windows)]
[InlineData(@"/??/UNC/", @"\??\UNC", TestOS.Windows)]
[InlineData(@"\\?\UNC\a", null, TestOS.Windows)]
[InlineData(@"//?/UNC/a", null, TestOS.Windows)]
[InlineData(@"\??\UNC\a", null, TestOS.Windows)]
[InlineData(@"/??/UNC/a", @"\??\UNC", TestOS.Windows)]
[InlineData(@"\\?\ABC\", null, TestOS.Windows)]
[InlineData(@"//?/ABC/", null, TestOS.Windows)]
[InlineData(@"\??\XYZ\", null, TestOS.Windows)]
[InlineData(@"/??/XYZ/", @"\??\XYZ", TestOS.Windows)]
[InlineData(@"\\?\unc\a", @"\\?\unc\", TestOS.Windows)]
[InlineData(@"//?/unc/a", @"\\?\unc\", TestOS.Windows)]
[InlineData(@"\??\unc\a", @"\??\unc\", TestOS.Windows)]
[InlineData(@"/??/unc/a", @"\??\unc", TestOS.Windows)]
[InlineData("//./", null, TestOS.Windows)]
[InlineData(@"\\.\", null, TestOS.Windows)]
[InlineData("//?/", null, TestOS.Windows)]
[InlineData(@"\\?\", null, TestOS.Windows)]
[InlineData("//a/", null, TestOS.Windows)]
[InlineData(@"\\a\", null, TestOS.Windows)]
[InlineData(@"C:", null, TestOS.Windows)]
[InlineData(@"D:\", null, TestOS.Windows)]
[InlineData(@"E:/", null, TestOS.Windows)]
[InlineData(@"F:\a", @"F:\", TestOS.Windows)]
[InlineData(@"F:\b\c", @"F:\b", TestOS.Windows)]
[InlineData(@"F:\d/e", @"F:\d", TestOS.Windows)]
[InlineData(@"G:/f", @"G:\", TestOS.Windows)]
[InlineData(@"F:/g\h", @"F:\g", TestOS.Windows)]
[InlineData(@"G:/i/j", @"G:\i", TestOS.Windows)]
public async Task GetDirectoryName_SpecialCases_ShouldReturnExpectedValue(
string path, string? expected, TestOS operatingSystem)
{
Skip.IfNot(Test.RunsOn(operatingSystem));
string? result = FileSystem.Path.GetDirectoryName(path);
await That(result).IsEqualTo(expected);
}
}
| GetDirectoryNameTests |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Subscription/ObservableExtensionsTests.cs | {
"start": 138,
"end": 10043
} | public class ____
{
private SampleObservable<string> Source { get; } = new();
private SampleObserver Observer { get; } = new();
[Fact]
public async Task DataInOrder()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
async (error, token) =>
{
error.Message.ShouldBe("abc");
return new ApplicationException();
});
observable.Subscribe(Observer);
Source.Next("200");
Source.Next("0");
Source.Error(new Exception("abc"));
Source.Next("300");
Source.Completed();
await Observer.WaitForAsync("Next '200'. Next '0'. Error 'ApplicationException'. Next '300'. Completed. ");
}
[Fact]
public async Task ExceptionsInDataTransformAreTransformed_Async()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
(error, token) => throw new NotSupportedException());
observable.Subscribe(Observer);
Source.Next("200");
Source.Next("aa");
await Observer.WaitForAsync("Next '200'. Error 'FormatException'. ");
}
[Fact]
public async Task ExceptionsInDataTransformAreTransformed_Sync()
{
var observable = Source
.SelectCatchAsync(
(data, token) =>
{
int s = int.Parse(data);
Thread.Sleep(s);
return new ValueTask<string>(data);
},
(error, token) => throw new NotSupportedException());
observable.Subscribe(Observer);
Source.Next("200");
Source.Next("aa");
await Observer.WaitForAsync("Next '200'. Error 'FormatException'. ");
}
[Fact]
public async Task ExceptionsInErrorTransformArePassedThrough_Async()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
async (error, token) =>
{
await Task.Delay(200);
return new FormatException();
});
observable.Subscribe(Observer);
Source.Next("200");
Source.Error(new ApplicationException());
await Observer.WaitForAsync("Next '200'. Error 'FormatException'. ");
}
[Fact]
public async Task ExceptionsInErrorTransformArePassedThrough_Sync()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
(error, token) => throw new FormatException());
observable.Subscribe(Observer);
Source.Next("200");
Source.Error(new ApplicationException());
await Observer.WaitForAsync("Next '200'. Error 'FormatException'. ");
}
[Fact]
public async Task ImmediateSend()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
(error, token) => throw error);
observable.Subscribe(Observer);
Source.Completed();
Source.Next("0");
Source.Next("200");
await Observer.WaitForAsync("Completed. Next '0'. Next '200'. ");
}
[Fact]
public async Task SendPauseSend()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
(error, token) => throw error);
observable.Subscribe(Observer);
Source.Next("10");
await Task.Delay(500);
Source.Next("20");
await Observer.WaitForAsync("Next '10'. Next '20'. ");
}
[Fact]
public void SendSynchronously()
{
// validates that if the transformations execute synchronously,
// nothing gets scheduled on the task scheduler
var observable = Source
.SelectCatchAsync(
(data, token) => new ValueTask<string>(data),
(error, token) => error is ApplicationException ? throw error : new ValueTask<Exception>(new DivideByZeroException()));
observable.Subscribe(Observer);
Source.Next("a");
Source.Error(new ApplicationException());
Source.Next("b");
Source.Error(new InvalidTimeZoneException());
Source.Completed();
Observer.Current.ShouldBe("Next 'a'. Error 'ApplicationException'. Next 'b'. Error 'DivideByZeroException'. Completed. ");
}
[Fact]
public async Task CanceledSubscriptionsDontSendData()
{
var observable = Source
.SelectCatchAsync(
(data, token) => new ValueTask<string>(data),
(error, token) => error is ApplicationException ? throw error : new ValueTask<Exception>(new DivideByZeroException()));
var subscription = observable.Subscribe(Observer);
Source.Next("test");
Observer.Current.ShouldBe("Next 'test'. ");
subscription.Dispose();
Source.Next("a");
Source.Error(new ApplicationException());
Source.Next("b");
Source.Error(new InvalidTimeZoneException());
Source.Next("c");
Source.Completed();
await Task.Delay(200); // just in case, but should execute synchronously anyway
Observer.Current.ShouldBe("Next 'test'. ");
}
[Fact]
public async Task CanceledSubscriptionsDontSendPendingData()
{
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
int s = int.Parse(data);
await Task.Delay(s);
return data;
},
(error, token) => new ValueTask<Exception>(error));
var subscription = observable.Subscribe(Observer);
Source.Next("200"); // if the value is 0, it completes synchronously, and the test would fail
Source.Next("200"); // another asynchronous event
Source.Error(new ExecutionError("test")); // a completed synchronous transformation, but in the queue after one with a delay
subscription.Dispose();
Observer.Current.ShouldBe("");
await Task.Delay(1000);
Observer.Current.ShouldBe("");
}
[Fact]
public async Task CanceledSubscriptionsDontTransform()
{
bool transformed = false;
bool disposed = false;
var observable = Source
.SelectCatchAsync(
async (data, token) =>
{
transformed = disposed;
return data;
},
async (error, token) =>
{
transformed = disposed;
return error;
});
var subscription = observable.Subscribe(Observer);
Source.Next("test");
Source.Error(new DivideByZeroException());
Observer.Current.ShouldBe("Next 'test'. Error 'DivideByZeroException'. ");
subscription.Dispose();
disposed = true;
Source.Next("a");
Source.Error(new ApplicationException());
Source.Next("b");
Source.Error(new InvalidTimeZoneException());
Source.Next("c");
Source.Completed();
await Task.Delay(200); // just in case, but should execute synchronously anyway
Observer.Current.ShouldBe("Next 'test'. Error 'DivideByZeroException'. ");
transformed.ShouldBeFalse();
}
[Fact]
public void CanCallDisposeTwice()
{
var observable = Source
.SelectCatchAsync(
async (data, token) => data,
async (error, token) => error);
var subscription = observable.Subscribe(Observer);
subscription.Dispose();
subscription.Dispose();
}
[Fact]
public void NullArgumentsThrow()
{
var observableSuccess = Source.SelectCatchAsync<string, string>((_, _) => default, (_, _) => default);
Should.Throw<ArgumentNullException>(() =>
{
var observableFail = Source.SelectCatchAsync<string, string>(null!, (_, _) => default);
});
Should.Throw<ArgumentNullException>(() =>
{
var observableFail = Source.SelectCatchAsync<string, string>((_, _) => default, default!);
});
Should.Throw<ArgumentNullException>(() =>
{
var observableFail = ((IObservable<string>)null!).SelectCatchAsync<string, string>((_, _) => default, (_, _) => default);
});
}
[Fact]
public async Task ExceptionsDuringSubscribeProduceOnError()
{
var errorObservable = new ErrorObservable();
var observable = errorObservable.SelectCatchAsync<string, string>((s, _) => new(s), (ex, _) => new(new ExecutionError(ex.Message)));
using var subscription = observable.Subscribe(Observer);
await Observer.WaitForAsync("Error 'ExecutionError'. ");
}
| ObservableExtensionsTests |
csharp | dotnet__aspnetcore | src/Features/JsonPatch.SystemTextJson/src/Internal/ListAdapter.cs | {
"start": 9350,
"end": 9595
} | struct ____
{
public PositionInfo(PositionType type, int index)
{
Type = type;
Index = index;
}
public PositionType Type { get; }
public int Index { get; }
}
| PositionInfo |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Credentials/PasswordCredential.cs | {
"start": 263,
"end": 2255
} | public partial class ____
{
// Skipping already declared property UserName
// Skipping already declared property Resource
// Skipping already declared property Password
#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.Collections.IPropertySet Properties
{
get
{
throw new global::System.NotImplementedException("The member IPropertySet PasswordCredential.Properties is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IPropertySet%20PasswordCredential.Properties");
}
}
#endif
// Skipping already declared method Windows.Security.Credentials.PasswordCredential.PasswordCredential(string, string, string)
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.PasswordCredential(string, string, string)
// Skipping already declared method Windows.Security.Credentials.PasswordCredential.PasswordCredential()
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.PasswordCredential()
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.Resource.get
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.Resource.set
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.UserName.get
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.UserName.set
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.Password.get
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.Password.set
// Skipping already declared method Windows.Security.Credentials.PasswordCredential.RetrievePassword()
// Forced skipping of method Windows.Security.Credentials.PasswordCredential.Properties.get
}
}
| PasswordCredential |
csharp | dotnet__BenchmarkDotNet | src/BenchmarkDotNet/Toolchains/Mono/MonoAotToolchain.cs | {
"start": 339,
"end": 2690
} | public class ____ : Toolchain
{
public static readonly IToolchain Instance = new MonoAotToolchain();
[PublicAPI]
public MonoAotToolchain() : base("MonoAot", new Generator(), new MonoAotBuilder(), new Executor())
{
}
public override IEnumerable<ValidationError> Validate(BenchmarkCase benchmarkCase, IResolver resolver)
{
foreach (var validationError in base.Validate(benchmarkCase, resolver))
{
yield return validationError;
}
if (!benchmarkCase.Job.Environment.HasValue(EnvironmentMode.RuntimeCharacteristic) || benchmarkCase.Job.Environment.Runtime is not MonoRuntime)
{
yield return new ValidationError(true,
"The MonoAOT toolchain requires the Runtime property to be configured explicitly to an instance of MonoRuntime class",
benchmarkCase);
}
if ((benchmarkCase.Job.Environment.Runtime is MonoRuntime monoRuntime) && !string.IsNullOrEmpty(monoRuntime.MonoBclPath) && !Directory.Exists(monoRuntime.MonoBclPath))
{
yield return new ValidationError(true,
$"The MonoBclPath provided for MonoAOT toolchain: {monoRuntime.MonoBclPath} does NOT exist.",
benchmarkCase);
}
if (benchmarkCase.Job.HasValue(InfrastructureMode.BuildConfigurationCharacteristic)
&& benchmarkCase.Job.ResolveValue(InfrastructureMode.BuildConfigurationCharacteristic, resolver) != InfrastructureMode.ReleaseConfigurationName)
{
yield return new ValidationError(true,
"The MonoAOT toolchain does not allow to rebuild source project, so defining custom build configuration makes no sense",
benchmarkCase);
}
#pragma warning disable CS0618 // Type or member is obsolete
if (benchmarkCase.Job.HasValue(InfrastructureMode.NuGetReferencesCharacteristic))
{
yield return new ValidationError(true,
"The MonoAOT toolchain does not allow specifying NuGet package dependencies",
benchmarkCase);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
}
} | MonoAotToolchain |
csharp | nunit__nunit | src/NUnitFramework/testdata/DerivedClassWithTestsInBaseClass.cs | {
"start": 932,
"end": 1056
} | public abstract class ____
{
[Test]
public abstract void VirtualTestInBaseClass();
}
}
| AbstractBaseClass |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/ClientAPI/read_allevents_backward_with_linkto_deleted_event.cs | {
"start": 1186,
"end": 1907
} | public class ____<TLogFormat, TStreamId> : SpecificationWithLinkToToDeletedEvents<TLogFormat, TStreamId> {
private StreamEventsSlice _read;
protected override async Task When() {
_read = await _conn.ReadStreamEventsBackwardAsync(LinkedStreamName, 0, 1, true, null);
}
[Test]
public void one_event_is_read() {
Assert.AreEqual(1, _read.Events.Length);
}
[Test]
public void the_linked_event_is_not_resolved() {
Assert.IsNull(_read.Events[0].Event);
}
[Test]
public void the_link_event_is_included() {
Assert.IsNotNull(_read.Events[0].OriginalEvent);
}
[Test]
public void the_event_is_not_resolved() {
Assert.IsFalse(_read.Events[0].IsResolved);
}
}
| read_allevents_backward_with_linkto_deleted_event |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/Product.cs | {
"start": 1217,
"end": 1851
} | public class ____
{
public string Name;
public DateTime ExpiryDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public decimal Price;
public string[] Sizes;
public override bool Equals(object obj)
{
if (obj is Product)
{
Product p = (Product)obj;
return (p.Name == Name && p.ExpiryDate == ExpiryDate && p.Price == Price);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return (Name ?? string.Empty).GetHashCode();
}
}
} | Product |
csharp | files-community__Files | src/Files.App/Actions/Display/GroupAction.cs | {
"start": 479,
"end": 818
} | partial class ____ : GroupByAction
{
protected override GroupOption GroupOption
=> GroupOption.Name;
public override string Label
=> Strings.Name.GetLocalizedResource();
public override string Description
=> Strings.GroupByNameDescription.GetLocalizedResource();
}
[GeneratedRichCommand]
internal sealed | GroupByNameAction |
csharp | dotnet__machinelearning | test/Microsoft.ML.Core.Tests/UnitTests/TestVBuffer.cs | {
"start": 45141,
"end": 46153
} | private enum ____ : byte
{
BothDense,
ASparseBDense,
ADenseBSparse,
BothSparseASameB,
BothSparseASubsetB,
BothSparseBSubsetA,
BothSparseAUnrelatedB,
BothSparseADisjointB,
}
/// <summary>
/// Generates a pair of vectors, where the pairs are generated in such a way that we
/// have a good chance (across many trials) to exercise all of the special casing logic
/// we see in <see cref="VectorUtils"/> and <see cref="VBufferUtils"/>, e.g., various
/// density/sparsity settings, different ways of the indices overlapping each other, etc.
/// </summary>
/// <param name="rgen">The random number generator</param>
/// <param name="len">The length of the vectors to generate</param>
/// <param name="a">The first of the pair</param>
/// <param name="b">The second of the pair</param>
/// <param name="subcase">An | GenLogic |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Bugs/BubbleUpTheNullToNextNullable.cs | {
"start": 12602,
"end": 12856
} | public class ____
{
public string? Nullable { get; set; }
public Data? NullableNest { get; set; }
public string? NonNullable { get; set; }
public Data? NonNullableNest { get; set; }
public List<string?>? ListOfStrings { get; set; }
}
| Data |
csharp | DuendeSoftware__IdentityServer | identity-server/clients/src/APIs/MtlsApi/ConfirmationValidationMiddleware.cs | {
"start": 913,
"end": 2491
} | public class ____(
RequestDelegate next,
ILogger<ConfirmationValidationMiddlewareOptions> logger,
ConfirmationValidationMiddlewareOptions? options = null)
{
private readonly ILogger _logger = logger;
private readonly ConfirmationValidationMiddlewareOptions _options = options ?? new ConfirmationValidationMiddlewareOptions();
public async Task Invoke(HttpContext ctx)
{
if (ctx.User.Identity!.IsAuthenticated)
{
var cnfJson = ctx.User.FindFirst("cnf")?.Value;
if (!string.IsNullOrWhiteSpace(cnfJson))
{
var certificate = await ctx.Connection.GetClientCertificateAsync();
if (certificate == null)
{
throw new InvalidOperationException("No client certificate found.");
}
var thumbprint = Base64UrlTextEncoder.Encode(certificate.GetCertHash(HashAlgorithmName.SHA256));
var sha256 = JsonDocument.Parse(cnfJson).RootElement.GetString("x5t#S256");
if (string.IsNullOrWhiteSpace(sha256) ||
!thumbprint.Equals(sha256, StringComparison.OrdinalIgnoreCase))
{
_logger.LogError("certificate thumbprint does not match cnf claim.");
await ctx.ChallengeAsync(_options.JwtBearerSchemeName);
return;
}
_logger.LogDebug("certificate thumbprint matches cnf claim.");
}
}
await next(ctx);
}
}
| ConfirmationValidationMiddleware |
csharp | ardalis__SmartEnum | src/SmartEnum/Exceptions/SmartEnumNotFoundException.cs | {
"start": 1118,
"end": 1838
} | class ____ a specified error message and
/// a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">
/// The exception that is the cause of the current exception. If the <paramref name="innerException"/> parameter is not a null reference,
/// the current exception is raised in a <c>catch</c> block that handles the inner exception.
/// </param>
public SmartEnumNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| with |
csharp | protobuf-net__protobuf-net | src/protobuf-net/Meta/RuntimeTypeModel.cs | {
"start": 1014,
"end": 18015
} | private enum ____
{
None = 0,
InternStrings = TypeModelOptions.InternStrings,
IncludeDateTimeKind = TypeModelOptions.IncludeDateTimeKind,
SkipZeroLengthPackedArrays = TypeModelOptions.SkipZeroLengthPackedArrays,
AllowPackedEncodingAtRoot = TypeModelOptions.AllowPackedEncodingAtRoot,
TypeModelMask = InternStrings | IncludeDateTimeKind | SkipZeroLengthPackedArrays | AllowPackedEncodingAtRoot,
// stuff specific to RuntimeTypeModel
InferTagFromNameDefault = 1 << 10,
IsDefaultModel = 1 << 11,
Frozen = 1 << 12,
AutoAddMissingTypes = 1 << 13,
AutoCompile = 1 << 14,
UseImplicitZeroDefaults = 1 << 15,
AllowParseableTypes = 1 << 16,
AutoAddProtoContractTypesOnly = 1 << 17,
}
/// <summary>
/// Specifies optional behaviors associated with this model
/// </summary>
public override TypeModelOptions Options => (TypeModelOptions)(_options & RuntimeTypeModelOptions.TypeModelMask);
private bool GetOption(RuntimeTypeModelOptions option) => (_options & option) != 0;
private void SetOption(RuntimeTypeModelOptions option, bool value)
{
if (value) _options |= option;
else _options &= ~option;
}
internal CompilerContextScope Scope { get; } = CompilerContextScope.CreateInProcess();
/// <summary>
/// Global default that
/// enables/disables automatic tag generation based on the existing name / order
/// of the defined members. See <seealso cref="ProtoContractAttribute.InferTagFromName"/>
/// for usage and <b>important warning</b> / explanation.
/// You must set the global default before attempting to serialize/deserialize any
/// impacted type.
/// </summary>
public bool InferTagFromNameDefault
{
get { return GetOption(RuntimeTypeModelOptions.InferTagFromNameDefault); }
set { SetOption(RuntimeTypeModelOptions.InferTagFromNameDefault, value); }
}
/// <summary>
/// Global default that determines whether types are considered serializable
/// if they have [DataContract] / [XmlType]. With this enabled, <b>ONLY</b>
/// types marked as [ProtoContract] are added automatically.
/// </summary>
public bool AutoAddProtoContractTypesOnly
{
get { return GetOption(RuntimeTypeModelOptions.AutoAddProtoContractTypesOnly); }
set { SetOption(RuntimeTypeModelOptions.AutoAddProtoContractTypesOnly, value); }
}
/// <summary>
/// <para>
/// Global switch that enables or disables the implicit
/// handling of "zero defaults"; meanning: if no other default is specified,
/// it assumes bools always default to false, integers to zero, etc.
/// </para>
/// <para>
/// If this is disabled, no such assumptions are made and only *explicit*
/// default values are processed. This is enabled by default to
/// preserve similar logic to v1.
/// </para>
/// </summary>
public bool UseImplicitZeroDefaults
{
get { return GetOption(RuntimeTypeModelOptions.UseImplicitZeroDefaults); }
set
{
if (!value && GetOption(RuntimeTypeModelOptions.IsDefaultModel))
ThrowDefaultUseImplicitZeroDefaults();
SetOption(RuntimeTypeModelOptions.UseImplicitZeroDefaults, value);
}
}
/// <summary>
/// Global switch that determines whether types with a <c>.ToString()</c> and a <c>Parse(string)</c>
/// should be serialized as strings.
/// </summary>
public bool AllowParseableTypes
{
get { return GetOption(RuntimeTypeModelOptions.AllowParseableTypes); }
set { SetOption(RuntimeTypeModelOptions.AllowParseableTypes, value); }
}
/// <summary>
/// Global switch that determines whether DateTime serialization should include the <c>Kind</c> of the date/time.
/// </summary>
public bool IncludeDateTimeKind
{
get { return GetOption(RuntimeTypeModelOptions.IncludeDateTimeKind); }
set { SetOption(RuntimeTypeModelOptions.IncludeDateTimeKind, value); }
}
/// <summary>
/// Should zero-length packed arrays be serialized? (this is the v2 behavior, but skipping them is more efficient)
/// </summary>
public bool SkipZeroLengthPackedArrays
{
get { return GetOption(RuntimeTypeModelOptions.SkipZeroLengthPackedArrays); }
set { SetOption(RuntimeTypeModelOptions.SkipZeroLengthPackedArrays, value); }
}
/// <summary>
/// Should root-values allow "packed" encoding? (v2 does not support this)
/// </summary>
public bool AllowPackedEncodingAtRoot
{
get { return GetOption(RuntimeTypeModelOptions.AllowPackedEncodingAtRoot); }
set { SetOption(RuntimeTypeModelOptions.AllowPackedEncodingAtRoot, value); }
}
/// <summary>
/// Global switch that determines whether a single instance of the same string should be used during deserialization.
/// </summary>
/// <remarks>Note this does not use the global .NET string interner</remarks>
public bool InternStrings
{
get { return GetOption(RuntimeTypeModelOptions.InternStrings); }
set { SetOption(RuntimeTypeModelOptions.InternStrings, value); }
}
/// <summary>
/// The default model, used to support ProtoBuf.Serializer
/// </summary>
public static RuntimeTypeModel Default
=> (DefaultModel as RuntimeTypeModel) ?? CreateDefaultModelInstance();
/// <summary>
/// Returns a sequence of the Type instances that can be
/// processed by this model.
/// </summary>
public IEnumerable GetTypes() => types;
/// <summary>
/// Gets or sets the default <see cref="CompatibilityLevel"/> for this model.
/// </summary>
public CompatibilityLevel DefaultCompatibilityLevel
{
get => _defaultCompatibilityLevel;
set
{
if (value != _defaultCompatibilityLevel)
{
CompatibilityLevelAttribute.AssertValid(value);
ThrowIfFrozen();
if (GetOption(RuntimeTypeModelOptions.IsDefaultModel)) ThrowHelper.ThrowInvalidOperationException("The default compatibility level of the default model cannot be changed");
if (types.Any()) ThrowHelper.ThrowInvalidOperationException("The default compatibility level of cannot be changed once types have been added");
_defaultCompatibilityLevel = value;
}
}
}
private CompatibilityLevel _defaultCompatibilityLevel = CompatibilityLevel.Level200;
/// <inheritdoc/>
public override string GetSchema(SchemaGenerationOptions options)
{
if (options is null) throw new ArgumentNullException(nameof(options));
var syntax = Serializer.GlobalOptions.Normalize(options.Syntax);
var requiredTypes = new List<MetaType>();
List<Type> inbuiltTypes = default;
HashSet<Type> forceGenerationTypes = null;
bool IsOutputForcedFor(Type type)
=> forceGenerationTypes?.Contains(type) ?? false;
string package = options.Package, origin = options.Origin;
var imports = new HashSet<string>(StringComparer.Ordinal);
MetaType AddType(Type type, bool forceOutput, bool inferPackageAndOrigin)
{
if (forceOutput && type is not null) (forceGenerationTypes ??= []).Add(type);
// generate just relative to the supplied type
int index = FindOrAddAuto(type, false, false, false, DefaultCompatibilityLevel);
if (index < 0) throw new ArgumentException($"The type specified is not a contract-type: '{type.NormalizeName()}'", nameof(type));
// get the required types
var mt = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false);
if (inferPackageAndOrigin)
{
if (origin is null && !string.IsNullOrWhiteSpace(mt.Origin))
{
origin = mt.Origin;
}
string tmp;
if (package is null && !string.IsNullOrWhiteSpace(tmp = mt.GuessPackage()))
{
package = tmp;
}
}
AddMetaType(mt);
return mt;
}
void AddMetaType(MetaType toAdd)
{
if (!string.IsNullOrWhiteSpace(toAdd.Origin) && toAdd.Origin != origin)
{
imports.Add(toAdd.Origin);
return; // external type; not our problem!
}
if (!requiredTypes.Contains(toAdd))
{ // ^^^ note that the type might have been added as a descendent
requiredTypes.Add(toAdd);
CascadeDependents(requiredTypes, toAdd, imports, origin);
}
}
if (!options.HasTypes && !options.HasServices)
{
// generate for the entire model
foreach (MetaType meta in types)
{
MetaType tmp = meta.GetSurrogateOrBaseOrSelf(false);
AddMetaType(tmp);
}
}
else
{
if (options.HasTypes)
{
foreach (var type in options.Types)
{
Type effectiveType = Nullable.GetUnderlyingType(type) ?? type;
var isInbuiltType = (ValueMember.TryGetCoreSerializer(this, DataFormat.Default, DefaultCompatibilityLevel, effectiveType, out var _, false, false, false, false) is object);
if (isInbuiltType)
{
(inbuiltTypes ??= []).Add(effectiveType);
}
else
{
bool isSingleInput = options.Types.Count == 1;
var mt = AddType(effectiveType, isSingleInput, isSingleInput);
}
}
}
if (options.HasServices)
{
foreach (var service in options.Services)
{
foreach (var method in service.Methods)
{
AddType(method.InputType, true, false);
AddType(method.OutputType, true, false);
}
}
}
}
// use the provided type's namespace for the "package"
StringBuilder headerBuilder = new StringBuilder();
if (package is null)
{
IEnumerable<MetaType> typesForNamespace = (options.HasTypes || options.HasServices) ? requiredTypes : types.Cast<MetaType>();
foreach (MetaType meta in typesForNamespace)
{
if (TryGetRepeatedProvider(meta.Type) is not null) continue;
string tmp = meta.Type.Namespace;
if (!string.IsNullOrEmpty(tmp))
{
if (tmp.StartsWith("System.")) continue;
if (package is null)
{ // haven't seen any suggestions yet
package = tmp;
}
else if (package == tmp)
{ // that's fine; a repeat of the one we already saw
}
else
{ // something else; have conflicting suggestions; abort
package = null;
break;
}
}
}
}
switch (syntax)
{
case ProtoSyntax.Proto2:
headerBuilder.AppendLine(@"syntax = ""proto2"";");
break;
case ProtoSyntax.Proto3:
headerBuilder.AppendLine(@"syntax = ""proto3"";");
break;
default:
#pragma warning disable CA2208 // param name - for clarity
throw new ArgumentOutOfRangeException(nameof(syntax));
#pragma warning restore CA2208 // param name - for clarity
}
if (!string.IsNullOrEmpty(package))
{
headerBuilder.Append("package ").Append(package).Append(';').AppendLine();
}
// check for validity
foreach (var mt in requiredTypes)
{
_ = mt.Serializer; // force errors to happen if there's problems
}
StringBuilder bodyBuilder = new StringBuilder();
// sort them by schema-name
var callstack = new HashSet<Type>(); // for recursion detection
MetaType[] metaTypesArr = new MetaType[requiredTypes.Count];
requiredTypes.CopyTo(metaTypesArr, 0);
Array.Sort(metaTypesArr, new MetaType.Comparer(callstack));
// write the messages
if (inbuiltTypes is not null)
{
foreach (var type in inbuiltTypes)
{
bodyBuilder.AppendLine().Append("message ").Append(type.Name).Append(" {");
MetaType.NewLine(bodyBuilder, 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(GetSchemaTypeName(callstack, type, DataFormat.Default, DefaultCompatibilityLevel, false, false, imports))
.Append(" value = 1;").AppendLine().Append('}');
}
}
for (int i = 0; i < metaTypesArr.Length; i++)
{
MetaType tmp = metaTypesArr[i];
if (tmp.SerializerType is not null)
{
continue; // not our concern
}
if (!IsOutputForcedFor(tmp.Type) && TryGetRepeatedProvider(tmp.Type) is not null) continue;
tmp.WriteSchema(callstack, bodyBuilder, 0, imports, syntax, package, options.Flags);
}
// write the services
if (options.HasServices)
{
foreach (var service in options.Services)
{
MetaType.NewLine(bodyBuilder, 0).Append("service ").Append(service.Name).Append(" {");
foreach (var method in service.Methods)
{
var inputName = GetSchemaTypeName(callstack, method.InputType, DataFormat.Default, DefaultCompatibilityLevel, false, false, imports);
var replyName = GetSchemaTypeName(callstack, method.OutputType, DataFormat.Default, DefaultCompatibilityLevel, false, false, imports);
MetaType.NewLine(bodyBuilder, 1).Append("rpc ").Append(method.Name).Append(" (")
.Append(method.ClientStreaming ? "stream " : "")
.Append(inputName).Append(") returns (")
.Append(method.ServerStreaming ? "stream " : "")
.Append(replyName).Append(");");
}
MetaType.NewLine(bodyBuilder, 0).Append('}');
}
}
foreach (var import in imports.OrderBy(_ => _))
{
if (!string.IsNullOrWhiteSpace(import))
{
headerBuilder.Append("import \"").Append(import).Append("\";");
switch (import)
{
case CommonImports.Bcl:
headerBuilder.Append(" // schema for protobuf-net's handling of core .NET types");
break;
case CommonImports.Protogen:
headerBuilder.Append(" // custom protobuf-net options");
break;
}
headerBuilder.AppendLine();
}
}
return headerBuilder.Append(bodyBuilder).AppendLine().ToString();
}
| RuntimeTypeModelOptions |
csharp | dotnet__efcore | benchmark/EFCore.Benchmarks/Models/AdventureWorks/Person.cs | {
"start": 262,
"end": 1795
} | public class ____
{
public Person()
{
BusinessEntityContact = new HashSet<BusinessEntityContact>();
Customer = new HashSet<Customer>();
EmailAddress = new HashSet<EmailAddress>();
PersonCreditCard = new HashSet<PersonCreditCard>();
PersonPhone = new HashSet<PersonPhone>();
}
public int BusinessEntityID { get; set; }
public int EmailPromotion { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public DateTime ModifiedDate { get; set; }
public bool NameStyle { get; set; }
public string PersonType { get; set; }
#pragma warning disable IDE1006 // Naming Styles
public Guid rowguid { get; set; }
#pragma warning restore IDE1006 // Naming Styles
public string Suffix { get; set; }
public string Title { get; set; }
public string AdditionalContactInfo { get; set; }
public string Demographics { get; set; }
public virtual ICollection<BusinessEntityContact> BusinessEntityContact { get; set; }
public virtual ICollection<Customer> Customer { get; set; }
public virtual ICollection<EmailAddress> EmailAddress { get; set; }
public virtual Employee Employee { get; set; }
public virtual Password Password { get; set; }
public virtual ICollection<PersonCreditCard> PersonCreditCard { get; set; }
public virtual ICollection<PersonPhone> PersonPhone { get; set; }
public virtual BusinessEntity BusinessEntity { get; set; }
}
| Person |
csharp | dotnet__BenchmarkDotNet | src/BenchmarkDotNet/Helpers/CodeAnnotations.cs | {
"start": 65646,
"end": 65885
} | internal sealed class ____ : Attribute { }
/// <summary>
/// Indicates that the marked parameter contains an ASP.NET Minimal API endpoint handler.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
| AspMinimalApiGroupAttribute |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1836415,
"end": 1836770
} | public partial interface ____ : IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes_Changes_3, IDeprecatedChange
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes_Changes_DeprecatedChange_3 |
csharp | ShareX__ShareX | ShareX.MediaLib/Forms/VideoThumbnailerForm.cs | {
"start": 1233,
"end": 3633
} | public partial class ____ : Form
{
public event Action<List<VideoThumbnailInfo>> ThumbnailsTaken;
public string FFmpegPath { get; set; }
public VideoThumbnailOptions Options { get; set; }
public VideoThumbnailerForm(string ffmpegPath, VideoThumbnailOptions options)
{
FFmpegPath = ffmpegPath;
Options = options;
InitializeComponent();
ShareXResources.ApplyTheme(this, true);
txtMediaPath.Text = Options.LastVideoPath ?? "";
pgOptions.SelectedObject = Options;
}
private async void btnStart_Click(object sender, EventArgs e)
{
string mediaPath = txtMediaPath.Text;
if (File.Exists(mediaPath) && File.Exists(FFmpegPath))
{
Options.LastVideoPath = mediaPath;
pbProgress.Value = 0;
pbProgress.Maximum = Options.ThumbnailCount;
pbProgress.Visible = true;
btnStart.Visible = false;
List<VideoThumbnailInfo> thumbnails = null;
await Task.Run(() =>
{
try
{
VideoThumbnailer thumbnailer = new VideoThumbnailer(FFmpegPath, Options);
thumbnailer.ProgressChanged += Thumbnailer_ProgressChanged;
thumbnails = thumbnailer.TakeThumbnails(mediaPath);
}
catch (Exception ex)
{
ex.ShowError();
}
});
if (thumbnails != null)
{
OnThumbnailsTaken(thumbnails);
}
btnStart.Visible = true;
pbProgress.Visible = false;
}
}
private void Thumbnailer_ProgressChanged(int current, int length)
{
this.InvokeSafe(() => pbProgress.Value = current);
}
protected void OnThumbnailsTaken(List<VideoThumbnailInfo> thumbnails)
{
ThumbnailsTaken?.Invoke(thumbnails);
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FileHelpers.BrowseFile(Resources.VideoThumbnailerForm_btnBrowse_Click_Browse_for_media_file, txtMediaPath);
}
}
} | VideoThumbnailerForm |
csharp | unoplatform__uno | src/Uno.UWP/System/MemoryManager.Android.cs | {
"start": 113,
"end": 1402
} | public partial class ____
{
private static ulong _appMemoryUsage;
private static ulong _appMemoryUsageLimit;
private static Debug.MemoryInfo? _mi;
private static ActivityManager.MemoryInfo? _memoryInfo;
private static global::System.Diagnostics.Stopwatch _updateWatch = global::System.Diagnostics.Stopwatch.StartNew();
private static TimeSpan _lastUpdate = TimeSpan.FromSeconds(-_updateInterval.TotalSeconds);
private readonly static TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
public static ulong AppMemoryUsage
{
get
{
Update();
return _appMemoryUsage;
}
}
public static ulong AppMemoryUsageLimit
{
get
{
Update();
return _appMemoryUsageLimit;
}
}
private static void Update()
{
var now = _updateWatch.Elapsed;
if (_lastUpdate + _updateInterval < now)
{
_lastUpdate = now;
_mi ??= new Debug.MemoryInfo();
Debug.GetMemoryInfo(_mi);
var totalMemory = _mi.TotalPss * 1024;
_appMemoryUsage = (ulong)totalMemory;
_memoryInfo ??= new ActivityManager.MemoryInfo();
ActivityManager.FromContext(ContextHelper.Current)?.GetMemoryInfo(_memoryInfo);
_appMemoryUsageLimit = _appMemoryUsage + (ulong)_memoryInfo.AvailMem - (ulong)_memoryInfo.Threshold;
}
}
}
}
| MemoryManager |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/Kubernetes/Kubernetes.Generated.cs | {
"start": 244578,
"end": 244962
} | public partial class ____ : KubernetesOptionsBase
{
}
#endregion
#region KubernetesPatchSettings
/// <inheritdoc cref="KubernetesTasks.KubernetesPatch(Nuke.Common.Tools.Kubernetes.KubernetesPatchSettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Command(Type = typeof(KubernetesTasks), Command = nameof(KubernetesTasks.KubernetesPatch), Arguments = "patch")]
| KubernetesCompletionSettings |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/ElectionsService/Randomized/elections_service_3_nodes_full_gossip_some_http_loss_some_dup.cs | {
"start": 323,
"end": 1136
} | public class ____ {
private RandomizedElectionsTestCase _randomCase;
[SetUp]
public void SetUp() {
_randomCase = new RandomizedElectionsTestCase(ElectionParams.MaxIterationCount,
instancesCnt: 3,
httpLossProbability: 0.3,
httpDupProbability: 0.3,
httpMaxDelay: 20,
timerMinDelay: 100,
timerMaxDelay: 200);
_randomCase.Init();
}
[Test, Category("LongRunning"), Category("Network")]
public void should_always_arrive_at_coherent_results([Range(0, ElectionParams.TestRunCount - 1)]
int run) {
var success = _randomCase.Run();
if (!success)
_randomCase.Logger.LogMessages();
Console.WriteLine("There were a total of {0} messages in this run.",
_randomCase.Logger.ProcessedItems.Count());
Assert.True(success);
}
}
| elections_service_3_nodes_full_gossip_some_http_loss_some_dup |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/QualifierTests.cs | {
"start": 2323,
"end": 2389
} | private class ____
{
public static void Test()
{
}
}
| i |
csharp | PrismLibrary__Prism | tests/Avalonia/Prism.Avalonia.Tests/Mocks/MockSortableViews.cs | {
"start": 101,
"end": 176
} | internal class ____
{
}
[ViewSortHint("02")]
| MockSortableView1 |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Plugins/PluginPageInfo.cs | {
"start": 131,
"end": 1102
} | public class ____
{
/// <summary>
/// Gets or sets the name of the plugin.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the display name of the plugin.
/// </summary>
public string? DisplayName { get; set; }
/// <summary>
/// Gets or sets the resource path.
/// </summary>
public string EmbeddedResourcePath { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether this plugin should appear in the main menu.
/// </summary>
public bool EnableInMainMenu { get; set; }
/// <summary>
/// Gets or sets the menu section.
/// </summary>
public string? MenuSection { get; set; }
/// <summary>
/// Gets or sets the menu icon.
/// </summary>
public string? MenuIcon { get; set; }
}
}
| PluginPageInfo |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.RenderTests/Media/VisualBrushTests.cs | {
"start": 218,
"end": 25347
} | public class ____ : TestBase
{
public VisualBrushTests()
: base(@"Media\VisualBrush")
{
}
private string BitmapPath
{
get
{
return System.IO.Path.Combine(OutputPath, "github_icon.png");
}
}
private Control Visual
{
get
{
return new Panel
{
Children =
{
new Image
{
Source = new Bitmap(BitmapPath),
},
new Border
{
BorderBrush = Brushes.Blue,
BorderThickness = new Thickness(2),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Child = new Panel
{
Height = 26,
Width = 150,
Background = Brushes.Green
}
}
}
};
}
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_Alignment_TopLeft()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Top,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_Alignment_Center()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
AlignmentX = AlignmentX.Center,
AlignmentY = AlignmentY.Center,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_Alignment_BottomRight()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
AlignmentX = AlignmentX.Right,
AlignmentY = AlignmentY.Bottom,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_Fill_NoTile()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 920,
Height = 920,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.Fill,
TileMode = TileMode.None,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_Uniform_NoTile()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 300,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.Uniform,
TileMode = TileMode.None,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_UniformToFill_NoTile()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 300,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.UniformToFill,
TileMode = TileMode.None,
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_BottomRightQuarterSource()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
SourceRect = new RelativeRect(250, 250, 250, 250, RelativeUnit.Absolute),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_BottomRightQuarterDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
DestinationRect = new RelativeRect(92, 92, 92, 92, RelativeUnit.Absolute),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_NoTile_BottomRightQuarterSource_BottomRightQuarterDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.None,
SourceRect = new RelativeRect(0.5, 0.5, 0.5, 0.5, RelativeUnit.Relative),
DestinationRect = new RelativeRect(0.5, 0.5, 0.5, 0.5, RelativeUnit.Relative),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_Tile_BottomRightQuarterSource_CenterQuarterDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.Tile,
SourceRect = new RelativeRect(0.5, 0.5, 0.5, 0.5, RelativeUnit.Relative),
DestinationRect = new RelativeRect(0.25, 0.25, 0.5, 0.5, RelativeUnit.Relative),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_FlipX_TopLeftDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.FlipX,
DestinationRect = new RelativeRect(0, 0, 0.5, 0.5, RelativeUnit.Relative),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_FlipY_TopLeftDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.FlipY,
DestinationRect = new RelativeRect(0, 0, 0.5, 0.5, RelativeUnit.Relative),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_NoStretch_FlipXY_TopLeftDest()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Rectangle
{
Fill = new VisualBrush
{
Stretch = Stretch.None,
TileMode = TileMode.FlipXY,
DestinationRect = new RelativeRect(0, 0, 0.5, 0.5, RelativeUnit.Relative),
Visual = Visual,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_InTree_Visual()
{
Border source;
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Grid
{
RowDefinitions = new RowDefinitions("Auto,*"),
Children =
{
(source = new Border
{
Background = Brushes.Yellow,
HorizontalAlignment = HorizontalAlignment.Left,
Child = new Panel
{
Height = 10,
Width = 50
}
}),
new Border
{
Background = new VisualBrush
{
Stretch = Stretch.Uniform,
Visual = source,
},
[Grid.RowProperty] = 1,
}
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_Grip_96_Dpi()
{
var target = new Border
{
Width = 100,
Height = 10,
Background = new VisualBrush
{
SourceRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
DestinationRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Stretch = Stretch.UniformToFill,
Visual = new Canvas
{
Width = 4,
Height = 5,
Background = Brushes.WhiteSmoke,
Children =
{
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.TopProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
[Canvas.TopProperty] = 4,
}
}
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_Grip_144_Dpi()
{
var target = new Border
{
Width = 100,
Height = 7.5,
Background = new VisualBrush
{
SourceRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
DestinationRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Stretch = Stretch.UniformToFill,
Visual = new Canvas
{
Width = 4,
Height = 5,
Background = Brushes.WhiteSmoke,
Children =
{
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.TopProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
[Canvas.TopProperty] = 4,
}
}
}
}
};
await RenderToFile(target, dpi: 144);
CompareImages();
}
[Fact]
public async Task VisualBrush_Grip_192_Dpi()
{
var target = new Border
{
Width = 100,
Height = 10,
Background = new VisualBrush
{
SourceRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
DestinationRect = new RelativeRect(0, 0, 4, 5, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Stretch = Stretch.UniformToFill,
Visual = new Canvas
{
Width = 4,
Height = 5,
Background = Brushes.WhiteSmoke,
Children =
{
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.TopProperty] = 2,
},
new Rectangle
{
Width = 1,
Height = 1,
Fill = Brushes.Red,
[Canvas.LeftProperty] = 2,
[Canvas.TopProperty] = 4,
}
}
}
}
};
await RenderToFile(target, dpi: 192);
CompareImages();
}
[Fact]
public async Task VisualBrush_Checkerboard_96_Dpi()
{
var target = new Border
{
Width = 200,
Height = 200,
Background = new VisualBrush
{
DestinationRect = new RelativeRect(0, 0, 16, 16, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Visual = new Canvas
{
Width = 16,
Height= 16,
Background = Brushes.Red,
Children =
{
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
},
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
[Canvas.LeftProperty] = 8,
[Canvas.TopProperty] = 8,
},
}
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task VisualBrush_Checkerboard_144_Dpi()
{
var target = new Border
{
Width = 200,
Height = 200,
Background = new VisualBrush
{
DestinationRect = new RelativeRect(0, 0, 16, 16, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Visual = new Canvas
{
Width = 16,
Height = 16,
Background = Brushes.Red,
Children =
{
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
},
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
[Canvas.LeftProperty] = 8,
[Canvas.TopProperty] = 8,
},
}
}
}
};
await RenderToFile(target, dpi: 144);
CompareImages();
}
[Fact]
public async Task VisualBrush_Checkerboard_192_Dpi()
{
var target = new Border
{
Width = 200,
Height = 200,
Background = new VisualBrush
{
DestinationRect = new RelativeRect(0, 0, 16, 16, RelativeUnit.Absolute),
TileMode = TileMode.Tile,
Visual = new Canvas
{
Width = 16,
Height = 16,
Background = Brushes.Red,
Children =
{
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
},
new Rectangle
{
Width = 8,
Height = 8,
Fill = Brushes.Green,
[Canvas.LeftProperty] = 8,
[Canvas.TopProperty] = 8,
},
}
}
}
};
await RenderToFile(target, dpi: 192);
CompareImages();
}
[Theory,
InlineData(false),
InlineData(true)
]
public async Task VisualBrush_Is_Properly_Mapped(bool relative)
{
var brush = new VisualBrush()
{
Stretch = Stretch.Fill,
TileMode = TileMode.Tile,
DestinationRect = relative
? new RelativeRect(0, 0, 1, 1, RelativeUnit.Relative)
: new RelativeRect(0, 0, 256, 256, RelativeUnit.Absolute),
Visual = Visual
};
var testName =
$"{nameof(VisualBrush_Is_Properly_Mapped)}_{brush.DestinationRect.Unit}";
await RenderToFile(new RelativePointTestPrimitivesHelper(brush), testName);
CompareImages(testName);
}
[Fact]
public async Task VisualBrush_Should_Be_Usable_As_Opacity_Mask()
{
var target = new Border()
{
Padding = new Thickness(8),
Width = 920,
Height = 920,
Background = Brushes.Magenta,
OpacityMask = new VisualBrush
{
Stretch = Stretch.Fill,
TileMode = TileMode.None,
Visual = new Border()
{
Width = 200,
Height = 200,
Padding = new Thickness(20),
Child = new Grid()
{
ColumnDefinitions = ColumnDefinitions.Parse("*,*,*"),
RowDefinitions = RowDefinitions.Parse("*,*,*"),
Children =
{
new Border()
{
Background = Brushes.Aqua,
},
new Border()
{
[Grid.ColumnProperty] = 1,
[Grid.RowProperty] = 2,
Background = Brushes.Aqua,
},
new Border()
{
[Grid.ColumnProperty] = 3,
Background = Brushes.Aqua,
},
}
},
}
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| VisualBrushTests |
csharp | AutoMapper__AutoMapper | src/UnitTests/AttributeBasedMaps.cs | {
"start": 25249,
"end": 26940
} | public class ____ : ITypeConverter<int, List<ChildDto>>
{
private readonly IList<Child> _childModels;
public ParentIdToChildDtoListConverter(IList<Child> childModels)
{
_childModels = childModels;
}
public List<ChildDto> Convert(int source, List<ChildDto> destination, ResolutionContext resolutionContext)
{
var childModels = _childModels.Where(x => x.Parent.Id == source).ToList();
return (List<ChildDto>)resolutionContext.Mapper.Map(childModels, destination, typeof(List<Child>), typeof(List<ChildDto>));
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
_parent = new Parent
{
Id = 2
};
var childModels = new List<Child>
{
new Child
{
Id = 1,
Parent = _parent
}
};
cfg.AddMaps(typeof(When_specifying_to_preserve_references_via_attribute));
cfg.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels));
});
private static Parent _parent;
[Fact]
public void Should_preserve_parent_relationship()
{
var dto = Mapper.Map<Parent, ParentDto>(_parent);
dto.Children[0].Parent.ShouldBe(dto);
}
}
| ParentIdToChildDtoListConverter |
csharp | neuecc__MessagePack-CSharp | sandbox/Sandbox/Program.cs | {
"start": 421,
"end": 616
} | public class ____
//{
// [Key(0)]
// public Foo<int> MemberUserGeneric { get; set; }
// [Key(1)]
// public System.Collections.Generic.List<int> MemberKnownGeneric { get; set; }
//}
| Bar |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/Issue5461.cs | {
"start": 203,
"end": 625
} | public class ____ : TestContentPage
{
const string Success = "If you can see this, the test has passed";
protected override void Init()
{
ScrollView scrollView = new ScrollbarFadingEnabledFalseScrollView()
{
Content = new StackLayout()
{
Children =
{
new Label()
{
Text = Success
}
},
HeightRequest = 2000
}
};
Content = scrollView;
}
| Issue5461 |
csharp | dotnet__orleans | test/Orleans.Journaling.Tests/StateMachineTestBase.cs | {
"start": 425,
"end": 2273
} | public abstract class ____
{
protected readonly ServiceProvider ServiceProvider;
protected readonly SerializerSessionPool SessionPool;
protected readonly ICodecProvider CodecProvider;
protected readonly ILoggerFactory LoggerFactory;
protected readonly StateMachineManagerOptions ManagerOptions = new();
protected StateMachineTestBase()
{
var services = new ServiceCollection();
services.AddSerializer();
services.AddLogging(builder => builder.AddConsole());
ServiceProvider = services.BuildServiceProvider();
SessionPool = ServiceProvider.GetRequiredService<SerializerSessionPool>();
CodecProvider = ServiceProvider.GetRequiredService<ICodecProvider>();
LoggerFactory = ServiceProvider.GetRequiredService<ILoggerFactory>();
}
/// <summary>
/// Creates an in-memory storage for testing
/// </summary>
protected virtual IStateMachineStorage CreateStorage()
{
return new VolatileStateMachineStorage();
}
/// <summary>
/// Creates a state machine manager with in-memory storage
/// </summary>
internal (IStateMachineManager Manager, IStateMachineStorage Storage, ILifecycleSubject Lifecycle)
CreateTestSystem(IStateMachineStorage? storage = null, TimeProvider? provider = null)
{
storage ??= CreateStorage();
provider ??= TimeProvider.System;
var logger = LoggerFactory.CreateLogger<StateMachineManager>();
var manager = new StateMachineManager(storage, logger, Options.Create(ManagerOptions), SessionPool, provider);
var lifecycle = new GrainLifecycle(LoggerFactory.CreateLogger<GrainLifecycle>());
(manager as ILifecycleParticipant<IGrainLifecycle>)?.Participate(lifecycle);
return (manager, storage, lifecycle);
}
| StateMachineTestBase |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Metrics/Unit/ParserTests.cs | {
"start": 4674,
"end": 4976
} | partial class ____
{
[Counter<int>(""d1"")]
static partial TestCounter CreateTestCounter(Meter meter);
}");
Assert.Empty(d);
}
[Fact]
public async Task NotPartialMethod()
{
var d = await RunGenerator(@"
| C |
csharp | louthy__language-ext | LanguageExt.Tests/ErrorTests.cs | {
"start": 2230,
"end": 4044
} | public record ____([property: DataMember] bool MyData) :
Expected("Expected something bespoke", 100, None);
[Fact]
public void BespokeExpectedSerialisationTest()
{
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
var ea = new BespokeError(true);
var json = JsonConvert.SerializeObject(ea, settings);
var eb = JsonConvert.DeserializeObject<Error>(json, settings);
Assert.True(eb.IsExpected);
Assert.False(eb.IsExceptional);
Assert.True(ea == eb);
Assert.True(ea.Is(eb));
Assert.True(eb.Is(ea));
}
[Fact]
public void ManyExpectedSerialisationTest()
{
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
var ea = Error.New(123, "Err 1");
var eb = Error.New(345, "Err 2");
var ec = Error.New(678, "Err 3");
var json = JsonConvert.SerializeObject(ea + eb + ec, settings);
var es = JsonConvert.DeserializeObject<Error>(json, settings);
Assert.False(es.IsEmpty);
Assert.True(es.Count == 3);
Assert.True(es.IsExpected);
Assert.False(eb.IsExceptional);
Assert.True(es == ea + eb + ec);
Assert.True(es.Is(ea + eb + ec));
Assert.True((ea + eb + ec).Is(es));
}
[Fact]
public void MonoidLawsTest()
{
var ea = Error.New(123, "Err 1");
var eb = Error.New(345, "Err 2");
var ec = Error.New(678, "Err 3");
Assert.True((ea + eb) + ec == ea + (eb + ec), "Associativity");
Assert.True(Error.Empty + ea == ea, "Left Identity");
Assert.True(ea + Error.Empty == ea, "Right Identity");
}
}
| BespokeError |
csharp | ardalis__CleanArchitecture | sample/tests/NimblePros.SampleToDo.UnitTests/Core/Specifications/IncompleteItemSpecificationsConstructor.cs | {
"start": 183,
"end": 729
} | public class ____
{
[Fact]
public void FilterCollectionToOnlyReturnItemsWithIsDoneFalse()
{
var item1 = new ToDoItem();
var item2 = new ToDoItem();
var item3 = new ToDoItem();
item3.MarkComplete();
var items = new List<ToDoItem>() { item1, item2, item3 };
var spec = new IncompleteItemsSpec();
var filteredList = spec.Evaluate(items);
Assert.Contains(item1, filteredList);
Assert.Contains(item2, filteredList);
Assert.DoesNotContain(item3, filteredList);
}
}
| IncompleteItemsSpecificationConstructor |
csharp | ServiceStack__ServiceStack.OrmLite | tests/ServiceStack.OrmLite.Tests/Expression/RestrictionTests.cs | {
"start": 249,
"end": 2389
} | public class ____
{
public Person() {}
public Person(int id, string firstName, string lastName, int age)
{
Id = id;
FirstName = firstName;
LastName = lastName;
Age = age;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
}
public Person[] People = {
new Person(1, "Jimi", "Hendrix", 27),
new Person(2, "Janis", "Joplin", 27),
new Person(3, "Jim", "Morrisson", 27),
new Person(4, "Kurt", "Cobain", 27),
new Person(5, "Elvis", "Presley", 42),
new Person(6, "Michael", "Jackson", 50),
};
[Test]
public void Can_Chain_Expressions_Using_Or_and_And()
{
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<Person>();
db.InsertAll(People);
var q = db.From<Person>();
q.Where(x => x.FirstName.StartsWith("Jim")).Or(x => x.LastName.StartsWith("Cob"));
var results = db.Select(q);
Assert.AreEqual(3, results.Count);
q.Where(); //clear where expression
q.Where(x => x.FirstName.StartsWith("Jim")).And(x => x.LastName.StartsWith("Hen"));
results = db.Select(q);
Assert.AreEqual(1, results.Count);
}
}
[Test]
public void Can_get_rowcount_from_expression_visitor()
{
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<Person>();
db.InsertAll(People);
var q = db.From<Person>();
q.Where(x => x.FirstName.StartsWith("Jim")).Or(x => x.LastName.StartsWith("Cob"));
var count = db.Count(q);
var results = db.Select(q);
Assert.AreEqual(count, results.Count);
}
}
}
} | Person |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.TestHelpers/XunitExtensions/CategoryAttribute.cs | {
"start": 928,
"end": 1168
} | public class ____ : Attribute, ITraitAttribute
{
public CategoryAttribute(params string[] categories)
{
Categories = categories;
}
public string[] Categories { get; }
}
| CategoryAttribute |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Reactive/AnonymousObserver.cs | {
"start": 364,
"end": 1805
} | public class ____<T> : IObserver<T>
{
private readonly Action<T> _onNext;
private readonly Action<Exception> _onError;
private readonly Action _onCompleted;
public AnonymousObserver(TaskCompletionSource<T> tcs)
{
if (tcs is null)
{
throw new ArgumentNullException(nameof(tcs));
}
_onNext = tcs.SetResult;
_onError = tcs.SetException;
_onCompleted = NoOpCompleted;
}
public AnonymousObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
_onNext = onNext ?? throw new ArgumentNullException(nameof(onNext));
_onError = onError ?? throw new ArgumentNullException(nameof(onError));
_onCompleted = onCompleted ?? throw new ArgumentNullException(nameof(onCompleted));
}
public AnonymousObserver(Action<T> onNext)
: this(onNext, ThrowsOnError, NoOpCompleted)
{
}
public AnonymousObserver(Action<T> onNext, Action<Exception> onError)
: this(onNext, onError, NoOpCompleted)
{
}
public AnonymousObserver(Action<T> onNext, Action onCompleted)
: this(onNext, ThrowsOnError, onCompleted)
{
}
public void OnCompleted()
{
_onCompleted.Invoke();
}
public void OnError(Exception error)
{
_onError.Invoke(error);
}
public void OnNext(T value)
{
_onNext.Invoke(value);
}
}
| AnonymousObserver |
csharp | dotnet__aspire | tests/Aspire.Hosting.Tests/HealthCheckTests.cs | {
"start": 445,
"end": 5862
} | public class ____(ITestOutputHelper testOutputHelper)
{
[Fact]
[RequiresDocker]
public void WithHttpHealthCheckThrowsIfReferencingEndpointByNameThatIsNotHttpScheme()
{
using var builder = TestDistributedApplicationBuilder.Create();
var container = builder.AddContainer("resource", "dummycontainer")
.WithEndpoint(targetPort: 9999, scheme: "tcp", name: "nonhttp");
var ex = Assert.Throws<DistributedApplicationException>(() =>
{
container.WithHttpHealthCheck(endpointName: "nonhttp");
});
Assert.Equal(
"Could not create HTTP health check for resource 'resource' as the endpoint with name 'nonhttp' and scheme 'tcp' is not an HTTP endpoint.",
ex.Message
);
}
[Fact]
[RequiresDocker]
public void WithHttpHealthCheckThrowsIfReferencingEndpointThatIsNotHttpScheme()
{
using var builder = TestDistributedApplicationBuilder.Create();
var container = builder.AddContainer("resource", "dummycontainer")
.WithEndpoint(targetPort: 9999, scheme: "tcp", name: "nonhttp");
var ex = Assert.Throws<DistributedApplicationException>(() =>
{
container.WithHttpHealthCheck(() => container.GetEndpoint("nonhttp"));
});
Assert.Equal(
"Could not create HTTP health check for resource 'resource' as the endpoint with name 'nonhttp' and scheme 'tcp' is not an HTTP endpoint.",
ex.Message
);
}
[Fact]
[RequiresDocker]
public void WithHttpsHealthCheckThrowsIfReferencingEndpointThatIsNotHttpsScheme()
{
using var builder = TestDistributedApplicationBuilder.Create();
var ex = Assert.Throws<DistributedApplicationException>(() =>
{
#pragma warning disable CS0618 // Type or member is obsolete
builder.AddContainer("resource", "dummycontainer")
.WithEndpoint(targetPort: 9999, scheme: "tcp", name: "nonhttp")
.WithHttpsHealthCheck(endpointName: "nonhttp");
#pragma warning restore CS0618 // Type or member is obsolete
});
Assert.Equal(
"Could not create HTTP health check for resource 'resource' as the endpoint with name 'nonhttp' and scheme 'tcp' is not an HTTP endpoint.",
ex.Message
);
}
[Fact]
[RequiresDocker]
public async Task VerifyWithHttpHealthCheckBlocksDependentResources()
{
using var builder = TestDistributedApplicationBuilder.Create().WithTestAndResourceLogging(testOutputHelper);
var healthCheckTcs = new TaskCompletionSource<HealthCheckResult>();
builder.Services.AddHealthChecks().AddAsyncCheck("blocking_check", () =>
{
return healthCheckTcs.Task;
});
var resource = builder.AddContainer("resource", "mcr.microsoft.com/cbl-mariner/base/nginx", "1.22")
.WithHttpEndpoint(targetPort: 80)
.WithHttpHealthCheck(statusCode: 404)
.WithHealthCheck("blocking_check");
var dependentResource = builder.AddContainer("dependentresource", "mcr.microsoft.com/cbl-mariner/base/nginx", "1.22")
.WaitFor(resource);
using var app = builder.Build();
var pendingStart = app.StartAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
await rns.WaitForResourceAsync(resource.Resource.Name, KnownResourceStates.Running).DefaultTimeout(TestConstants.DefaultOrchestratorTestLongTimeout);
await rns.WaitForResourceAsync(dependentResource.Resource.Name, KnownResourceStates.Waiting).DefaultTimeout(TestConstants.DefaultOrchestratorTestLongTimeout);
healthCheckTcs.SetResult(HealthCheckResult.Healthy());
await rns.WaitForResourceHealthyAsync(resource.Resource.Name).DefaultTimeout(TestConstants.DefaultOrchestratorTestLongTimeout);
await rns.WaitForResourceAsync(dependentResource.Resource.Name, KnownResourceStates.Running).DefaultTimeout(TestConstants.DefaultOrchestratorTestLongTimeout);
await pendingStart.DefaultTimeout(TestConstants.DefaultOrchestratorTestTimeout);
await app.StopAsync().DefaultTimeout(TestConstants.DefaultOrchestratorTestTimeout);
}
[Fact]
public async Task BuildThrowsOnMissingHealthCheckRegistration()
{
using var builder = TestDistributedApplicationBuilder.Create();
builder.Services.AddLogging(b => {
b.AddXunit(testOutputHelper);
b.AddFakeLogging();
});
builder.AddResource(new CustomResource("test"))
.WithHealthCheck("test_check");
var app = builder.Build();
var ex = await Assert.ThrowsAsync<OptionsValidationException>(async () =>
{
await app.StartAsync();
}).DefaultTimeout(TestConstants.DefaultOrchestratorTestTimeout);
Assert.Equal("A health check registration is missing. Check logs for more details.", ex.Message);
var collector = app.Services.GetFakeLogCollector();
var logs = collector.GetSnapshot();
Assert.Contains(
logs,
l => l.Message == "The health check 'test_check' is not registered and is required for resource 'test'."
);
}
| HealthCheckTests |
csharp | LibreHardwareMonitor__LibreHardwareMonitor | LibreHardwareMonitorLib/Interop/AtiAdlxx.cs | {
"start": 19232,
"end": 19642
} | internal enum ____
{
// This typed is named like this in the documentation but for some reason AMD failed to include it...
// Yet it seems these correspond with ADL_PMLOG_TEMPERATURE_xxx.
EDGE = 1,
MEM = 2,
VRVDDC = 3,
VRMVDD = 4,
LIQUID = 5,
PLX = 6,
HOTSPOT = 7
}
[StructLayout(LayoutKind.Sequential)]
| ADLODNTemperatureType |
csharp | grpc__grpc-dotnet | test/FunctionalTests/Web/Client/ServerStreamingMethodTests.cs | {
"start": 1586,
"end": 9029
} | public class ____ : GrpcWebFunctionalTestBase
{
public ServerStreamingMethodTests(GrpcTestMode grpcTestMode, TestServerEndpointName endpointName)
: base(grpcTestMode, endpointName)
{
}
[Test]
public async Task SendValidRequest_StreamedContentReturned()
{
// Arrage
var httpClient = CreateGrpcWebClient();
var channel = GrpcChannel.ForAddress(httpClient.BaseAddress!, new GrpcChannelOptions
{
HttpClient = httpClient,
LoggerFactory = LoggerFactory
});
var client = new EchoService.EchoServiceClient(channel);
// Act
var call = client.ServerStreamingEcho(new ServerStreamingEchoRequest
{
Message = "test",
MessageCount = 3,
MessageInterval = TimeSpan.FromMilliseconds(10).ToDuration()
});
// Assert
Assert.IsTrue(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual("test", call.ResponseStream.Current.Message);
Assert.IsTrue(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual("test", call.ResponseStream.Current.Message);
Assert.IsTrue(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual("test", call.ResponseStream.Current.Message);
Assert.IsFalse(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual(null, call.ResponseStream.Current);
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
}
[Test]
public async Task SendValidRequest_ServerAbort_ClientThrowsAbortException()
{
// Arrage
var httpClient = CreateGrpcWebClient();
var channel = GrpcChannel.ForAddress(httpClient.BaseAddress!, new GrpcChannelOptions
{
HttpClient = httpClient,
LoggerFactory = LoggerFactory
});
var client = new EchoService.EchoServiceClient(channel);
// Act
var call = client.ServerStreamingEchoAbort(new ServerStreamingEchoRequest
{
Message = "test",
MessageCount = 3,
MessageInterval = TimeSpan.FromMilliseconds(10).ToDuration()
});
// Assert
Assert.IsTrue(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual("test", call.ResponseStream.Current.Message);
var ex = await ExceptionAssert.ThrowsAsync<RpcException>(() => call.ResponseStream.MoveNext(CancellationToken.None)).DefaultTimeout();
Assert.AreEqual(StatusCode.Aborted, ex.StatusCode);
Assert.AreEqual("Aborted from server side.", ex.Status.Detail);
Assert.AreEqual(StatusCode.Aborted, call.GetStatus().StatusCode);
// It is possible get into a situation where the response stream finishes slightly before the call.
// Small delay to ensure call logging is complete.
await Task.Delay(50);
AssertHasLog(LogLevel.Information, "GrpcStatusError", "Call failed with gRPC error status. Status code: 'Aborted', Message: 'Aborted from server side.'.");
AssertHasLogRpcConnectionError(StatusCode.Aborted, "Aborted from server side.");
}
[TestCase(true)]
[TestCase(false)]
public async Task SendValidRequest_ClientAbort_ClientThrowsCancelledException(bool delayWithCancellationToken)
{
var serverAbortedTcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
async Task ServerStreamingEcho(ServerStreamingEchoRequest request, IServerStreamWriter<ServerStreamingEchoResponse> responseStream, ServerCallContext context)
{
Logger.LogInformation("Server call started");
var httpContext = context.GetHttpContext();
httpContext.RequestAborted.Register(() =>
{
Logger.LogInformation("Server RequestAborted raised.");
serverAbortedTcs.SetResult(null);
});
try
{
for (var i = 0; i < request.MessageCount; i++)
{
Logger.LogInformation($"Server writing message {i}");
await responseStream.WriteAsync(new ServerStreamingEchoResponse
{
Message = request.Message
});
if (delayWithCancellationToken)
{
await Task.Delay(request.MessageInterval.ToTimeSpan(), context.CancellationToken);
}
else
{
await Task.Delay(request.MessageInterval.ToTimeSpan());
}
}
}
catch (Exception ex)
{
Logger.LogInformation(ex, "Server error.");
return;
}
finally
{
Logger.LogInformation("Server waiting for RequestAborted.");
await serverAbortedTcs.Task;
}
}
// Arrage
var method = Fixture.DynamicGrpc.AddServerStreamingMethod<ServerStreamingEchoRequest, ServerStreamingEchoResponse>(ServerStreamingEcho);
var httpClient = CreateGrpcWebClient();
var channel = GrpcChannel.ForAddress(httpClient.BaseAddress!, new GrpcChannelOptions
{
HttpClient = httpClient,
LoggerFactory = LoggerFactory
});
var cts = new CancellationTokenSource();
var client = TestClientFactory.Create(channel, method);
// Act
var call = client.ServerStreamingCall(new ServerStreamingEchoRequest
{
Message = "test",
MessageCount = 2,
MessageInterval = TimeSpan.FromMilliseconds(100).ToDuration()
}, new CallOptions(cancellationToken: cts.Token));
// Assert
Assert.IsTrue(await call.ResponseStream.MoveNext(CancellationToken.None).DefaultTimeout());
Assert.AreEqual("test", call.ResponseStream.Current.Message);
cts.Cancel();
var ex = await ExceptionAssert.ThrowsAsync<RpcException>(() => call.ResponseStream.MoveNext(CancellationToken.None)).DefaultTimeout();
Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
Assert.AreEqual("Call canceled by the client.", ex.Status.Detail);
Assert.AreEqual(StatusCode.Cancelled, call.GetStatus().StatusCode);
// It is possible get into a situation where the response stream finishes slightly before the call.
// Small delay to ensure call logging is complete.
await Task.Delay(50);
AssertHasLog(LogLevel.Information, "GrpcStatusError", "Call failed with gRPC error status. Status code: 'Cancelled', Message: 'Call canceled by the client.'.");
// HTTP/1.1 doesn't appear to send the cancellation to the server.
// This might be because the server has finished reading the response body
// and doesn't have a way to get the notification.
if (EndpointName != TestServerEndpointName.Http1)
{
// Verify the abort reached the server.
Logger.LogInformation("Client waiting for notification of abort in server.");
await serverAbortedTcs.Task.DefaultTimeout();
}
}
}
| ServerStreamingMethodTests |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/src/Analyzers/RouteHandlers/DisallowReturningActionResultFromMapMethods.cs | {
"start": 441,
"end": 3825
} | public partial class ____ : DiagnosticAnalyzer
{
private static void DisallowReturningActionResultFromMapMethods(
in OperationAnalysisContext context,
WellKnownTypes wellKnownTypes,
IInvocationOperation invocationOperation,
IAnonymousFunctionOperation anonymousFunction,
SyntaxNode nodeForError)
{
DisallowReturningActionResultFromMapMethods(in context, wellKnownTypes, invocationOperation, anonymousFunction.Symbol, anonymousFunction.Body, nodeForError);
}
private static void DisallowReturningActionResultFromMapMethods(
in OperationAnalysisContext context,
WellKnownTypes wellKnownTypes,
IInvocationOperation invocationOperation,
IMethodSymbol methodSymbol,
IBlockOperation? methodBody,
SyntaxNode nodeForError)
{
var returnType = UnwrapPossibleAsyncReturnType(methodSymbol.ReturnType);
if (wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Http_IResult).IsAssignableFrom(returnType))
{
// This type returns some form of IResult. Nothing to do here.
return;
}
if (methodBody is null &&
(wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Mvc_IActionResult).IsAssignableFrom(returnType) ||
wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Mvc_Infrastructure_IConvertToActionResult).IsAssignableFrom(returnType)))
{
// if we don't have a method body, and the action is IResult or ActionResult<T> returning, produce diagnostics for the entire method.
context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.DoNotReturnActionResultsFromRouteHandlers,
nodeForError.GetLocation(),
invocationOperation.TargetMethod.Name));
return;
}
foreach (var returnOperation in methodBody.Descendants().OfType<IReturnOperation>())
{
if (returnOperation.ReturnedValue is null or IInvalidOperation)
{
continue;
}
var returnedValue = returnOperation.ReturnedValue;
if (returnedValue is IConversionOperation conversionOperation)
{
returnedValue = conversionOperation.Operand;
}
var type = returnedValue.Type;
if (type is null)
{
continue;
}
if (wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Http_IResult).IsAssignableFrom(type))
{
continue;
}
if (wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Mvc_IActionResult).IsAssignableFrom(type))
{
context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.DoNotReturnActionResultsFromRouteHandlers,
returnOperation.Syntax.GetLocation(),
invocationOperation.TargetMethod.Name));
}
}
}
private static ITypeSymbol UnwrapPossibleAsyncReturnType(ITypeSymbol returnType)
{
if (returnType is not INamedTypeSymbol { Name: "Task" or "ValueTask", IsGenericType: true, TypeArguments: { Length: 1 } } taskLike)
{
return returnType;
}
return taskLike.TypeArguments[0];
}
}
| RouteHandlerAnalyzer |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Spatial/test/Types.Tests/TransformationIntegrationTests.cs | {
"start": 19496,
"end": 19747
} | public class ____
{
public LineString Test(LineString arg) => arg;
}
/// <summary>
/// The transformation are different from system to system. We need to round the result
/// to make it consistent!
/// </summary>
| Query |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver.Encryption/PinnedBinary.cs | {
"start": 817,
"end": 1636
} | internal class ____ : Binary
{
#region static
internal static void RunAsPinnedBinary<THandle>(THandle handle, byte[] bytes, Status status, Func<THandle, BinarySafeHandle, bool> handleFunc) where THandle : CheckableSafeHandle
{
unsafe
{
fixed (byte* map = bytes)
{
var ptr = (IntPtr)map;
using (var pinned = new PinnedBinary(ptr, (uint)bytes.Length))
{
handle.Check(status, handleFunc(handle, pinned.Handle));
}
}
}
}
#endregion
internal PinnedBinary(IntPtr ptr, uint len)
: base(Library.mongocrypt_binary_new_from_data(ptr, len))
{
}
}
}
| PinnedBinary |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Abstractions/src/Authorization/IAllowAnonymousFilter.cs | {
"start": 356,
"end": 417
} | public interface ____ : IFilterMetadata
{
}
| IAllowAnonymousFilter |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/Dynamic Modify/State_Specs.cs | {
"start": 3220,
"end": 4574
} | public class ____
{
[Test]
public void It_should_get_the_name_right()
{
Assert.That(_machine.GetState(_instance).Result, Is.EqualTo(Running));
}
State Running;
Event Started;
StateMachine<Instance> _machine;
Instance _instance;
[OneTimeSetUp]
public void A_state_is_declared()
{
_machine = MassTransitStateMachine<Instance>
.New(builder => builder
.State("Running", out Running)
.Event("Started", out Started)
.InstanceState(x => x.CurrentState, Running)
.Initially()
.When(Started, b => b.TransitionTo(Running))
);
_instance = new Instance();
_machine.RaiseEvent(_instance, Started).Wait();
}
/// <summary>
/// For this instance, the state is actually stored as a string. Therefore,
/// it is important that the StateMachine property is initialized when the
/// instance is hydrated, as it is used to get the State for the name of
/// the current state. This makes it easier to save the instance using
/// an ORM that doesn't support user types (cough, EF, cough).
/// </summary>
| When_storing_state_as_an_int |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Scaffolding/CompiledModelInMemoryTest.cs | {
"start": 9795,
"end": 9978
} | public class ____
{
public int Id { get; set; }
public virtual LazyProxiesEntity2? ReferenceNavigation { get; set; }
}
| LazyProxiesEntity1 |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Common/Startup/ForwardedHeadersStartup.cs | {
"start": 328,
"end": 1801
} | public class ____ : IStartupApplication
{
/// <summary>
/// Add and configure any of the middleware
/// </summary>
/// <param name="services">Collection of service descriptors</param>
/// <param name="configuration">Configuration root of the application</param>
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
}
/// <summary>
/// Configure the using of added middleware
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
/// <param name="webHostEnvironment">WebHostEnvironment</param>
public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
{
//check whether database is installed
if (!DataSettingsManager.DatabaseIsInstalled())
return;
var securityConfig = application.Services.GetRequiredService<SecurityConfig>();
if (securityConfig.ForceUseHTTPS)
application.Use((context, next) =>
{
context.Request.Scheme = "https";
return next(context);
});
if (securityConfig.UseForwardedHeaders)
application.UseGrandForwardedHeaders();
}
/// <summary>
/// Gets order of this startup configuration implementation
/// </summary>
public int Priority => -20;
public bool BeforeConfigure => true;
} | ForwardedHeadersStartup |
csharp | dotnet__efcore | src/ef/Commands/DbContextInfoCommand.cs | {
"start": 323,
"end": 1809
} | internal partial class ____
{
protected override int Execute(string[] args)
{
using var executor = CreateExecutor(args);
var result = executor.GetContextInfo(Context!.Value());
if (_json!.HasValue())
{
ReportJsonResult(result);
}
else
{
ReportResult(result);
}
return base.Execute(args);
}
private static void ReportJsonResult(IDictionary result)
{
Reporter.WriteData("{");
Reporter.WriteData(" \"type\": " + Json.Literal(result["Type"] as string) + ",");
Reporter.WriteData(" \"providerName\": " + Json.Literal(result["ProviderName"] as string) + ",");
Reporter.WriteData(" \"databaseName\": " + Json.Literal(result["DatabaseName"] as string) + ",");
Reporter.WriteData(" \"dataSource\": " + Json.Literal(result["DataSource"] as string) + ",");
Reporter.WriteData(" \"options\": " + Json.Literal(result["Options"] as string));
Reporter.WriteData("}");
}
private static void ReportResult(IDictionary result)
{
Reporter.WriteData(Resources.DbContextType(result["Type"]));
Reporter.WriteData(Resources.ProviderName(result["ProviderName"]));
Reporter.WriteData(Resources.DatabaseName(result["DatabaseName"]));
Reporter.WriteData(Resources.DataSource(result["DataSource"]));
Reporter.WriteData(Resources.Options(result["Options"]));
}
}
| DbContextInfoCommand |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Models/Catalog/CategoryNavigationModel.cs | {
"start": 74,
"end": 251
} | public class ____ : BaseModel
{
public string CurrentCategoryId { get; set; }
public List<CategorySimpleModel> Categories { get; set; } = new();
| CategoryNavigationModel |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Input/DragDrop.cs | {
"start": 138,
"end": 7006
} | public static class ____
{
/// <summary>
/// Event which is raised, when a drag-and-drop operation enters the element.
/// </summary>
public static readonly RoutedEvent<DragEventArgs> DragEnterEvent = RoutedEvent.Register<DragEventArgs>("DragEnter", RoutingStrategies.Bubble, typeof(DragDrop));
/// <summary>
/// Event which is raised, when a drag-and-drop operation leaves the element.
/// </summary>
public static readonly RoutedEvent<DragEventArgs> DragLeaveEvent = RoutedEvent.Register<DragEventArgs>("DragLeave", RoutingStrategies.Bubble, typeof(DragDrop));
/// <summary>
/// Event which is raised, when a drag-and-drop operation is updated while over the element.
/// </summary>
public static readonly RoutedEvent<DragEventArgs> DragOverEvent = RoutedEvent.Register<DragEventArgs>("DragOver", RoutingStrategies.Bubble, typeof(DragDrop));
/// <summary>
/// Event which is raised, when a drag-and-drop operation should complete over the element.
/// </summary>
public static readonly RoutedEvent<DragEventArgs> DropEvent = RoutedEvent.Register<DragEventArgs>("Drop", RoutingStrategies.Bubble, typeof(DragDrop));
public static readonly AttachedProperty<bool> AllowDropProperty = AvaloniaProperty.RegisterAttached<Interactive, bool>("AllowDrop", typeof(DragDrop), inherits: true);
/// <summary>
/// Gets a value indicating whether the given element can be used as the target of a drag-and-drop operation.
/// </summary>
public static bool GetAllowDrop(Interactive interactive)
{
return interactive.GetValue(AllowDropProperty);
}
/// <summary>
/// Sets a value indicating whether the given interactive can be used as the target of a drag-and-drop operation.
/// </summary>
public static void SetAllowDrop(Interactive interactive, bool value)
{
interactive.SetValue(AllowDropProperty, value);
}
/// <summary>
/// Adds a handler for the DragEnter attached event.
/// </summary>
/// <param name="element">The element to attach the handler to.</param>
/// <param name="handler">The handler for the event.</param>
public static void AddDragEnterHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.AddHandler(DragEnterEvent, handler);
}
/// <summary>
/// Removes a handler for the DragEnter attached event.
/// </summary>
/// <param name="element">The element to remove the handler from.</param>
/// <param name="handler">The handler to remove.</param>
public static void RemoveDragEnterHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.RemoveHandler(DragEnterEvent, handler);
}
/// <summary>
/// Adds a handler for the DragLeave attached event.
/// </summary>
/// <param name="element">The element to attach the handler to.</param>
/// <param name="handler">The handler for the event.</param>
public static void AddDragLeaveHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.AddHandler(DragLeaveEvent, handler);
}
/// <summary>
/// Removes a handler for the DragLeave attached event.
/// </summary>
/// <param name="element">The element to remove the handler from.</param>
/// <param name="handler">The handler to remove.</param>
public static void RemoveDragLeaveHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.RemoveHandler(DragLeaveEvent, handler);
}
/// <summary>
/// Adds a handler for the DragOver attached event.
/// </summary>
/// <param name="element">The element to attach the handler to.</param>
/// <param name="handler">The handler for the event.</param>
public static void AddDragOverHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.AddHandler(DragOverEvent, handler);
}
/// <summary>
/// Removes a handler for the DragOver attached event.
/// </summary>
/// <param name="element">The element to remove the handler from.</param>
/// <param name="handler">The handler to remove.</param>
public static void RemoveDragOverHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.RemoveHandler(DragOverEvent, handler);
}
/// <summary>
/// Adds a handler for the Drop attached event.
/// </summary>
/// <param name="element">The element to attach the handler to.</param>
/// <param name="handler">The handler for the event.</param>
public static void AddDropHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.AddHandler(DropEvent, handler);
}
/// <summary>
/// Removes a handler for the Drop attached event.
/// </summary>
/// <param name="element">The element to remove the handler from.</param>
/// <param name="handler">The handler to remove.</param>
public static void RemoveDropHandler(Interactive element, EventHandler<DragEventArgs> handler)
{
element.RemoveHandler(DropEvent, handler);
}
/// <summary>
/// Starts a dragging operation with the given <see cref="IDataObject"/> and returns the applied drop effect from the target.
/// <seealso cref="DataObject"/>
/// </summary>
[Obsolete($"Use {nameof(DoDragDropAsync)} instead.")]
public static Task<DragDropEffects> DoDragDrop(PointerEventArgs triggerEvent, IDataObject data, DragDropEffects allowedEffects)
{
return DoDragDropAsync(triggerEvent, new DataObjectToDataTransferWrapper(data), allowedEffects);
}
/// <summary>
/// Starts a dragging operation with the given <see cref="IDataTransfer"/> and returns the applied drop effect from the target.
/// <seealso cref="DataTransfer"/>
/// </summary>
public static Task<DragDropEffects> DoDragDropAsync(
PointerEventArgs triggerEvent,
IDataTransfer dataTransfer,
DragDropEffects allowedEffects)
{
if (AvaloniaLocator.Current.GetService<IPlatformDragSource>() is not { } dragSource)
{
dataTransfer.Dispose();
return Task.FromResult(DragDropEffects.None);
}
return dragSource.DoDragDropAsync(triggerEvent, dataTransfer, allowedEffects);
}
}
}
| DragDrop |
csharp | dotnet__aspnetcore | src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs | {
"start": 531,
"end": 2005
} | public static class ____
{
/// <summary>
/// Adds services required for propagating headers to a <see cref="HttpClient"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddHeaderPropagation(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
services.TryAddSingleton<HeaderPropagationValues>();
return services;
}
/// <summary>
/// Adds services required for propagating headers to a <see cref="HttpClient"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <param name="configureOptions">A delegate used to configure the <see cref="HeaderPropagationOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddHeaderPropagation(this IServiceCollection services, Action<HeaderPropagationOptions> configureOptions)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configureOptions);
services.Configure(configureOptions);
services.AddHeaderPropagation();
return services;
}
}
| HeaderPropagationServiceCollectionExtensions |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternAnalyzerTests.cs | {
"start": 2781,
"end": 3578
} | class ____ : Attribute
{
public HttpGet([StringSyntax(""Route"")] string pattern)
{
}
}
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
var diagnostic = Assert.Single(diagnostics);
Assert.Same(DiagnosticDescriptors.RoutePatternIssue, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal(Resources.FormatAnalyzer_RouteIssue_Message(Resources.TemplateRoute_InvalidRouteTemplate), diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
[Fact]
public async Task StringSyntax_FieldSet_ReportResults()
{
// Arrange
var source = TestSource.Read(@"
using System.Diagnostics.CodeAnalysis;
| HttpGet |
csharp | dotnet__aspnetcore | src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTestBase.cs | {
"start": 18777,
"end": 19516
} | private class ____ : IServiceScope, IServiceProvider, IServiceScopeFactory, IServiceProviderIsService
{
public IServiceProvider ServiceProvider => this;
public IServiceScope CreateScope()
{
return this;
}
public void Dispose() { }
public object GetService(Type serviceType)
{
if (IsService(serviceType))
{
return this;
}
return null;
}
public bool IsService(Type serviceType) =>
serviceType == typeof(IServiceProvider) ||
serviceType == typeof(IServiceScopeFactory) ||
serviceType == typeof(IServiceProviderIsService);
}
| EmptyServiceProvider |
csharp | MassTransit__MassTransit | src/MassTransit/SqlTransport/SqlTransport/HostInfoCache.cs | {
"start": 106,
"end": 404
} | public static class ____
{
static readonly Lazy<string> _hostInfoJson =
new Lazy<string>(() => SystemTextJsonMessageSerializer.Instance.SerializeObject(HostMetadataCache.Host).GetString());
public static string HostInfoJson => _hostInfoJson.Value;
}
}
| HostInfoCache |
csharp | protobuf-net__protobuf-net | src/NativeGoogleTests/Timeofday.cs | {
"start": 2119,
"end": 10889
} | partial class ____ : pb::IMessage<TimeOfDay>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<TimeOfDay> _parser = new pb::MessageParser<TimeOfDay>(() => new TimeOfDay());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TimeOfDay> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.TimeofdayReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeOfDay() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeOfDay(TimeOfDay other) : this() {
hours_ = other.hours_;
minutes_ = other.minutes_;
seconds_ = other.seconds_;
nanos_ = other.nanos_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeOfDay Clone() {
return new TimeOfDay(this);
}
/// <summary>Field number for the "hours" field.</summary>
public const int HoursFieldNumber = 1;
private int hours_;
/// <summary>
/// Hours of day in 24 hour format. Should be from 0 to 23. An API may choose
/// to allow the value "24:00:00" for scenarios like business closing time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Hours {
get { return hours_; }
set {
hours_ = value;
}
}
/// <summary>Field number for the "minutes" field.</summary>
public const int MinutesFieldNumber = 2;
private int minutes_;
/// <summary>
/// Minutes of hour of day. Must be from 0 to 59.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Minutes {
get { return minutes_; }
set {
minutes_ = value;
}
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 3;
private int seconds_;
/// <summary>
/// Seconds of minutes of the time. Must normally be from 0 to 59. An API may
/// allow the value 60 if it allows leap-seconds.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 4;
private int nanos_;
/// <summary>
/// Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TimeOfDay);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TimeOfDay other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Hours != other.Hours) return false;
if (Minutes != other.Minutes) return false;
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Hours != 0) hash ^= Hours.GetHashCode();
if (Minutes != 0) hash ^= Minutes.GetHashCode();
if (Seconds != 0) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Hours != 0) {
output.WriteRawTag(8);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(16);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(24);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(32);
output.WriteInt32(Nanos);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Hours != 0) {
output.WriteRawTag(8);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(16);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(24);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(32);
output.WriteInt32(Nanos);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Hours != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Hours);
}
if (Minutes != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Minutes);
}
if (Seconds != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TimeOfDay other) {
if (other == null) {
return;
}
if (other.Hours != 0) {
Hours = other.Hours;
}
if (other.Minutes != 0) {
Minutes = other.Minutes;
}
if (other.Seconds != 0) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Hours = input.ReadInt32();
break;
}
case 16: {
Minutes = input.ReadInt32();
break;
}
case 24: {
Seconds = input.ReadInt32();
break;
}
case 32: {
Nanos = input.ReadInt32();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Hours = input.ReadInt32();
break;
}
case 16: {
Minutes = input.ReadInt32();
break;
}
case 24: {
Seconds = input.ReadInt32();
break;
}
case 32: {
Nanos = input.ReadInt32();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| TimeOfDay |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs | {
"start": 431,
"end": 804
} | public interface ____
{
ShapeMetadata Metadata { get; }
string Id { get; set; }
string TagName { get; set; }
IList<string> Classes { get; }
IDictionary<string, string> Attributes { get; }
IDictionary<string, object> Properties { get; }
IReadOnlyList<IPositioned> Items { get; }
ValueTask<IShape> AddAsync(object item, string position);
}
| IShape |
csharp | unoplatform__uno | src/Uno.Foundation/Uno.Core.Extensions/Uno.Core.Extensions.Disposables/Disposables/DisposableExtensions.cs | {
"start": 881,
"end": 2613
} | internal static class ____
{
/// <summary>
/// Register an object who implements IDisposable to be disposed by a CompositeDisposable.
/// </summary>
/// <remarks>
/// The parameter could be anything who implements ICollection<IDisposable>.
/// This extension is designed for usage in a fluent declaration.
/// </remarks>
public static T? DisposeWith<T>(this T? disposable, ICollection<IDisposable> composite)
where T : class, IDisposable
{
if (disposable != null)
{
composite.Add(disposable);
}
return disposable;
}
/// <summary>
/// Register an object who implements IDisposable to be disposed by a SerialDisposable.
/// </summary>
/// <remarks>
/// This extension is designed for usage in a fluent declaration.
/// </remarks>
public static T DisposeWith<T>(this T disposable, SerialDisposable serialDisposable)
where T : class, IDisposable
{
if (serialDisposable == null)
{
throw new ArgumentNullException("serialDisposable");
}
serialDisposable.Disposable = disposable;
return disposable;
}
/// <summary>
/// Dispose the object if not null
/// </summary>
public static void SafeDispose(this IDisposable? disposable)
{
if (null != disposable)
{
disposable.Dispose();
}
}
/// <summary>
/// Dispose the object if not null and if it implements IDisposable
/// </summary>
/// <returns>
/// True means the object was successfully disposed.
/// </returns>
public static bool TryDispose(this object maybeDisposableObject)
{
var disposable = maybeDisposableObject as IDisposable;
if (disposable != null)
{
disposable.Dispose();
return true;
}
return false;
}
}
}
| DisposableExtensions |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 180478,
"end": 180695
} | public class ____
{
public int Id { get; set; }
public RelatedEntity832 ParentEntity { get; set; }
public IEnumerable<RelatedEntity834> ChildEntities { get; set; }
}
| RelatedEntity833 |
csharp | dotnet__orleans | src/Orleans.Core/Utils/AsyncEnumerable.cs | {
"start": 208,
"end": 388
} | internal static class ____
{
internal static readonly object InitialValue = new();
internal static readonly object DisposedValue = new();
}
| AsyncEnumerable |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/Mappings/ConstructorParameter/FormatAttributeTests.cs | {
"start": 2820,
"end": 3044
} | private class ____
{
public int Id { get; private set; }
public DateTimeOffset Date { get; private set; }
public Foo(int id, [Format(FORMAT)] DateTimeOffset date)
{
Id = id;
Date = date;
}
}
}
}
| Foo |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Build/WoodpeckerCI/Data/WoodpeckerCIRepositoryInfoTests.cs | {
"start": 807,
"end": 1229
} | public sealed class ____
{
[Fact]
public void Should_Return_Correct_Value()
{
// Given
var info = new WoodpeckerCIInfoFixture().CreateRepositoryInfo();
// When
var result = info.RepoOwner;
// Then
Assert.Equal("john-doe", result);
}
}
| TheRepoOwnerProperty |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Server.Tests/Messaging/MqServerIntroTests.cs | {
"start": 1600,
"end": 1847
} | public class ____ : MqServerIntroTests
{
public override IMessageService CreateMqServer(int retryCount = 1)
{
return new BackgroundMqService { RetryCount = retryCount };
}
}
| BackgroundMqServerIntroTests |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWebCore/ContactServices.cs | {
"start": 11095,
"end": 11729
} | public static class ____
{
internal static readonly ServiceInterface.ContactServiceFilters Instance = new ServiceInterface.ContactServiceFilters();
public static Dictionary<string, string> ContactColors(this IHtmlHelper html) => Instance.contactColors();
public static List<KeyValuePair<string, string>> ContactTitles(this IHtmlHelper html) => Instance.contactTitles();
public static List<string> ContactGenres(this IHtmlHelper html) => Instance.contactGenres();
public static List<NavItem> MenuItems(this IHtmlHelper html) => ViewUtils.GetNavItems("Menu");
}
| RazorHelpers |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.BlobStoring/BlobStoring/IBlobContainerConfigurationProvider.cs | {
"start": 33,
"end": 458
} | public interface ____
{
/// <summary>
/// Gets a <see cref="BlobContainerConfiguration"/> for the given container <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the container</param>
/// <returns>The configuration that should be used for the container</returns>
BlobContainerConfiguration Get(string name);
}
} | IBlobContainerConfigurationProvider |
csharp | grpc__grpc-dotnet | test/Grpc.Net.ClientFactory.Tests/GrpcHttpClientBuilderExtensionsTests.cs | {
"start": 2309,
"end": 29839
} | private class ____
{
public TestService(int value)
{
Value = value;
}
public int Value { get; }
}
[Test]
public async Task AddInterceptor_MultipleInstances_ExecutedInOrder()
{
// Arrange
var list = new List<int>();
var testHttpMessageHandler = new TestHttpMessageHandler();
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddInterceptor(() => new CallbackInterceptor(o => list.Add(1)))
.AddInterceptor(() => new CallbackInterceptor(o => list.Add(2)))
.AddInterceptor(() => new CallbackInterceptor(o => list.Add(3)))
.ConfigurePrimaryHttpMessageHandler(() => testHttpMessageHandler);
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsTrue(testHttpMessageHandler.Invoked);
Assert.IsNotNull(response);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(1, list[0]);
Assert.AreEqual(2, list[1]);
Assert.AreEqual(3, list[2]);
}
[Test]
public void AddInterceptor_OnGrpcClientFactoryWithServicesConfig_Success()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<CallbackInterceptor>(s => new CallbackInterceptor(o => { }));
// Act
services
.AddGrpcClient<Greeter.GreeterClient>((s, o) => o.Address = new Uri("http://localhost"))
.AddInterceptor<CallbackInterceptor>()
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
// Assert
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
Assert.IsNotNull(serviceProvider.GetRequiredService<Greeter.GreeterClient>());
}
[Test]
public void AddInterceptor_NotFromGrpcClientFactoryAndExistingGrpcClient_ThrowError()
{
// Arrange
var services = new ServiceCollection();
var client = services.AddHttpClient("TestClient");
var ex = Assert.Throws<InvalidOperationException>(() => client.AddInterceptor(() => new CallbackInterceptor(o => { })))!;
Assert.AreEqual("AddInterceptor must be used with a gRPC client.", ex.Message);
ex = Assert.Throws<InvalidOperationException>(() => client.AddInterceptor(s => new CallbackInterceptor(o => { })))!;
Assert.AreEqual("AddInterceptor must be used with a gRPC client.", ex.Message);
}
[Test]
public void AddInterceptor_AddGrpcClientWithoutConfig_NoError()
{
// Arrange
var services = new ServiceCollection();
var client = services.AddGrpcClient<Greeter.GreeterClient>();
// Act
client.AddInterceptor(() => new CallbackInterceptor(o => { }));
}
[Test]
public void AddInterceptor_AddGrpcClientWithNameAndWithoutConfig_NoError()
{
// Arrange
var services = new ServiceCollection();
var client = services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
// Act
client.AddInterceptor(() => new CallbackInterceptor(o => { }));
}
[Test]
public void AddInterceptor_NotFromGrpcClientFactory_ThrowError()
{
// Arrange
var services = new ServiceCollection();
var client = services.AddHttpClient("TestClient");
var ex = Assert.Throws<InvalidOperationException>(() => client.AddInterceptor(() => new CallbackInterceptor(o => { })))!;
Assert.AreEqual("AddInterceptor must be used with a gRPC client.", ex.Message);
ex = Assert.Throws<InvalidOperationException>(() => client.AddInterceptor(s => new CallbackInterceptor(o => { })))!;
Assert.AreEqual("AddInterceptor must be used with a gRPC client.", ex.Message);
}
[Test]
public async Task AddInterceptorGeneric_MultipleInstances_ExecutedInOrder()
{
// Arrange
var list = new List<int>();
var i = 0;
var services = new ServiceCollection();
services.AddTransient<CallbackInterceptor>(s => new CallbackInterceptor(o =>
{
var increment = i += 2;
list.Add(increment);
}));
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddInterceptor<CallbackInterceptor>()
.AddInterceptor<CallbackInterceptor>()
.AddInterceptor<CallbackInterceptor>()
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsNotNull(response);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(2, list[0]);
Assert.AreEqual(4, list[1]);
Assert.AreEqual(6, list[2]);
}
[Test]
public void AddInterceptorGeneric_NotFromGrpcClientFactory_ThrowError()
{
// Arrange
var services = new ServiceCollection();
var client = services.AddHttpClient("TestClient");
var ex = Assert.Throws<InvalidOperationException>(() => client.AddInterceptor<CallbackInterceptor>())!;
Assert.AreEqual("AddInterceptor must be used with a gRPC client.", ex.Message);
}
[Test]
public void ConfigureGrpcClientCreator_CreatorSuccess_ClientReturned()
{
// Arrange
Greeter.GreeterClient? createdClient = null;
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.ConfigureGrpcClientCreator(callInvoker =>
{
createdClient = new Greeter.GreeterClient(callInvoker);
return createdClient;
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
// Assert
Assert.IsNotNull(client);
Assert.AreEqual(createdClient, client);
}
[Test]
public void ConfigureGrpcClientCreator_ServiceProviderCreatorSuccess_ClientReturned()
{
// Arrange
DerivedGreeterClient? createdGreaterClient = null;
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.ConfigureGrpcClientCreator((serviceProvider, callInvoker) =>
{
createdGreaterClient = new DerivedGreeterClient(callInvoker);
return createdGreaterClient;
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
services
.AddGrpcClient<SecondGreeter.SecondGreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var greeterClient = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var secondGreeterClient = clientFactory.CreateClient<SecondGreeter.SecondGreeterClient>(nameof(SecondGreeter.SecondGreeterClient));
// Assert
Assert.IsNotNull(greeterClient);
Assert.AreEqual(createdGreaterClient, greeterClient);
Assert.IsNotNull(secondGreeterClient);
}
[Test]
public void ConfigureGrpcClientCreator_CreatorReturnsNull_ThrowError()
{
// Arrange
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.ConfigureGrpcClientCreator(callInvoker =>
{
return null!;
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var ex = Assert.Throws<InvalidOperationException>(() => clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient)))!;
// Assert
Assert.AreEqual("A null instance was returned by the configured client creator.", ex.Message);
}
[Test]
public void ConfigureGrpcClientCreator_CreatorReturnsIncorrectType_ThrowError()
{
// Arrange
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.ConfigureGrpcClientCreator(callInvoker =>
{
return new object();
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var ex = Assert.Throws<InvalidOperationException>(() => clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient)))!;
// Assert
Assert.AreEqual("The System.Object instance returned by the configured client creator is not compatible with Greet.Greeter+GreeterClient.", ex.Message);
}
[TestCase(InterceptorScope.Client, 2)]
[TestCase(InterceptorScope.Channel, 1)]
public async Task AddInterceptor_InterceptorLifetime_InterceptorCreatedCountCorrect(InterceptorScope scope, int callCount)
{
// Arrange
var testHttpMessageHandler = new TestHttpMessageHandler();
var interceptorCreatedCount = 0;
var services = new ServiceCollection();
services.AddTransient<CallbackInterceptor>(s =>
{
interceptorCreatedCount++;
return new CallbackInterceptor(o => { });
});
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddInterceptor<CallbackInterceptor>(scope)
.ConfigurePrimaryHttpMessageHandler(() => testHttpMessageHandler);
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client1 = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
await client1.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
var client2 = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
await client2.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.AreEqual(callCount, interceptorCreatedCount);
}
[TestCase(1)]
[TestCase(2)]
public async Task AddInterceptor_ClientLifetimeInScope_InterceptorCreatedCountCorrect(int scopes)
{
// Arrange
var testHttpMessageHandler = new TestHttpMessageHandler();
var interceptorCreatedCount = 0;
var services = new ServiceCollection();
services.AddScoped<CallbackInterceptor>(s =>
{
interceptorCreatedCount++;
return new CallbackInterceptor(o => { });
});
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddInterceptor<CallbackInterceptor>(InterceptorScope.Client)
.ConfigurePrimaryHttpMessageHandler(() => testHttpMessageHandler);
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
for (var i = 0; i < scopes; i++)
{
await MakeCallsInScope(serviceProvider);
}
// Assert
Assert.AreEqual(scopes, interceptorCreatedCount);
static async Task MakeCallsInScope(ServiceProvider rootServiceProvider)
{
var scope = rootServiceProvider.CreateScope();
var clientFactory = scope.ServiceProvider.GetRequiredService<GrpcClientFactory>();
var client1 = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
await client1.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
var client2 = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
await client2.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
}
}
[Test]
public async Task AddInterceptorGeneric_ScopedLifetime_CreatedOncePerScope()
{
// Arrange
var i = 0;
var channelInterceptorCreatedCount = 0;
var services = new ServiceCollection();
services.AddScoped<List<int>>();
services.AddScoped<CallbackInterceptor>(s =>
{
var increment = ++i;
return new CallbackInterceptor(o =>
{
var list = s.GetRequiredService<List<int>>();
list.Add(increment * list.Count);
});
});
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddInterceptor(() =>
{
channelInterceptorCreatedCount++;
return new CallbackInterceptor(o => { });
})
.AddInterceptor<CallbackInterceptor>(InterceptorScope.Client)
.AddInterceptor<CallbackInterceptor>(InterceptorScope.Client)
.AddInterceptor<CallbackInterceptor>(InterceptorScope.Client)
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
using (var scope = serviceProvider.CreateScope())
{
var list = scope.ServiceProvider.GetRequiredService<List<int>>();
var clientFactory = scope.ServiceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsNotNull(response);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(0, list[0]);
Assert.AreEqual(1, list[1]);
Assert.AreEqual(2, list[2]);
}
// Act
using (var scope = serviceProvider.CreateScope())
{
var list = scope.ServiceProvider.GetRequiredService<List<int>>();
var clientFactory = scope.ServiceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsNotNull(response);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(0, list[0]);
Assert.AreEqual(2, list[1]);
Assert.AreEqual(4, list[2]);
}
// Only one channel and its interceptor is created for multiple scopes.
Assert.AreEqual(1, channelInterceptorCreatedCount);
}
[Test]
public async Task AddCallCredentials_ServiceProvider_RunInScope()
{
// Arrange
var scopeCount = 0;
var authHeaderValues = new List<string>();
var services = new ServiceCollection();
services
.AddScoped<AuthProvider>(s => new AuthProvider((scopeCount++).ToString(CultureInfo.InvariantCulture)))
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost");
})
.AddCallCredentials(async (context, metadata, serviceProvider) =>
{
var authProvider = serviceProvider.GetRequiredService<AuthProvider>();
metadata.Add("authorize", await authProvider.GetTokenAsync());
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler(request =>
{
if (request.Headers.TryGetValues("authorize", out var values))
{
authHeaderValues.AddRange(values);
}
}));
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
using (var scope = serviceProvider.CreateScope())
{
var clientFactory = scope.ServiceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response1 = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
var response2 = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsNotNull(response1);
Assert.IsNotNull(response2);
Assert.AreEqual(2, authHeaderValues.Count);
Assert.AreEqual("0", authHeaderValues[0]);
Assert.AreEqual("0", authHeaderValues[1]);
}
authHeaderValues.Clear();
// Act
using (var scope = serviceProvider.CreateScope())
{
var clientFactory = scope.ServiceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response1 = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
var response2 = await client.SayHelloAsync(new HelloRequest()).ResponseAsync.DefaultTimeout();
// Assert
Assert.IsNotNull(response1);
Assert.IsNotNull(response2);
Assert.AreEqual(2, authHeaderValues.Count);
Assert.AreEqual("1", authHeaderValues[0]);
Assert.AreEqual("1", authHeaderValues[1]);
}
// Only one channel and its interceptor is created for multiple scopes.
Assert.AreEqual(2, scopeCount);
}
[Test]
public async Task AddCallCredentials_CallCredentials_HeaderAdded()
{
// Arrange
HttpRequestMessage? sentRequest = null;
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost");
})
.AddCallCredentials(CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("factory-authorize", "auth!");
return Task.CompletedTask;
}))
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler(request =>
{
sentRequest = request;
}));
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(
new HelloRequest(),
new CallOptions()).ResponseAsync.DefaultTimeout();
// Assert
Assert.NotNull(response);
Assert.AreEqual("auth!", sentRequest!.Headers.GetValues("factory-authorize").Single());
}
[Test]
public void AddCallCredentials_InsecureChannel_Error()
{
// Arrange
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddCallCredentials(CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("factory-authorize", "auth!");
return Task.CompletedTask;
}))
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler());
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var ex = Assert.Throws<InvalidOperationException>(() => clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient)))!;
// Assert
Assert.AreEqual("Call credential configured for gRPC client 'GreeterClient' requires TLS, and the client isn't configured to use TLS. " +
"Either configure a TLS address, or use the call credential without TLS by setting GrpcChannelOptions.UnsafeUseInsecureChannelCallCredentials to true: " +
"client.AddCallCredentials((context, metadata) => {}).ConfigureChannel(o => o.UnsafeUseInsecureChannelCallCredentials = true)", ex.Message);
}
#if NET5_0_OR_GREATER
[Test]
public void AddCallCredentials_StaticLoadBalancingSecureChannel_Success()
{
// Arrange
HttpRequestMessage? sentRequest = null;
var services = new ServiceCollection();
services.AddSingleton<ResolverFactory>(new StaticResolverFactory(_ => new[]
{
new BalancerAddress("localhost", 80)
}));
// Can't use ConfigurePrimaryHttpMessageHandler with load balancing because underlying
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("static:///localhost");
})
.ConfigureChannel(o =>
{
o.Credentials = ChannelCredentials.SecureSsl;
})
.AddCallCredentials(CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("factory-authorize", "auth!");
return Task.CompletedTask;
}))
.AddHttpMessageHandler(() => new TestHttpMessageHandler(request =>
{
sentRequest = request;
}));
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act & Assert
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
_ = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
// No call because there isn't an endpoint at localhost:80
}
#endif
[Test]
public async Task AddCallCredentials_InsecureChannel_UnsafeUseInsecureChannelCallCredentials_Success()
{
// Arrange
HttpRequestMessage? sentRequest = null;
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("http://localhost");
})
.AddCallCredentials(CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("factory-authorize", "auth!");
return Task.CompletedTask;
}))
.ConfigureChannel(o => o.UnsafeUseInsecureChannelCallCredentials = true)
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler(request =>
{
sentRequest = request;
}));
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(
new HelloRequest(),
new CallOptions()).ResponseAsync.DefaultTimeout();
// Assert
Assert.NotNull(response);
Assert.AreEqual("auth!", sentRequest!.Headers.GetValues("factory-authorize").Single());
}
[Test]
public async Task AddCallCredentials_PassedInCallCredentials_Combine()
{
// Arrange
HttpRequestMessage? sentRequest = null;
var services = new ServiceCollection();
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost");
})
.ConfigureChannel(c =>
{
c.Credentials = ChannelCredentials.Create(ChannelCredentials.SecureSsl, CallCredentials.FromInterceptor((c, m) =>
{
m.Add("channel-authorize", "auth!");
return Task.CompletedTask;
}));
})
.AddCallCredentials((context, metadata) =>
{
metadata.Add("factory-authorize", "auth!");
return Task.CompletedTask;
})
.ConfigurePrimaryHttpMessageHandler(() => new TestHttpMessageHandler(request =>
{
sentRequest = request;
}));
var serviceProvider = services.BuildServiceProvider(validateScopes: true);
// Act
var clientFactory = serviceProvider.GetRequiredService<GrpcClientFactory>();
var client = clientFactory.CreateClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
var response = await client.SayHelloAsync(
new HelloRequest(),
new CallOptions(credentials: CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("call-authorize", "auth!");
return Task.CompletedTask;
}))).ResponseAsync.DefaultTimeout();
// Assert
Assert.NotNull(response);
Assert.AreEqual("auth!", sentRequest!.Headers.GetValues("channel-authorize").Single());
Assert.AreEqual("auth!", sentRequest!.Headers.GetValues("factory-authorize").Single());
Assert.AreEqual("auth!", sentRequest!.Headers.GetValues("call-authorize").Single());
}
| TestService |
csharp | rabbitmq__rabbitmq-dotnet-client | projects/RabbitMQ.Client/Exceptions/ProtocolException.cs | {
"start": 1721,
"end": 2502
} | public abstract class ____ : RabbitMQClientException
{
protected ProtocolException(string message) : base(message)
{
}
///<summary>Retrieve the reply code to use in a
///connection/channel close method.</summary>
public abstract ushort ReplyCode { get; }
///<summary>Retrieve the shutdown details to use in a
///connection/channel close method. Defaults to using
///ShutdownInitiator.Library, and this.ReplyCode and
///this.Message as the reply code and text,
///respectively.</summary>
public virtual ShutdownEventArgs ShutdownReason
{
get { return new ShutdownEventArgs(ShutdownInitiator.Library, ReplyCode, Message, this); }
}
}
}
| ProtocolException |
csharp | microsoft__semantic-kernel | dotnet/src/VectorData/AzureAISearch/AzureAISearchModelBuilder.cs | {
"start": 288,
"end": 3136
} | internal class ____() : CollectionJsonModelBuilder(s_modelBuildingOptions)
{
internal const string SupportedVectorTypes = "ReadOnlyMemory<float>, Embedding<float>, float[]";
internal static readonly CollectionModelBuildingOptions s_modelBuildingOptions = new()
{
RequiresAtLeastOneVector = false,
SupportsMultipleKeys = false,
SupportsMultipleVectors = true,
UsesExternalSerializer = true
};
protected override bool IsKeyPropertyTypeValid(Type type, [NotNullWhen(false)] out string? supportedTypes)
=> IsKeyPropertyTypeValidCore(type, out supportedTypes);
protected override bool IsDataPropertyTypeValid(Type type, [NotNullWhen(false)] out string? supportedTypes)
=> IsDataPropertyTypeValidCore(type, out supportedTypes);
protected override bool IsVectorPropertyTypeValid(Type type, [NotNullWhen(false)] out string? supportedTypes)
=> IsVectorPropertyTypeValidCore(type, out supportedTypes);
internal static bool IsKeyPropertyTypeValidCore(Type type, [NotNullWhen(false)] out string? supportedTypes)
{
supportedTypes = "string, Guid";
return type == typeof(string) || type == typeof(Guid);
}
internal static bool IsDataPropertyTypeValidCore(Type type, [NotNullWhen(false)] out string? supportedTypes)
{
supportedTypes = "string, int, long, double, float, bool, DateTimeOffset, or arrays/lists of these types";
if (Nullable.GetUnderlyingType(type) is Type underlyingType)
{
type = underlyingType;
}
return IsValid(type)
|| (type.IsArray && IsValid(type.GetElementType()!))
|| (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>) && IsValid(type.GenericTypeArguments[0]));
static bool IsValid(Type type)
=> type == typeof(string) ||
type == typeof(int) ||
type == typeof(long) ||
type == typeof(double) ||
type == typeof(float) ||
type == typeof(bool) ||
type == typeof(DateTimeOffset);
}
internal static bool IsVectorPropertyTypeValidCore(Type type, [NotNullWhen(false)] out string? supportedTypes)
{
// Azure AI Search is adding support for more types than just float32, but these are not available for use via the
// SDK yet. We will update this list as the SDK is updated.
// <see href="https://learn.microsoft.com/en-us/rest/api/searchservice/supported-data-types#edm-data-types-for-vector-fields"/>
supportedTypes = SupportedVectorTypes;
return type == typeof(ReadOnlyMemory<float>)
|| type == typeof(ReadOnlyMemory<float>?)
|| type == typeof(Embedding<float>)
|| type == typeof(float[]);
}
}
| AzureAISearchModelBuilder |
csharp | dotnet__aspire | tools/GenerateTestSummary/TrxReader.cs | {
"start": 246,
"end": 4318
} | public class ____
{
public static IList<TestResult> GetTestResultsFromTrx(string filepath, Func<string, string, bool>? testFilter = null)
{
XmlSerializer serializer = new(typeof(TestRun));
using FileStream fileStream = new(filepath, FileMode.Open);
if (serializer.Deserialize(fileStream) is not TestRun testRun || testRun.Results?.UnitTestResults is null)
{
return Array.Empty<TestResult>();
}
var testResults = new List<TestResult>();
foreach (var unitTestResult in testRun.Results.UnitTestResults)
{
if (string.IsNullOrEmpty(unitTestResult.TestName) || string.IsNullOrEmpty(unitTestResult.Outcome))
{
continue;
}
if (testFilter is not null && !testFilter(unitTestResult.TestName, unitTestResult.Outcome))
{
continue;
}
var startTime = unitTestResult.StartTime;
var endTime = unitTestResult.EndTime;
testResults.Add(new TestResult(
Name: unitTestResult.TestName,
Outcome: unitTestResult.Outcome,
StartTime: startTime is null ? TimeSpan.MinValue : TimeSpan.Parse(startTime, CultureInfo.InvariantCulture),
EndTime: endTime is null ? TimeSpan.MinValue : TimeSpan.Parse(endTime, CultureInfo.InvariantCulture),
ErrorMessage: unitTestResult.Output?.ErrorInfoString,
Stdout: unitTestResult.Output?.StdOut
));
}
return testResults;
}
public static TestRun? DeserializeTrxFile(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException($"{nameof(filePath)} cannot be null or empty.", nameof(filePath));
}
XmlSerializer serializer = new(typeof(TestRun));
using FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read);
return serializer.Deserialize(fileStream) as TestRun;
}
public static double GetTestRunDurationInMinutes(TestRun testRun)
{
// First try to use the Times element if available
if (testRun?.Times is not null
&& !string.IsNullOrEmpty(testRun.Times.Start)
&& !string.IsNullOrEmpty(testRun.Times.Finish))
{
if (DateTime.TryParse(testRun.Times.Start, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var start)
&& DateTime.TryParse(testRun.Times.Finish, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var finish))
{
return (finish - start).TotalMinutes;
}
}
// Fall back to computing from individual test results if Times element is not available
if (testRun?.Results?.UnitTestResults is null || testRun.Results.UnitTestResults.Count == 0)
{
return 0.0;
}
DateTime? earliestStartTime = null;
DateTime? latestEndTime = null;
foreach (var unitTestResult in testRun.Results.UnitTestResults)
{
if (DateTime.TryParse(unitTestResult.StartTime, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var startTime))
{
if (earliestStartTime is null || startTime < earliestStartTime)
{
earliestStartTime = startTime;
}
}
if (DateTime.TryParse(unitTestResult.EndTime, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var endTime))
{
if (latestEndTime is null || endTime > latestEndTime)
{
latestEndTime = endTime;
}
}
}
if (earliestStartTime is null || latestEndTime is null)
{
return 0.0;
}
return (latestEndTime.Value - earliestStartTime.Value).TotalMinutes;
}
}
[XmlRoot("TestRun", Namespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010")]
| TrxReader |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ViewFeatures/test/ModelExplorerExtensionsTest.cs | {
"start": 234,
"end": 1783
} | public class ____
{
public static TheoryData<object, Type, string> SimpleDisplayTextData
{
get
{
return new TheoryData<object, Type, string>
{
{
new ComplexClass()
{
Prop1 = new Class1 { Prop1 = "Hello" }
},
typeof(ComplexClass),
"Class1"
},
{
new Class1(),
typeof(Class1),
"Class1"
},
{
new ClassWithNoProperties(),
typeof(ClassWithNoProperties),
string.Empty
},
{
null,
typeof(object),
null
},
};
}
}
[Theory]
[MemberData(nameof(SimpleDisplayTextData))]
public void GetSimpleDisplayText_WithoutSimpleDisplayProperty(
object model,
Type modelType,
string expectedResult)
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var modelExplorer = provider.GetModelExplorerForType(modelType, model);
// Act
var result = modelExplorer.GetSimpleDisplayText();
// Assert
Assert.Equal(expectedResult, result);
}
| ModelExplorerExtensionsTest |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.SystemTextJson/GraphQLSerializer.cs | {
"start": 4831,
"end": 6660
} | class ____ the specified settings.
/// <br/><br/>
/// Note that <see cref="JsonSerializerOptions"/> is designed in such a way to reuse created objects.
/// This leads to a massive speedup in subsequent calls to the serializer. The downside is you can't
/// change properties on the options object after you've passed it in a
/// <see cref="JsonSerializer.Serialize(object, Type, JsonSerializerOptions)">Serialize()</see> or
/// <see cref="JsonSerializer.Deserialize(string, Type, JsonSerializerOptions)">Deserialize()</see> call.
/// You'll get the exception: <i><see cref="InvalidOperationException"/>: Serializer options cannot be changed
/// once serialization or deserialization has occurred</i>. To get around this problem we create a copy of
/// options on NET5 platform and above. Passed options object remains unchanged and any changes you
/// make are unobserved.
/// </summary>
/// <param name="serializerOptions">Specifies the JSON serializer settings</param>
/// <param name="errorInfoProvider">Specifies the <see cref="IErrorInfoProvider"/> instance to use to serialize GraphQL errors</param>
public GraphQLSerializer(JsonSerializerOptions serializerOptions, IErrorInfoProvider errorInfoProvider)
{
#if NET5_0_OR_GREATER
// clone serializerOptions
SerializerOptions = new(serializerOptions ?? throw new ArgumentNullException(nameof(serializerOptions)));
#else
// TODO: fix this: it modifies serializerOptions
SerializerOptions = serializerOptions ?? throw new ArgumentNullException(nameof(serializerOptions));
#endif
ConfigureOptions(errorInfoProvider ?? throw new ArgumentNullException(nameof(errorInfoProvider)));
}
/// <summary>
/// Initializes a new instance of the <see cref="GraphQLSerializer"/> | with |
csharp | dotnetcore__CAP | samples/Sample.Dashboard.Auth/MyDashboardAuthenticationHandler.cs | {
"start": 577,
"end": 2291
} | public class ____ : AuthenticationHandler<MyDashboardAuthenticationSchemeOptions>
{
public MyDashboardAuthenticationHandler(IOptionsMonitor<MyDashboardAuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
{
// options.CurrentValue.ForwardChallenge = "";
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var testAuthHeaderPresent = Request.Headers["X-Base-Token"].Contains("xxx");
var authResult = testAuthHeaderPresent ? CreateAuthenticatonTicket() : AuthenticateResult.NoResult();
return Task.FromResult(authResult);
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
//Response.Headers["WWW-Authenticate"] = MyDashboardAuthenticationSchemeDefaults.Scheme;
//return base.HandleChallengeAsync(properties);
// Challenge use OpenId for AddCapWithOpenIdAndCustomAuthorization
return Context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, properties);
}
private AuthenticateResult CreateAuthenticatonTicket()
{
var claims = new[] { new Claim(ClaimTypes.Name, "My Dashboard user") };
var identity = new ClaimsIdentity(claims, MyDashboardAuthenticationSchemeDefaults.Scheme);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, MyDashboardAuthenticationSchemeDefaults.Scheme);
return AuthenticateResult.Success(ticket);
}
}
}
| MyDashboardAuthenticationHandler |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.Web.WebView2.Core/CoreWebView2ProcessFailedReason.cs | {
"start": 265,
"end": 1233
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Unexpected = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Unresponsive = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Terminated = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Crashed = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
LaunchFailed = 4,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
OutOfMemory = 5,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
ProfileDeleted = 6,
#endif
}
#endif
}
| CoreWebView2ProcessFailedReason |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/PivotItem.cs | {
"start": 261,
"end": 866
} | public partial class ____ : global::Microsoft.UI.Xaml.Controls.ContentControl
{
// Skipping already declared property Header
// Skipping already declared property HeaderProperty
// Skipping already declared method Microsoft.UI.Xaml.Controls.PivotItem.PivotItem()
// Forced skipping of method Microsoft.UI.Xaml.Controls.PivotItem.PivotItem()
// Forced skipping of method Microsoft.UI.Xaml.Controls.PivotItem.Header.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.PivotItem.Header.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.PivotItem.HeaderProperty.get
}
}
| PivotItem |
csharp | microsoft__garnet | libs/server/SortedSetAggregateType.cs | {
"start": 223,
"end": 549
} | public enum ____ : byte
{
/// <summary>
/// Sum the values.
/// </summary>
Sum,
/// <summary>
/// Use the minimum value.
/// </summary>
Min,
/// <summary>
/// Use the maximum value.
/// </summary>
Max
}
} | SortedSetAggregateType |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Shipping.UPS/UPSSettings.cs | {
"start": 186,
"end": 2242
} | public class ____ : ISettings
{
/// <summary>
/// Gets or sets the account number
/// </summary>
public string AccountNumber { get; set; }
/// <summary>
/// Gets or sets the client ID
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the client secret
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use sandbox environment
/// </summary>
public bool UseSandbox { get; set; }
/// <summary>
/// Gets or sets an amount of the additional handling charge
/// </summary>
public decimal AdditionalHandlingCharge { get; set; }
/// <summary>
/// Gets or sets UPS customer classification
/// </summary>
public CustomerClassification CustomerClassification { get; set; }
/// <summary>
/// Gets or sets a pickup type
/// </summary>
public PickupType PickupType { get; set; }
/// <summary>
/// Gets or sets packaging type
/// </summary>
public PackagingType PackagingType { get; set; }
/// <summary>
/// Gets or sets offered carrier services
/// </summary>
public string CarrierServicesOffered { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Saturday Delivery enabled
/// </summary>
public bool SaturdayDeliveryEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to insure packages
/// </summary>
public bool InsurePackage { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to pass package dimensions
/// </summary>
public bool PassDimensions { get; set; }
/// <summary>
/// Gets or sets the packing package volume
/// </summary>
public int PackingPackageVolume { get; set; }
/// <summary>
/// Gets or sets packing type
/// </summary>
public PackingType PackingType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to | UPSSettings |
csharp | bitwarden__server | src/Core/NotificationCenter/Commands/MarkNotificationDeletedCommand.cs | {
"start": 413,
"end": 3265
} | public class ____ : IMarkNotificationDeletedCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
private readonly INotificationStatusRepository _notificationStatusRepository;
private readonly IPushNotificationService _pushNotificationService;
public MarkNotificationDeletedCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository,
INotificationStatusRepository notificationStatusRepository,
IPushNotificationService pushNotificationService)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
_notificationStatusRepository = notificationStatusRepository;
_pushNotificationService = pushNotificationService;
}
public async Task MarkDeletedAsync(Guid notificationId)
{
if (!_currentContext.UserId.HasValue)
{
throw new NotFoundException();
}
var notification = await _notificationRepository.GetByIdAsync(notificationId);
if (notification == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notification,
NotificationOperations.Read);
var notificationStatus = await _notificationStatusRepository.GetByNotificationIdAndUserIdAsync(notificationId,
_currentContext.UserId.Value);
if (notificationStatus == null)
{
notificationStatus = new NotificationStatus
{
NotificationId = notificationId,
UserId = _currentContext.UserId.Value,
DeletedDate = DateTime.UtcNow
};
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Create);
var newNotificationStatus = await _notificationStatusRepository.CreateAsync(notificationStatus);
await _pushNotificationService.PushNotificationStatusAsync(notification, newNotificationStatus);
}
else
{
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Update);
notificationStatus.DeletedDate = DateTime.UtcNow;
await _notificationStatusRepository.UpdateAsync(notificationStatus);
await _pushNotificationService.PushNotificationStatusAsync(notification, notificationStatus);
}
}
}
| MarkNotificationDeletedCommand |
csharp | xunit__xunit | src/xunit.v2.tests/Acceptance/Xunit2TheoryAcceptanceTests.cs | {
"start": 24938,
"end": 25445
} | class ____
{
[Theory]
[InlineData("Foo")]
public void TestViaIncompatibleData(int x) { }
}
[Fact]
public void ImplicitlyConvertibleDataPasses()
{
var testMessages = Run<ITestResultMessage>(typeof(ClassWithImplicitlyConvertibleData));
var passed = Assert.Single(testMessages.Cast<ITestPassed>());
Assert.Equal(@"Xunit2TheoryAcceptanceTests+DataConversionTests+ClassWithImplicitlyConvertibleData.TestViaImplicitData(x: 42)", passed.Test.DisplayName);
}
| ClassWithIncompatibleData |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/Jira/CSharp2480Tests.cs | {
"start": 665,
"end": 1782
} | public class ____
{
[Fact(Skip = "No need to run the test, we just need to be sure that the method calls are non-ambiguous")]
public void Test()
{
var collection = new Mock<IMongoCollection<Person>>().Object;
var replace = new Person { Name = "newName" };
collection.FindOneAndReplace(c => c.Name == "Test", replace, new FindOneAndReplaceOptions<Person>());
collection.FindOneAndReplaceAsync(c => c.Name == "Test", replace, new FindOneAndReplaceOptions<Person>());
var updateDefinition = new ObjectUpdateDefinition<Person>(new Person());
collection.FindOneAndUpdate(c => c.Name == "Test", updateDefinition, new FindOneAndUpdateOptions<Person>());
collection.FindOneAndUpdateAsync(c => c.Name == "Test", updateDefinition, new FindOneAndUpdateOptions<Person>());
collection.FindOneAndDelete(c => c.Name == "Test", new FindOneAndDeleteOptions<Person>());
collection.FindOneAndDeleteAsync(c => c.Name == "Test", new FindOneAndDeleteOptions<Person>());
}
| CSharp2480Tests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.