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 | MassTransit__MassTransit | tests/MassTransit.ActiveMqTransport.Tests/StartStop_Specs.cs | {
"start": 316,
"end": 1668
} | public class ____ :
BusTestFixture
{
[Test]
public async Task Should_start_stop_and_start()
{
var bus = MassTransit.Bus.Factory.CreateUsingActiveMq(x =>
{
ConfigureBusDiagnostics(x);
x.ReceiveEndpoint("input_queue", e =>
{
e.Handler<PingMessage>(async context =>
{
await context.RespondAsync(new PongMessage());
});
});
});
await bus.StartAsync(TestCancellationToken);
try
{
await bus.CreateRequestClient<PingMessage>().GetResponse<PongMessage>(new PingMessage());
}
finally
{
await bus.StopAsync(TestCancellationToken);
}
await bus.StartAsync(TestCancellationToken);
try
{
await bus.CreateRequestClient<PingMessage>().GetResponse<PongMessage>(new PingMessage());
}
finally
{
await bus.StopAsync(TestCancellationToken);
}
}
public StartStop_Specs()
: base(new InMemoryTestHarness())
{
}
}
[TestFixture]
[Category("Flaky")]
| StartStop_Specs |
csharp | grandnode__grandnode2 | src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MaxOrderNumberCommandHandlerTests.cs | {
"start": 318,
"end": 894
} | public class ____
{
private MaxOrderNumberCommandHandler _handler;
private IRepository<Order> _repository;
[TestInitialize]
public void Init()
{
_repository = new MongoDBRepositoryTest<Order>();
_handler = new MaxOrderNumberCommandHandler(_repository);
}
[TestMethod]
public async Task HandleTest()
{
//Act
var result = await _handler.Handle(new MaxOrderNumberCommand { OrderNumber = 10 }, CancellationToken.None);
//Assert
Assert.AreEqual(10, result);
}
} | MaxOrderNumberCommandHandlerTests |
csharp | dotnet__efcore | test/EFCore.Tests/Extensions/TypeExtensionsTest.cs | {
"start": 28588,
"end": 28646
} | private class ____<T> : C<T, int>;
| PartiallyClosedGeneric |
csharp | dotnet__machinelearning | src/Microsoft.ML.AutoML/EstimatorExtensions/EstimatorExtensions.cs | {
"start": 4083,
"end": 5319
} | internal class ____ : IEstimatorExtension
{
public IEstimator<ITransformer> CreateInstance(MLContext context, PipelineNode pipelineNode)
{
return CreateInstance(context, pipelineNode.InColumns, pipelineNode.OutColumns);
}
public static SuggestedTransform CreateSuggestedTransform(MLContext context, string[] inColumns, string[] outColumns)
{
var pipelineNode = new PipelineNode(EstimatorName.MissingValueIndicating.ToString(),
PipelineNodeType.Transform, inColumns, outColumns);
var estimator = CreateInstance(context, inColumns, outColumns);
return new SuggestedTransform(pipelineNode, estimator);
}
private static IEstimator<ITransformer> CreateInstance(MLContext context, string[] inColumns, string[] outColumns)
{
var pairs = new InputOutputColumnPair[inColumns.Length];
for (var i = 0; i < inColumns.Length; i++)
{
var pair = new InputOutputColumnPair(outColumns[i], inColumns[i]);
pairs[i] = pair;
}
return context.Transforms.IndicateMissingValues(pairs);
}
}
| MissingValueIndicatingExtension |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs | {
"start": 54402,
"end": 54497
} | public interface ____
{
UniTask OnMouseDragAsync();
}
| IAsyncOnMouseDragHandler |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Transports/IHeaderProvider.cs | {
"start": 214,
"end": 400
} | public interface ____
{
IEnumerable<KeyValuePair<string, object>> GetAll();
bool TryGetHeader(string key, [NotNullWhen(true)] out object? value);
}
}
| IHeaderProvider |
csharp | microsoft__semantic-kernel | dotnet/samples/GettingStartedWithProcesses/Step03/Processes/SingleFoodItemProcess.cs | {
"start": 3629,
"end": 3776
} | public static class ____
{
public const string PrepareSingleOrder = nameof(PrepareSingleOrder);
}
| ProcessFunctions |
csharp | duplicati__duplicati | Duplicati/UnitTest/UtilityTests.cs | {
"start": 1583,
"end": 24528
} | public class ____ : BasicSetupHelper
{
[Test]
[Category("Utility")]
public static void AppendDirSeparator()
{
const string noTrailingSlash = @"/a\b/c";
string hasTrailingSlash = noTrailingSlash + Util.DirectorySeparatorString;
string alternateSeparator = null;
if (String.Equals(Util.DirectorySeparatorString, "/", StringComparison.Ordinal))
{
alternateSeparator = @"\";
}
if (String.Equals(Util.DirectorySeparatorString, @"\", StringComparison.Ordinal))
{
alternateSeparator = "/";
}
Assert.AreEqual(hasTrailingSlash, Util.AppendDirSeparator(noTrailingSlash));
Assert.AreEqual(hasTrailingSlash, Util.AppendDirSeparator(hasTrailingSlash));
Assert.AreEqual(hasTrailingSlash, Util.AppendDirSeparator(noTrailingSlash), Util.DirectorySeparatorString);
Assert.AreEqual(hasTrailingSlash, Util.AppendDirSeparator(hasTrailingSlash), Util.DirectorySeparatorString);
Assert.AreEqual(noTrailingSlash + alternateSeparator, Util.AppendDirSeparator(noTrailingSlash, alternateSeparator));
Assert.AreEqual(noTrailingSlash + alternateSeparator, Util.AppendDirSeparator(noTrailingSlash + alternateSeparator, alternateSeparator));
Assert.AreEqual(hasTrailingSlash + alternateSeparator, Util.AppendDirSeparator(hasTrailingSlash, alternateSeparator));
}
[Test]
[Category("Utility")]
[TestCase("da-DK")]
[TestCase("en-US")]
[TestCase("hu-HU")]
[TestCase("tr-TR")]
public static void FilenameStringComparison(string cultureName)
{
Action<string, string> checkStringComparison = (x, y) => Assert.IsFalse(String.Equals(x, y, Utility.ClientFilenameStringComparison));
Action<string, string> checkStringComparer = (x, y) => Assert.IsFalse(new HashSet<string>(new[] { x }).Contains(y, Utility.ClientFilenameStringComparer));
CultureInfo originalCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo(cultureName, false);
// These are equivalent with respect to hu-HU, but different with respect to en-US.
string ddzs = "ddzs";
string dzsdzs = "dzsdzs";
checkStringComparison(ddzs, dzsdzs);
checkStringComparer(ddzs, dzsdzs);
// Many cultures treat the following as equivalent.
string eAcuteOneCharacter = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(new byte[] { 233 }); // 'é' as one character (ALT+0233).
string eAcuteTwoCharacters = "\u0065\u0301"; // 'e', combined with an acute accent (U+301).
checkStringComparison(eAcuteOneCharacter, eAcuteTwoCharacters);
checkStringComparer(eAcuteOneCharacter, eAcuteTwoCharacters);
// These are equivalent with respect to en-US, but different with respect to da-DK.
string aDiaeresisOneCharacter = "\u00C4"; // 'A' with a diaeresis.
string aDiaeresisTwoCharacters = "\u0041\u0308"; // 'A', combined with a diaeresis.
checkStringComparison(aDiaeresisOneCharacter, aDiaeresisTwoCharacters);
checkStringComparer(aDiaeresisOneCharacter, aDiaeresisTwoCharacters);
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
}
}
[Test]
[Category("Utility")]
public static void ReadLimitLengthStreamWithGrowingFile()
{
var growingFilename = Path.GetTempFileName();
long fixedGrowingStreamLength, limitStreamLength, nextGrowingStreamLength;
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Task task = TestUtils.GrowingFile(growingFilename, tokenSource.Token);
Thread.Sleep(100);
using (FileStream growingStream = new FileStream(growingFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Thread.Sleep(100);
fixedGrowingStreamLength = growingStream.Length;
Thread.Sleep(100);
using (var limitStream = new ReadLimitLengthStream(growingStream, fixedGrowingStreamLength))
{
Thread.Sleep(100);
nextGrowingStreamLength = growingStream.Length;
limitStreamLength = limitStream.Length;
}
}
}
Console.WriteLine($"fixedGrowingStreamLength:{fixedGrowingStreamLength} limitStreamLength:{limitStreamLength} nextGrowingStreamLength:{nextGrowingStreamLength}");
Assert.IsTrue(fixedGrowingStreamLength > 0);
Assert.AreEqual(fixedGrowingStreamLength, limitStreamLength);
Assert.IsTrue(limitStreamLength < nextGrowingStreamLength);
}
[Test]
[Category("Utility")]
public static void ReadLimitLengthStream()
{
Action<IEnumerable<int>, IEnumerable<byte>> assertArray = (expected, actual) =>
{
List<int> expectedList = expected.ToList();
List<byte> actualList = actual.ToList();
Assert.AreEqual(expectedList.Count, actualList.Count, "Count");
for (int i = 0; i < expectedList.Count; i++)
{
Assert.AreEqual((byte)expectedList[i], actualList[i], "Index {0}", i);
}
};
byte[] readBuffer = new byte[10];
Action<Stream, int, int> testSeek = (stream, position, readByte) =>
{
stream.Position = position;
Assert.AreEqual(position, stream.Position);
Assert.AreEqual(readByte, stream.ReadByte());
Assert.AreEqual(position, stream.Seek(position, SeekOrigin.Begin));
Assert.AreEqual(position, stream.Position);
Array.Clear(readBuffer, 0, 10);
Assert.AreEqual(readByte >= 0 ? 1 : 0, stream.Read(readBuffer, 1, 1), "Read count");
if (readByte >= 0)
{
// Make sure nothing was read before or after the offset byte given as well.
Assert.AreEqual(readBuffer[0], 0);
Assert.AreEqual(readBuffer[1], readByte);
Assert.AreEqual(readBuffer[2], 0);
}
else
{
// Make sure nothing was read
Assert.AreEqual(readBuffer[0], 0);
Assert.AreEqual(readBuffer[1], 0);
Assert.AreEqual(readBuffer[2], 0);
}
Assert.AreEqual(position, stream.Seek(position - stream.Length, SeekOrigin.End));
Assert.AreEqual(position, stream.Position);
Assert.AreEqual(readByte, stream.ReadByte());
};
// Base stream is a sequence from 0..9
using (MemoryStream baseStream = new MemoryStream(Enumerable.Range(0, 10).Select(i => (byte)i).ToArray()))
{
using (ReadLimitLengthStream stream = new ReadLimitLengthStream(baseStream, 5))
{
Assert.AreEqual(5, stream.Length);
// Test reading past array bounds
Assert.AreEqual(5, stream.Read(readBuffer, 0, 10), "Read count");
assertArray(Enumerable.Range(0, 5), readBuffer.Take(5));
// Set the position directly and read a shorter range
stream.Position = 2;
Assert.AreEqual(2, stream.ReadAsync(readBuffer, 0, 2).Await(), "Read count");
assertArray(Enumerable.Range(2, 2), readBuffer.Take(2));
}
// Make sure the stream will be seeked if the start does not match the current position.
baseStream.Position = 0;
using (ReadLimitLengthStream stream = new ReadLimitLengthStream(baseStream, 2, 4))
{
// Make sure the position is updated when the stream is created
Assert.AreEqual(0, stream.Position);
// Test basic read
Assert.AreEqual(4, stream.Read(readBuffer, 0, 4), "Read count");
assertArray(Enumerable.Range(2, 4), readBuffer.Take(4));
// Test CopyTo
using (MemoryStream destination = new MemoryStream())
{
stream.Position = 0;
stream.CopyTo(destination);
assertArray(Enumerable.Range(2, 4), destination.ToArray());
}
// Test CopyToAsync
using (MemoryStream destination = new MemoryStream())
{
stream.Position = 0;
stream.CopyToAsync(destination).Await();
assertArray(Enumerable.Range(2, 4), destination.ToArray());
}
// Test seeking
testSeek(stream, 0, 2);
testSeek(stream, 1, 3);
testSeek(stream, 2, 4);
testSeek(stream, 3, 5);
testSeek(stream, 4, -1);
// Test seeking from current
stream.Position = 0;
Assert.AreEqual(2, stream.Seek(2, SeekOrigin.Current));
Assert.AreEqual(2, stream.Position);
// Test clamping of position
stream.Position = -2;
Assert.AreEqual(0, stream.Position);
Assert.AreEqual(2, baseStream.Position);
stream.Position = 9;
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(6, baseStream.Position);
// Make sure changing the base stream still shows clamped positions
baseStream.Position = 0;
Assert.AreEqual(0, stream.Position);
baseStream.Position = 4;
Assert.AreEqual(2, stream.Position);
baseStream.Position = 10;
Assert.AreEqual(4, stream.Position);
// Reading when the baseStream is positioned before the start of the limit
// should still be possible, and should seek to return the correct values.
baseStream.Position = 0;
Assert.AreEqual(0, stream.Position);
Assert.AreEqual(2, stream.ReadByte());
}
// Check a stream with length 0
baseStream.Position = 0;
using (ReadLimitLengthStream stream = new ReadLimitLengthStream(baseStream, 2, 0))
{
// Make sure the position is updated when the stream is created
Assert.AreEqual(0, stream.Position);
// Test basic read
Assert.AreEqual(0, stream.Read(readBuffer, 0, 4), "Read count");
// Test seeking
testSeek(stream, 0, -1);
testSeek(stream, 0, -1);
// Test seeking from current
stream.Position = 0;
Assert.AreEqual(0, stream.Seek(2, SeekOrigin.Current));
Assert.AreEqual(0, stream.Position);
// Test clamping of position
stream.Position = -2;
Assert.AreEqual(0, stream.Position);
Assert.AreEqual(2, baseStream.Position);
stream.Position = 9;
Assert.AreEqual(0, stream.Position);
Assert.AreEqual(2, baseStream.Position);
// Make sure changing the base stream still shows clamped positions
baseStream.Position = 0;
Assert.AreEqual(0, stream.Position);
baseStream.Position = 4;
Assert.AreEqual(0, stream.Position);
baseStream.Position = 10;
Assert.AreEqual(0, stream.Position);
}
}
}
[Test]
[Category("Utility")]
public static void ForceStreamRead()
{
byte[] source = { 0x10, 0x20, 0x30, 0x40, 0x50 };
// Ensure that ReadOneByteStream returns one byte at a time.
byte[] buffer = new byte[source.Length];
ReadOneByteStream stream = new ReadOneByteStream(source);
Assert.AreEqual(1, stream.Read(buffer, 0, buffer.Length));
Assert.AreEqual(source.First(), buffer.First());
foreach (byte value in buffer.Skip(1))
{
Assert.AreEqual(default(byte), value);
}
// Buffer is larger than the length of the stream.
buffer = new byte[source.Length + 1];
int bytesRead = Utility.ForceStreamRead(new ReadOneByteStream(source), buffer, source.Length);
Assert.AreEqual(source.Length, bytesRead);
CollectionAssert.AreEqual(source, buffer.Take(source.Length));
Assert.AreEqual(default(byte), buffer.Last());
// Maximum number of bytes is larger than the length of the stream.
buffer = new byte[source.Length + 1];
bytesRead = Utility.ForceStreamRead(new ReadOneByteStream(source), buffer, source.Length + 1);
Assert.AreEqual(source.Length, bytesRead);
CollectionAssert.AreEqual(source, buffer.Take(bytesRead));
Assert.AreEqual(default(byte), buffer.Last());
// Maximum number of bytes is smaller than the length of the stream.
buffer = new byte[source.Length];
bytesRead = Utility.ForceStreamRead(new ReadOneByteStream(source), buffer, source.Length - 1);
Assert.AreEqual(source.Length - 1, bytesRead);
CollectionAssert.AreEqual(source.Take(bytesRead), buffer.Take(bytesRead));
Assert.AreEqual(default(byte), buffer.Last());
// Buffer is smaller than the length of the stream.
Assert.Throws<ArgumentException>(() => Utility.ForceStreamRead(new ReadOneByteStream(source), new byte[source.Length - 1], source.Length));
}
[Test]
[Category("Utility")]
public void GetUniqueItems()
{
string[] collection = { "A", "a", "A", "b", "c", "c" };
string[] uniqueItems = { "A", "a", "b", "c" };
string[] duplicateItems = { "A", "c" };
// Test with default comparer.
var actualUniqueItems = Utility.GetUniqueItems(collection, out var actualDuplicateItems);
CollectionAssert.AreEquivalent(uniqueItems, actualUniqueItems);
CollectionAssert.AreEquivalent(duplicateItems, actualDuplicateItems);
// Test with custom comparer.
IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase;
uniqueItems = new string[] { "a", "b", "c" };
duplicateItems = new string[] { "a", "c" };
actualDuplicateItems = null;
actualUniqueItems = Utility.GetUniqueItems(collection, comparer, out actualDuplicateItems);
Assert.That(actualUniqueItems, Is.EquivalentTo(uniqueItems).Using(comparer));
Assert.That(actualDuplicateItems, Is.EquivalentTo(duplicateItems).Using(comparer));
// Test with empty collection.
actualDuplicateItems = null;
actualUniqueItems = Utility.GetUniqueItems(new string[0], out actualDuplicateItems);
Assert.IsNotNull(actualUniqueItems);
Assert.IsNotNull(actualDuplicateItems);
}
[Test]
[Category("Utility")]
public void NormalizeDateTime()
{
DateTime baseDateTime = new DateTime(2000, 1, 2, 3, 4, 5);
DateTime baseDateTimeUTC = baseDateTime.ToUniversalTime();
Assert.AreEqual(baseDateTimeUTC, Utility.NormalizeDateTime(baseDateTime.AddMilliseconds(1)));
Assert.AreEqual(baseDateTimeUTC, Utility.NormalizeDateTime(baseDateTime.AddMilliseconds(500)));
Assert.AreEqual(baseDateTimeUTC, Utility.NormalizeDateTime(baseDateTime.AddMilliseconds(999)));
Assert.AreEqual(baseDateTimeUTC.AddSeconds(-1), Utility.NormalizeDateTime(baseDateTime.AddMilliseconds(-1)));
Assert.AreEqual(baseDateTimeUTC.AddSeconds(1), Utility.NormalizeDateTime(baseDateTime.AddSeconds(1.9)));
}
[Test]
[Category("Utility")]
public void NormalizeDateTimeToEpochSeconds()
{
DateTime baseDateTime = new DateTime(2000, 1, 2, 3, 4, 5);
long epochSeconds = (long)(baseDateTime.ToUniversalTime() - Utility.EPOCH).TotalSeconds;
Assert.AreEqual(epochSeconds, Utility.NormalizeDateTimeToEpochSeconds(baseDateTime.AddMilliseconds(1)));
Assert.AreEqual(epochSeconds, Utility.NormalizeDateTimeToEpochSeconds(baseDateTime.AddMilliseconds(500)));
Assert.AreEqual(epochSeconds, Utility.NormalizeDateTimeToEpochSeconds(baseDateTime.AddMilliseconds(999)));
Assert.AreEqual(epochSeconds - 1, Utility.NormalizeDateTimeToEpochSeconds(baseDateTime.AddMilliseconds(-1)));
Assert.AreEqual(epochSeconds + 1, Utility.NormalizeDateTimeToEpochSeconds(baseDateTime.AddSeconds(1.9)));
}
[Test]
[Category("Utility")]
public void ParseBool()
{
string[] expectTrue = { "1", "on", "true", "yes" };
string[] expectFalse = { "0", "off", "false", "no" };
string[] expectDefault = { null, "", "maybe" };
Func<bool> returnsTrue = () => true;
Func<bool> returnsFalse = () => false;
foreach (string value in expectTrue)
{
string message = $"{value} should be parsed to true.";
Assert.IsTrue(Utility.ParseBool(value, false), message);
Assert.IsTrue(Utility.ParseBool(value.ToUpper(CultureInfo.InvariantCulture), false), message);
Assert.IsTrue(Utility.ParseBool($" {value} ", false), message);
}
foreach (string value in expectFalse)
{
string message = $"{value} should be parsed to false.";
Assert.IsFalse(Utility.ParseBool(value, true), message);
Assert.IsFalse(Utility.ParseBool(value.ToUpper(CultureInfo.InvariantCulture), true), message);
Assert.IsFalse(Utility.ParseBool($" {value} ", true), message);
}
foreach (string value in expectDefault)
{
Assert.IsTrue(Utility.ParseBool(value, true));
Assert.IsTrue(Utility.ParseBool(value, returnsTrue));
Assert.IsFalse(Utility.ParseBool(value, false));
Assert.IsFalse(Utility.ParseBool(value, returnsFalse));
}
}
[Test]
[Category("Utility")]
public static void ThrottledStreamRead()
{
byte[] sourceBuffer = [0x10, 0x20, 0x30, 0x40, 0x50];
var destinationBuffer = new byte[sourceBuffer.Length + 1];
const int offset = 1;
const int bytesToRead = 3;
using (var baseStream = new MemoryStream(sourceBuffer))
{
const int readSpeed = 1;
const int writeSpeed = 1;
var throttledStream = new ThrottleEnabledStream(baseStream, readSpeed, writeSpeed);
var bytesRead = throttledStream.Read(destinationBuffer, offset, bytesToRead);
Assert.AreEqual(bytesToRead, bytesRead);
for (var k = 0; k < destinationBuffer.Length; k++)
{
if (offset <= k && k < offset + bytesToRead)
{
Assert.AreEqual(sourceBuffer[k - offset], destinationBuffer[k]);
}
else
{
Assert.AreEqual(default(byte), destinationBuffer[k]);
}
}
}
}
[Test]
[Category("Utility")]
public static void ThrottledStreamWrite()
{
byte[] initialBuffer = [0x10, 0x20, 0x30, 0x40, 0x50];
byte[] source = [0x60, 0x70, 0x80, 0x90];
const int offset = 1;
const int bytesToWrite = 3;
using (var baseStream = new MemoryStream(initialBuffer))
{
const int readSpeed = 1;
const int writeSpeed = 1;
var throttledStream = new ThrottleEnabledStream(baseStream, readSpeed, writeSpeed);
throttledStream.Write(source, offset, bytesToWrite);
byte[] result = baseStream.ToArray();
for (int k = 0; k < result.Length; k++)
{
if (k < bytesToWrite)
{
Assert.AreEqual(source[offset + k], result[k]);
}
else
{
Assert.AreEqual(initialBuffer[k], result[k]);
}
}
}
}
[Test]
[Category("Utility")]
public static void RetryDelayNoExponentialBackoff()
{
// test boundary values
TimeSpan baseDelay = TimeSpan.FromSeconds(1);
int[] testValues = { 1, 2, 11, 12, int.MaxValue };
double[] expect = { 1, 1, 1, 1, 1 };
for (int i = 0; i < testValues.Length; i++)
Assert.AreEqual(TimeSpan.FromSeconds(expect[i]), Utility.GetRetryDelay(baseDelay, testValues[i], false));
}
[Test]
[Category("Utility")]
public static void RetryDelayExponentialBackoff()
{
// test boundary values
TimeSpan baseDelay = TimeSpan.FromSeconds(1);
int[] testValues = { 1, 2, 11, 12, int.MaxValue };
double[] expect = { 1, 2, 1024, 1024, 1024 };
for (int i = 0; i < testValues.Length; i++)
Assert.AreEqual(TimeSpan.FromSeconds(expect[i]), Utility.GetRetryDelay(baseDelay, testValues[i], true));
}
}
/// <summary>
/// Mimic a Stream that can only read one byte at a time.
/// </summary>
| UtilityTests |
csharp | xunit__xunit | src/xunit.v3.core.tests/Acceptance/Xunit3TheoryAcceptanceTests.cs | {
"start": 102490,
"end": 102845
} | public abstract class ____
{
[Theory]
#pragma warning disable xUnit1015 // MemberData must reference an existing member
[MemberData(nameof(SubClassWithTestData.TestData))]
#pragma warning restore xUnit1015 // MemberData must reference an existing member
public void Test(int x)
{
Assert.Equal(42, x);
}
}
| BaseClassWithTestWithoutData |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/Metadata/LightJson/JsonObject.cs | {
"start": 5357,
"end": 5965
} | private class ____
{
private JsonObject jsonObject;
public JsonObjectDebugView(JsonObject jsonObject)
{
this.jsonObject = jsonObject;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair[] Keys {
get {
var keys = new KeyValuePair[this.jsonObject.Count];
var i = 0;
foreach (var property in this.jsonObject)
{
keys[i] = new KeyValuePair(property.Key, property.Value);
i += 1;
}
return keys;
}
}
[DebuggerDisplay("{value.ToString(),nq}", Name = "{key}", Type = "JsonValue({Type})")]
| JsonObjectDebugView |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Controls/ResourceProvider.cs | {
"start": 196,
"end": 2623
} | public abstract class ____ : AvaloniaObject, IResourceProvider
{
private IResourceHost? _owner;
public ResourceProvider()
{
}
public ResourceProvider(IResourceHost owner)
{
_owner = owner;
}
/// <inheritdoc/>
public abstract bool HasResources { get; }
/// <inheritdoc/>
public abstract bool TryGetResource(object key, ThemeVariant? theme, out object? value);
/// <inheritdoc/>
public IResourceHost? Owner
{
get => _owner;
private set
{
if (_owner != value)
{
_owner = value;
OwnerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <inheritdoc/>
public event EventHandler? OwnerChanged;
protected void RaiseResourcesChanged()
{
Owner?.NotifyHostedResourcesChanged(ResourcesChangedToken.Create());
}
/// <summary>
/// Handles when owner was added.
/// Base method implementation raises <see cref="IResourceHost.NotifyHostedResourcesChanged"/>, if this provider has any resources.
/// </summary>
/// <param name="owner">New owner.</param>
protected virtual void OnAddOwner(IResourceHost owner)
{
if (HasResources)
{
owner.NotifyHostedResourcesChanged(ResourcesChangedToken.Create());
}
}
/// <summary>
/// Handles when owner was removed.
/// Base method implementation raises <see cref="IResourceHost.NotifyHostedResourcesChanged"/>, if this provider has any resources.
/// </summary>
/// <param name="owner">Old owner.</param>
protected virtual void OnRemoveOwner(IResourceHost owner)
{
if (HasResources)
{
owner.NotifyHostedResourcesChanged(ResourcesChangedToken.Create());
}
}
void IResourceProvider.AddOwner(IResourceHost owner)
{
owner = owner ?? throw new ArgumentNullException(nameof(owner));
if (Owner != null)
{
throw new InvalidOperationException("The ResourceDictionary already has a parent.");
}
Owner = owner;
OnAddOwner(owner);
}
void IResourceProvider.RemoveOwner(IResourceHost owner)
{
owner = owner ?? throw new ArgumentNullException(nameof(owner));
if (Owner == owner)
{
Owner = null;
OnRemoveOwner(owner);
}
}
}
| ResourceProvider |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Shim/Numbers.cs | {
"start": 16353,
"end": 18489
} | internal static class ____
{
#if NETSTANDARD2_1
public static bool TryParse(ReadOnlySpan<char> s, out System.Numerics.BigInteger result)
=> System.Numerics.BigInteger.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result);
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result)
=> System.Numerics.BigInteger.TryParse(s, style, provider, out result);
public static System.Numerics.BigInteger Parse(ReadOnlySpan<char> s)
=> System.Numerics.BigInteger.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
public static System.Numerics.BigInteger Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider)
=> System.Numerics.BigInteger.Parse(s, style, provider);
#else
//TODO: copy from .NET Core sources
public static bool TryParse(ReadOnlySpan<char> s, out System.Numerics.BigInteger result)
=> System.Numerics.BigInteger.TryParse(s.ToString(), NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result);
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result)
=> System.Numerics.BigInteger.TryParse(s.ToString(), style, provider, out result);
public static System.Numerics.BigInteger Parse(ReadOnlySpan<char> s)
=> System.Numerics.BigInteger.Parse(s.ToString(), NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
public static System.Numerics.BigInteger Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider)
=> System.Numerics.BigInteger.Parse(s.ToString(), style, provider);
#endif
}
/// <summary>
/// Adapter to unify usages of double.[Parse|TryParse](ReadOnlySpan) for netstandard2.0 and netstandard2.1
/// </summary>
| BigInt |
csharp | dotnet__maui | src/Controls/samples/Controls.Sample/Pages/PlatformSpecifics/Android/AndroidWebViewZoomPage.xaml.cs | {
"start": 73,
"end": 207
} | public partial class ____ : ContentPage
{
public AndroidWebViewZoomPage()
{
InitializeComponent();
}
}
}
| AndroidWebViewZoomPage |
csharp | abpframework__abp | framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutoFac_OnActivated_Tests.cs | {
"start": 188,
"end": 968
} | public class ____ : Autofac_Interception_Test
{
protected override Task AfterAddApplicationAsync(IServiceCollection services)
{
var serviceDescriptor = ServiceDescriptor.Transient<MyServer, MyServer>();
services.Add(serviceDescriptor);
services.OnActivated(serviceDescriptor, x =>
{
x.Instance.As<MyServer>().Name += "1";
});
services.OnActivated(serviceDescriptor, x =>
{
x.Instance.As<MyServer>().Name += "2";
});
return base.AfterAddApplicationAsync(services);
}
[Fact]
public void Should_Call_OnActivated()
{
var server = ServiceProvider.GetRequiredService<MyServer>();
server.Name.ShouldBe("MyServer12");
}
| AutoFac_OnActivated_Tests |
csharp | unoplatform__uno | src/Uno.UI.Runtime.Skia.WebAssembly.Browser/Builder/WebAssemblyHostBuilder.cs | {
"start": 128,
"end": 414
} | internal partial class ____ : IPlatformHostBuilder
{
public WebAssemblyHostBuilder()
{
}
public bool IsSupported => true;
public UnoPlatformHost Create(Func<Microsoft.UI.Xaml.Application> appBuilder, Type appType)
=> new WebAssemblyBrowserHost(appBuilder);
}
| WebAssemblyHostBuilder |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Server.Tests/ProxyFeatureTests.cs | {
"start": 5020,
"end": 9490
} | public partial class ____
: IReturn<EchoTypes>
{
public virtual byte Byte { get; set; }
public virtual short Short { get; set; }
public virtual int Int { get; set; }
public virtual long Long { get; set; }
public virtual ushort UShort { get; set; }
public virtual uint UInt { get; set; }
public virtual ulong ULong { get; set; }
public virtual float Float { get; set; }
public virtual double Double { get; set; }
public virtual decimal Decimal { get; set; }
public virtual string String { get; set; }
public virtual DateTime DateTime { get; set; }
public virtual TimeSpan TimeSpan { get; set; }
public virtual DateTimeOffset DateTimeOffset { get; set; }
public virtual Guid Guid { get; set; }
public virtual Char Char { get; set; }
}
[Test]
public void Can_proxy_to_test_servicestack()
{
var client = new JsonServiceClient(ListeningOn.CombineWith("test"));
var request = new EchoTypes
{
Byte = 1,
Short = 2,
Int = 3,
Long = 4,
Float = 1.1f,
String = "foo"
};
var response = client.Post(request);
Assert.That(response.Byte, Is.EqualTo(1));
Assert.That(response.Short, Is.EqualTo(2));
Assert.That(response.Int, Is.EqualTo(3));
Assert.That(response.Long, Is.EqualTo(4));
Assert.That(response.Float, Is.EqualTo(1.1f));
Assert.That(response.String, Is.EqualTo("foo"));
}
[Test]
public async Task Can_proxy_to_test_servicestack_Async()
{
var client = new JsonHttpClient(ListeningOn.CombineWith("test"));
var request = new EchoTypes
{
Byte = 1,
Short = 2,
Int = 3,
Long = 4,
Float = 1.1f,
String = "foo"
};
var response = await client.PostAsync(request);
Assert.That(response.Byte, Is.EqualTo(1));
Assert.That(response.Short, Is.EqualTo(2));
Assert.That(response.Int, Is.EqualTo(3));
Assert.That(response.Long, Is.EqualTo(4));
Assert.That(response.Float, Is.EqualTo(1.1f));
Assert.That(response.String, Is.EqualTo("foo"));
}
[Test]
public void Can_TransformRequest_when_proxying_to_test()
{
var request = new EchoTypes
{
Byte = 1,
Short = 2,
Int = 3,
Long = 4,
Float = 1.1f,
String = "foo"
};
var url = ListeningOn.CombineWith("test")
.CombineWith("/echo/types")
.AddQueryParam("reqReplace", "foo,bar");
var response = url.PostJsonToUrl(request)
.FromJson<EchoTypes>();
Assert.That(response.Byte, Is.EqualTo(1));
Assert.That(response.Short, Is.EqualTo(2));
Assert.That(response.Int, Is.EqualTo(3));
Assert.That(response.Long, Is.EqualTo(4));
Assert.That(response.Float, Is.EqualTo(1.1f));
Assert.That(response.String, Is.EqualTo("bar"));
}
[Test]
public void Can_TransformResponse_when_proxying_to_test()
{
var request = new EchoTypes
{
Byte = 1,
Short = 2,
Int = 3,
Long = 4,
Float = 1.1f,
String = "foo"
};
var url = ListeningOn.CombineWith("test")
.CombineWith("/echo/types")
.AddQueryParam("resReplace", "foo,bar");
var response = url.PostJsonToUrl(request)
.FromJson<EchoTypes>();
Assert.That(response.Byte, Is.EqualTo(1));
Assert.That(response.Short, Is.EqualTo(2));
Assert.That(response.Int, Is.EqualTo(3));
Assert.That(response.Long, Is.EqualTo(4));
Assert.That(response.Float, Is.EqualTo(1.1f));
Assert.That(response.String, Is.EqualTo("bar"));
}
[Route("/technology/{Slug}")]
| EchoTypes |
csharp | smartstore__Smartstore | src/Smartstore.Web/Areas/Admin/Models/Search/SearchSettingsModel.cs | {
"start": 3257,
"end": 4136
} | public partial class ____ : SettingModelValidator<SearchSettingsModel, SearchSettings>
{
const int MaxInstantSearchItems = 16;
public SearchSettingValidator(Localizer T)
{
RuleFor(x => x.InstantSearchNumberOfProducts)
.Must(x => x >= 1 && x <= MaxInstantSearchItems)
//.When(x => (StoreScope == 0 && x.InstantSearchEnabled) || (StoreScope > 0 && IsOverrideChecked("InstantSearchNumberOfProducts")))
.WhenSettingOverriden((m, x) => m.InstantSearchEnabled)
.WithMessage(T("Admin.Validation.ValueRange", 1, MaxInstantSearchItems));
RuleFor(x => x.InstantSearchTermMinLength).GreaterThan(0);
RuleFor(x => x.FilterMinHitCount).GreaterThanOrEqualTo(0);
RuleFor(x => x.FilterMaxChoicesCount).GreaterThan(0);
}
}
}
| SearchSettingValidator |
csharp | neuecc__MessagePack-CSharp | tests/MessagePack.Tests/UnionResolverTest.cs | {
"start": 14191,
"end": 14648
} | public class ____ : AWithStringSubType
{
[IgnoreMember]
public string Type => "C";
[Key(0)]
public string Name { get; set; }
[Key(1)]
public virtual int Val { get; set; }
[Key(2)]
public virtual int Valer { get; set; }
}
[Union(0, "ComplexdUnion.B2WithStringSubType, MessagePack.Tests")]
[Union(1, "ComplexdUnion.C2WithStringSubType, MessagePack.Tests")]
| CWithStringSubType |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/StoreGeneratedFixupTestBase.cs | {
"start": 151631,
"end": 151877
} | protected class ____
{
public int Id1 { get; set; }
public Guid Id2 { get; set; }
public int ParentId1 { get; set; }
public Guid ParentId2 { get; set; }
public Parent Parent { get; set; }
}
| Child |
csharp | npgsql__npgsql | src/Npgsql/NameTranslation/INpgsqlNameTranslator.cs | {
"start": 184,
"end": 226
} | enum ____ composite types.
/// </summary>
| and |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/Gh7559.xaml.cs | {
"start": 507,
"end": 884
} | public abstract class ____<T>
{
public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(T), typeof(Gh7559Generic<T>), default(T));
public static T GetIcon(BindableObject bindable) => (T)bindable.GetValue(IconProperty);
public static void SetIcon(BindableObject bindable, T value) => bindable.SetValue(IconProperty, value);
}
| Gh7559Generic |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core/Services/Processing/Emitting/EmittedEvents/EmittedLinkTo.cs | {
"start": 375,
"end": 1687
} | public class ____ : EmittedEvent {
private readonly string _targetStreamId;
private long? _eventNumber;
public EmittedLinkTo(
string streamId, Guid eventId,
string targetStreamId, CheckpointTag causedByTag, CheckpointTag expectedTag,
Action<long> onCommitted = null)
: base(streamId, eventId, "$>", causedByTag, expectedTag, onCommitted) {
_targetStreamId = targetStreamId;
}
public EmittedLinkTo(
string streamId, Guid eventId,
string targetStreamId, int targetEventNumber, CheckpointTag causedByTag, CheckpointTag expectedTag,
string originalStreamId = null)
: base(streamId, eventId, "$>", causedByTag, expectedTag, null) {
_eventNumber = targetEventNumber;
_targetStreamId = targetStreamId;
}
public override string Data {
get {
if (!IsReady())
throw new InvalidOperationException("Link target has not been yet committed");
return
_eventNumber.Value.ToString(CultureInfo.InvariantCulture) + "@" + _targetStreamId;
}
}
public override bool IsJson {
get { return false; }
}
public override bool IsReady() {
return _eventNumber != null;
}
public void SetTargetEventNumber(long eventNumber) {
if (_eventNumber != null)
throw new InvalidOperationException("Target event number has been already set");
_eventNumber = eventNumber;
}
}
| EmittedLinkTo |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1839175,
"end": 1839544
} | public partial interface ____ : IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes, IDirectiveLocationAdded
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_DirectiveLocationAdded |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_Layout.cs | {
"start": 8189,
"end": 10323
} | public class ____ : ScopedTestBase
{
[Fact]
public void Measure_Rounds_Padding()
{
var target = new ContentPresenter
{
Padding = new Thickness(1),
Content = new Canvas
{
Width = 101,
Height = 101,
}
};
var root = CreatedRoot(1.5, target);
root.LayoutManager.ExecuteInitialLayoutPass();
// - 1 pixel padding is rounded up to 1.3333; for both sides it is 2.6666
// - Size of 101 gets rounded up to 101.3333
// - Desired size = 101.3333 + 2.6666 = 104
Assert.Equal(new Size(104, 104), target.DesiredSize);
}
[Fact]
public void Measure_Rounds_BorderThickness()
{
var target = new ContentPresenter
{
BorderThickness = new Thickness(1),
Content = new Canvas
{
Width = 101,
Height = 101,
}
};
var root = CreatedRoot(1.5, target);
root.LayoutManager.ExecuteInitialLayoutPass();
// - 1 pixel border thickness is rounded up to 1.3333; for both sides it is 2.6666
// - Size of 101 gets rounded up to 101.3333
// - Desired size = 101.3333 + 2.6666 = 104
Assert.Equal(new Size(104, 104), target.DesiredSize);
}
private static TestRoot CreatedRoot(
double scaling,
Control child,
Size? constraint = null)
{
return new TestRoot
{
LayoutScaling = scaling,
UseLayoutRounding = true,
Child = child,
ClientSize = constraint ?? new Size(1000, 1000),
};
}
}
}
}
| UseLayoutRounding |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AsyncTaskTests.cs | {
"start": 5138,
"end": 5375
} | public class ____ : AsyncTaskTests
{
protected override IServiceClient CreateServiceClient()
{
return new JsonHttpClient(Config.ListeningOn);
}
}
[TestFixture]
| JsonHttpClientAsyncTaskTests |
csharp | dotnet__efcore | test/EFCore.Tests/ChangeTracking/ValueComparerTest.cs | {
"start": 758,
"end": 1552
} | private class ____ : DbContext
{
protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString());
protected internal override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Foo>().Property(e => e.Bar).HasConversion<string>(new FakeValueComparer());
}
[ConditionalFact]
public void Throws_for_provider_comparer_with_wrong_type()
{
using var context = new InvalidProviderDbContext();
Assert.Equal(
CoreStrings.ComparerPropertyMismatch("double", nameof(Foo), nameof(Foo.Bar), "string"),
Assert.Throws<InvalidOperationException>(() => context.Model).Message);
}
| InvalidDbContext |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ScriptTests/PageBasedRoutingTests.cs | {
"start": 208,
"end": 6990
} | class ____ : AppSelfHostBase
{
public AppHost()
: base(nameof(SharpPageTests), typeof(SharpPagesService).Assembly) { }
public override void Configure(Container container)
{
Plugins.Add(new SharpPagesFeature());
}
static readonly Dictionary<string,string> HtmlFiles = new Dictionary<string, string>
{
{ "_layout.html", "<html><body>{{ page }}</body></html>" },
{ "_slug/index.html", "_slug/index.html slug: {{slug}}" },
{ "_slug/_category.html", "_slug/_category.html slug: {{slug}}, category: {{category}}" },
{ "comments/_postid/_id.html", "comments/_postid/_id.html postid: {{postid}}, id: {{id}}" },
{ "favorites/index.html", "favorites/index.html" },
{ "login/_provider.html", "login/_provider.html provider: {{provider}}" },
{ "organizations/_slug/index.html", "organizations/_slug/index.html slug: {{slug}}" },
{ "organizations/index.html", "organizations/index.html" },
{ "posts/_id/_postslug.html", "posts/_id/_postslug.html id: {{id}}, postslug: {{postslug}}" },
{ "stacks/index.html", "stacks/index.html" },
{ "stacks/new.html", "stacks/new.html" },
{ "stacks/_slug/index.html", "stacks/_slug/index.html slug: {{slug}}" },
{ "stacks/_slug/edit.html", "stacks/_slug/edit.html slug: {{slug}}" },
{ "tech/index.html", "tech/index.html" },
{ "tech/new.html", "tech/new.html" },
{ "tech/_slug/index.html", "tech/_slug/index.html slug: {{slug}}" },
{ "tech/_slug/edit.html", "tech/_slug/edit.html slug: {{slug}}" },
{ "top/index.html", "top/index.html" },
{ "users/_username.html", "users/_username.html username: {{username}}" },
{ "returnpages/index.html", "returnpages/index.html {{ return }} suffix" },
{ "returnpages/_arg.html", "returnpages/_arg.html {{arg}} {{ return }} suffix" },
{ "returnpages/if.html", "returnpages/if.html {{#if true}}{{ return }}{{/if}} suffix" },
{ "httpresults/index.html", "httpresults/index.html {{ {foo:'bar'} |> return({ format: 'json' }) }} suffix" },
{ "httpresults/explicit.html", "httpresults/explicit.html {{ {response: {foo:'bar'}, format: 'json'} |> httpResult |> return }} suffix" },
{ "httpresults/_arg.html", "httpresults/_arg.html {{ {foo:arg} |> return({ format: 'json' }) }} suffix" },
{ "httpresults/no-response.html", "httpresults/no-response.html {{ httpResult({ format: 'json' }) |> return }} suffix" },
{ "httpresults/redirect.html", "httpresults/redirect.html {{ httpResult({ status:'Found', Location:'/httpresults/redirected' }) |> return }} suffix" },
{ "httpresults/redirect-code.html", "httpresults/redirect.html {{ httpResult({ status:301, Location:'/httpresults/redirected-301' }) |> return }} suffix" },
};
public override List<IVirtualPathProvider> GetVirtualFileSources()
{
var existingProviders = base.GetVirtualFileSources();
var memFs = new MemoryVirtualFiles();
foreach (var entry in HtmlFiles)
{
memFs.AppendFile(entry.Key, entry.Value);
}
existingProviders.Insert(0, memFs);
return existingProviders;
}
}
private readonly ServiceStackHost appHost;
public PageBasedRoutingTests()
{
appHost = new AppHost()
.Init()
.Start(Config.ListeningOn);
}
[OneTimeTearDown] public void OneTimeTearDown() => appHost.Dispose();
[Test]
[TestCase("/redis", "<html><body>_slug/index.html slug: redis</body></html>")]
[TestCase("/redis/", "<html><body>_slug/index.html slug: redis</body></html>")]
[TestCase("/redis/clients", "<html><body>_slug/_category.html slug: redis, category: clients</body></html>")]
[TestCase("/comments/1/2", "<html><body>comments/_postid/_id.html postid: 1, id: 2</body></html>")]
[TestCase("/favorites", "<html><body>favorites/index.html</body></html>")]
[TestCase("/login/github", "<html><body>login/_provider.html provider: github</body></html>")]
[TestCase("/organizations/redis", "<html><body>organizations/_slug/index.html slug: redis</body></html>")]
[TestCase("/organizations", "<html><body>organizations/index.html</body></html>")]
[TestCase("/posts/1/the-slug", "<html><body>posts/_id/_postslug.html id: 1, postslug: the-slug</body></html>")]
[TestCase("/stacks", "<html><body>stacks/index.html</body></html>")]
[TestCase("/stacks/new", "<html><body>stacks/new.html</body></html>")]
[TestCase("/stacks/redis", "<html><body>stacks/_slug/index.html slug: redis</body></html>")]
[TestCase("/stacks/redis/edit", "<html><body>stacks/_slug/edit.html slug: redis</body></html>")]
[TestCase("/tech", "<html><body>tech/index.html</body></html>")]
[TestCase("/tech/new", "<html><body>tech/new.html</body></html>")]
[TestCase("/tech/redis", "<html><body>tech/_slug/index.html slug: redis</body></html>")]
[TestCase("/tech/redis/edit", "<html><body>tech/_slug/edit.html slug: redis</body></html>")]
[TestCase("/top", "<html><body>top/index.html</body></html>")]
[TestCase("returnpages", "")]
[TestCase("returnpages/qux", "")]
[TestCase("returnpages/if", "")]
public void Can_use_page_based_routing(string path, string expectedHtml)
{
var html = Config.ListeningOn.CombineWith(path)
.GetStringFromUrl();
Assert.That(html, Is.EqualTo(expectedHtml));
}
[Test]
[TestCase("/httpresults", "{\"foo\":\"bar\"}")]
[TestCase("/httpresults/explicit", "{\"foo\":\"bar\"}")]
[TestCase("/httpresults/qux", "{\"foo\":\"qux\"}")]
[TestCase("/httpresults/no-response", "")]
[TestCase("/httpresults/redirect", "{\"foo\":\"redirected\"}")]
[TestCase("/httpresults/redirect-code", "{\"foo\":\"redirected-301\"}")]
public void Does_return_custom_result(string path, string expectedJson)
{
var response = Config.ListeningOn.CombineWith(path).GetStringFromUrl(
responseFilter:res => Assert.That(res.MatchesContentType(MimeTypes.Json)));
Assert.That(response, Is.EqualTo(expectedJson));
}
}
} | AppHost |
csharp | dotnet__orleans | src/Orleans.Core.Abstractions/Runtime/GrainReference.cs | {
"start": 10001,
"end": 11088
} | public class ____ : IAddressable, IEquatable<GrainReference>, ISpanFormattable
{
/// <summary>
/// The grain reference functionality which is shared by all grain references of a given type.
/// </summary>
[NonSerialized]
private readonly GrainReferenceShared _shared;
/// <summary>
/// The underlying grain id key.
/// </summary>
[NonSerialized]
private readonly IdSpan _key;
/// <summary>
/// Gets the grain reference functionality which is shared by all grain references of a given type.
/// </summary>
internal GrainReferenceShared Shared => _shared ?? throw new GrainReferenceNotBoundException(this);
/// <summary>
/// Gets the grain reference runtime.
/// </summary>
internal IGrainReferenceRuntime Runtime => Shared.Runtime;
/// <summary>
/// Gets the grain id.
/// </summary>
public GrainId GrainId => GrainId.Create(_shared.GrainType, _key);
/// <summary>
/// Gets the | GrainReference |
csharp | microsoft__semantic-kernel | dotnet/src/InternalUtilities/connectors/Memory/MongoDB/MongoMapper.cs | {
"start": 504,
"end": 5680
} | internal sealed class ____<TRecord> : IMongoMapper<TRecord>
where TRecord : class
{
private readonly CollectionModel _model;
/// <summary>A key property info of the data model.</summary>
private readonly PropertyInfo? _keyClrProperty;
/// <summary>A key property name of the data model.</summary>
private readonly string _keyPropertyModelName;
/// <summary>
/// Initializes a new instance of the <see cref="MongoMapper{TRecord}"/> class.
/// </summary>
/// <param name="model">The model.</param>
public MongoMapper(CollectionModel model)
{
this._model = model;
var keyProperty = model.KeyProperty;
this._keyPropertyModelName = keyProperty.ModelName;
this._keyClrProperty = keyProperty.PropertyInfo;
var conventionPack = new ConventionPack
{
new IgnoreExtraElementsConvention(ignoreExtraElements: true)
};
ConventionRegistry.Register(
nameof(MongoMapper<TRecord>),
conventionPack,
type => type == typeof(TRecord));
}
public BsonDocument MapFromDataToStorageModel(TRecord dataModel, int recordIndex, IReadOnlyList<Embedding>?[]? generatedEmbeddings)
{
var document = dataModel.ToBsonDocument();
// Handle key property mapping due to reserved key name in Mongo.
if (!document.Contains(MongoConstants.MongoReservedKeyPropertyName))
{
var value = document[this._keyPropertyModelName];
document.Remove(this._keyPropertyModelName);
document[MongoConstants.MongoReservedKeyPropertyName] = value;
}
// Go over the vector properties; those which have an embedding generator configured on them will have embedding generators, overwrite
// the value in the JSON object with that.
for (var i = 0; i < this._model.VectorProperties.Count; i++)
{
var property = this._model.VectorProperties[i];
Embedding<float>? embedding = generatedEmbeddings?[i]?[recordIndex] is Embedding e ? (Embedding<float>)e : null;
if (embedding is null)
{
switch (Nullable.GetUnderlyingType(property.Type) ?? property.Type)
{
case var t when t == typeof(ReadOnlyMemory<float>):
case var t2 when t2 == typeof(float[]):
// The .NET vector property is a ReadOnlyMemory<float> or float[] (not an Embedding<float>), which means that ToBsonDocument()
// already serialized it correctly above.
// In addition, there's no generated embedding (which would be an Embedding<float> which we'd need to handle manually).
// So there's nothing for us to do.
continue;
case var t when t == typeof(Embedding<float>):
embedding = (Embedding<float>)property.GetValueAsObject(dataModel)!;
break;
default:
throw new UnreachableException();
}
}
document[property.StorageName] = BsonArray.Create(embedding.Vector.ToArray());
}
return document;
}
public TRecord MapFromStorageToDataModel(BsonDocument storageModel, bool includeVectors)
{
// Handle key property mapping due to reserved key name in Mongo.
if (!this._keyPropertyModelName.Equals(MongoConstants.DataModelReservedKeyPropertyName, StringComparison.OrdinalIgnoreCase) &&
this._keyClrProperty?.GetCustomAttribute<BsonIdAttribute>() is null)
{
var value = storageModel[MongoConstants.MongoReservedKeyPropertyName];
storageModel.Remove(MongoConstants.MongoReservedKeyPropertyName);
storageModel[this._keyPropertyModelName] = value;
}
if (includeVectors)
{
foreach (var vectorProperty in this._model.VectorProperties)
{
// If the vector property .NET type is Embedding<float>, we need to create the BSON structure for it
// (BSON array embedded inside an object representing the embedding), so that the deserialization below
// works correctly.
if (vectorProperty.Type == typeof(Embedding<float>))
{
storageModel[vectorProperty.StorageName] = new BsonDocument
{
[nameof(Embedding<float>.Vector)] = BsonArray.Create(storageModel[vectorProperty.StorageName])
};
}
}
}
else
{
// If includeVectors is false, remove the values; this allows us to not project them out of Mongo in the future
// (more efficient) without introducing a breaking change.
foreach (var vectorProperty in this._model.VectorProperties)
{
storageModel.Remove(vectorProperty.StorageName);
}
}
return BsonSerializer.Deserialize<TRecord>(storageModel);
}
}
| MongoMapper |
csharp | nunit__nunit | src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs | {
"start": 350,
"end": 1948
} | public class ____ : TestSuite
{
private readonly bool _genericFixture;
/// <summary>
/// Initializes a new instance of the <see cref="ParameterizedFixtureSuite"/> class.
/// </summary>
/// <param name="typeInfo">The ITypeInfo for the type that represents the suite.</param>
public ParameterizedFixtureSuite(ITypeInfo typeInfo) : base(typeInfo.Namespace, typeInfo.GetDisplayName())
{
_genericFixture = typeInfo.ContainsGenericParameters;
}
/// <summary>
/// Creates a copy of the given suite with only the descendants that pass the specified filter.
/// </summary>
/// <param name="suite">The <see cref="ParameterizedFixtureSuite"/> to copy.</param>
/// <param name="filter">Determines which descendants are copied.</param>
public ParameterizedFixtureSuite(ParameterizedFixtureSuite suite, ITestFilter filter)
: base(suite, filter)
{
}
/// <summary>
/// Gets a string representing the type of test
/// </summary>
public override string TestType =>
_genericFixture
? "GenericFixture"
: "ParameterizedFixture";
/// <summary>
/// Creates a filtered copy of the test suite.
/// </summary>
/// <param name="filter">Determines which descendants are copied.</param>
public override TestSuite Copy(ITestFilter filter)
{
return new ParameterizedFixtureSuite(this, filter);
}
}
}
| ParameterizedFixtureSuite |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Services/Orders/CustomValues.cs | {
"start": 126,
"end": 5439
} | public partial class ____ : List<CustomValue>
{
#region Methods
/// <summary>
/// Get custom values by specified display location
/// </summary>
/// <param name="displayLocation">Display location</param>
/// <returns>List of custom values filtered by display location</returns>
public virtual List<CustomValue> GetValuesByDisplayLocation(CustomValueDisplayLocation displayLocation)
{
return this.Where(cv => cv.DisplayLocation == displayLocation).ToList();
}
/// <summary>
/// Serialize list of custom values into XML format
/// </summary>
/// <returns>XML of custom values</returns>
public virtual string SerializeToXml()
{
if (!this.Any())
return string.Empty;
using var textWriter = new StringWriter();
var root = new XElement("DictionarySerializer");
root.Add(this.Select(value => new XElement("item",
new XElement("key", value.Name),
new XElement("value", value.Value),
new XElement("displayToCustomer", value.DisplayToCustomer),
new XElement("location", (int)value.DisplayLocation),
new XElement("createdOn", value.CreatedOnUtc?.Ticks ?? 0))));
var document = new XDocument();
document.Add(root);
document.Save(textWriter, SaveOptions.DisableFormatting);
var result = textWriter.ToString();
return result;
}
/// <summary>
/// Fill order custom values by XML
/// </summary>
/// <param name="customValuesXml">XML of custom values</param>
/// <param name="displayToCustomerOnly">The flag indicates whether we should use only values that are allowed for customers</param>
/// <returns>Custom values</returns>
public virtual void FillByXml(string customValuesXml, bool displayToCustomerOnly = false)
{
Clear();
if (string.IsNullOrWhiteSpace(customValuesXml))
return;
//use the 'Payment' value as default for compatibility with previous versions
var defaultLocation = CustomValueDisplayLocation.Payment;
//display a custom value by default for compatibility with previous versions
var defaultDisplayToCustomer = true;
try
{
using var textReader = new StringReader(customValuesXml);
var rootElement = XDocument.Load(textReader).Root;
AddRange(rootElement!.Elements("item").Select(i =>
{
var name = i.Element("key")!.Value;
var value = i.Element("value")!.Value;
var displayLocation = int.TryParse(i.Element("location")?.Value, out var location) && Enum.IsDefined(typeof(CustomValueDisplayLocation), location)
? (CustomValueDisplayLocation)location
: defaultLocation;
var displayToCustomer = bool.TryParse(i.Element("displayToCustomer")?.Value, out var display)
? display
: defaultDisplayToCustomer;
var createdOn = long.TryParse(i.Element("createdOn")?.Value, out var ticks)
? (ticks > 0 ? new DateTime(ticks) : (DateTime?)null)
: null;
return new CustomValue(name, value, displayLocation, displayToCustomer, createdOn);
}).Where(value => value.DisplayToCustomer || !displayToCustomerOnly));
}
catch
{
//ignore
}
}
/// <summary>
/// Removes the custom value with the specified name
/// </summary>
/// <param name="name">The name of the custom value.</param>
/// <returns>
/// <see langword="true" /> if the element is successfully removed; otherwise, <see langword="false" />. This method also returns <see langword="false" /> if <paramref name="name" /> was not found.
/// </returns>
public virtual bool Remove(string name)
{
return TryGetValue(name, out var value) && Remove(value);
}
/// <summary>
/// Gets the value associated with the specified name
/// </summary>
/// <param name="name">The name whose value to get.</param>
/// <param name="customValue">When this method returns, the value associated with the specified name, if the name is found; otherwise, the null value</param>
/// <returns>
/// <see langword="true" /> if the custom values list contains an element with the specified name; otherwise, <see langword="false" />.
/// </returns>
public virtual bool TryGetValue(string name, out CustomValue customValue)
{
customValue = this.FirstOrDefault(cv => cv.Name.Equals(name));
return customValue != null;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the value of custom value with the specified name
/// </summary>
/// <param name="name">The name of the custom value to get or set</param>
/// <returns>The value of custom value with the specified name</returns>
public virtual string this[string name]
{
get
{
var value = this.First(cv => cv.Name.Equals(name));
return value.Value;
}
set
{
Remove(name);
Add(new CustomValue(name, value));
}
}
#endregion
} | CustomValues |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/Helm/Helm.Generated.cs | {
"start": 255763,
"end": 263014
} | partial class ____
{
#region Revision
/// <inheritdoc cref="HelmGetManifestSettings.Revision"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Revision))]
public static T SetRevision<T>(this T o, int? v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.Revision, v));
/// <inheritdoc cref="HelmGetManifestSettings.Revision"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Revision))]
public static T ResetRevision<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.Revision));
#endregion
#region Tls
/// <inheritdoc cref="HelmGetManifestSettings.Tls"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Tls))]
public static T SetTls<T>(this T o, bool? v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.Tls, v));
/// <inheritdoc cref="HelmGetManifestSettings.Tls"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Tls))]
public static T ResetTls<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.Tls));
/// <inheritdoc cref="HelmGetManifestSettings.Tls"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Tls))]
public static T EnableTls<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.Tls, true));
/// <inheritdoc cref="HelmGetManifestSettings.Tls"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Tls))]
public static T DisableTls<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.Tls, false));
/// <inheritdoc cref="HelmGetManifestSettings.Tls"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.Tls))]
public static T ToggleTls<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.Tls, !o.Tls));
#endregion
#region TlsCaCert
/// <inheritdoc cref="HelmGetManifestSettings.TlsCaCert"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsCaCert))]
public static T SetTlsCaCert<T>(this T o, string v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsCaCert, v));
/// <inheritdoc cref="HelmGetManifestSettings.TlsCaCert"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsCaCert))]
public static T ResetTlsCaCert<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.TlsCaCert));
#endregion
#region TlsCert
/// <inheritdoc cref="HelmGetManifestSettings.TlsCert"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsCert))]
public static T SetTlsCert<T>(this T o, string v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsCert, v));
/// <inheritdoc cref="HelmGetManifestSettings.TlsCert"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsCert))]
public static T ResetTlsCert<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.TlsCert));
#endregion
#region TlsHostname
/// <inheritdoc cref="HelmGetManifestSettings.TlsHostname"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsHostname))]
public static T SetTlsHostname<T>(this T o, string v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsHostname, v));
/// <inheritdoc cref="HelmGetManifestSettings.TlsHostname"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsHostname))]
public static T ResetTlsHostname<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.TlsHostname));
#endregion
#region TlsKey
/// <inheritdoc cref="HelmGetManifestSettings.TlsKey"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsKey))]
public static T SetTlsKey<T>(this T o, string v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsKey, v));
/// <inheritdoc cref="HelmGetManifestSettings.TlsKey"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsKey))]
public static T ResetTlsKey<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.TlsKey));
#endregion
#region TlsVerify
/// <inheritdoc cref="HelmGetManifestSettings.TlsVerify"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsVerify))]
public static T SetTlsVerify<T>(this T o, bool? v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsVerify, v));
/// <inheritdoc cref="HelmGetManifestSettings.TlsVerify"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsVerify))]
public static T ResetTlsVerify<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.TlsVerify));
/// <inheritdoc cref="HelmGetManifestSettings.TlsVerify"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsVerify))]
public static T EnableTlsVerify<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsVerify, true));
/// <inheritdoc cref="HelmGetManifestSettings.TlsVerify"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsVerify))]
public static T DisableTlsVerify<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsVerify, false));
/// <inheritdoc cref="HelmGetManifestSettings.TlsVerify"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.TlsVerify))]
public static T ToggleTlsVerify<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.TlsVerify, !o.TlsVerify));
#endregion
#region ReleaseName
/// <inheritdoc cref="HelmGetManifestSettings.ReleaseName"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.ReleaseName))]
public static T SetReleaseName<T>(this T o, string v) where T : HelmGetManifestSettings => o.Modify(b => b.Set(() => o.ReleaseName, v));
/// <inheritdoc cref="HelmGetManifestSettings.ReleaseName"/>
[Pure] [Builder(Type = typeof(HelmGetManifestSettings), Property = nameof(HelmGetManifestSettings.ReleaseName))]
public static T ResetReleaseName<T>(this T o) where T : HelmGetManifestSettings => o.Modify(b => b.Remove(() => o.ReleaseName));
#endregion
}
#endregion
#region HelmGetNotesSettingsExtensions
/// <inheritdoc cref="HelmTasks.HelmGetNotes(Nuke.Common.Tools.Helm.HelmGetNotesSettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static | HelmGetManifestSettingsExtensions |
csharp | dotnet__aspnetcore | src/Razor/Razor/src/TagHelpers/DefaultTagHelperContent.cs | {
"start": 443,
"end": 7282
} | public class ____ : TagHelperContent
{
private object _singleContent;
private bool _isSingleContentSet;
private bool _isModified;
private bool _hasContent;
private List<object> _buffer;
private List<object> Buffer
{
get
{
if (_buffer == null)
{
_buffer = new List<object>();
}
if (_isSingleContentSet)
{
Debug.Assert(_buffer.Count == 0);
_buffer.Add(_singleContent);
_isSingleContentSet = false;
}
return _buffer;
}
}
/// <inheritdoc />
public override bool IsModified => _isModified;
/// <inheritdoc />
/// <remarks>Returns <c>true</c> for a cleared <see cref="TagHelperContent"/>.</remarks>
public override bool IsEmptyOrWhiteSpace
{
get
{
if (!_hasContent)
{
return true;
}
using (var writer = new EmptyOrWhiteSpaceWriter())
{
if (_isSingleContentSet)
{
return IsEmptyOrWhiteSpaceCore(_singleContent, writer);
}
for (var i = 0; i < (_buffer?.Count ?? 0); i++)
{
if (!IsEmptyOrWhiteSpaceCore(Buffer[i], writer))
{
return false;
}
}
}
return true;
}
}
/// <inheritdoc />
public override TagHelperContent Append(string unencoded) => AppendCore(unencoded);
/// <inheritdoc />
public override TagHelperContent AppendHtml(IHtmlContent htmlContent) => AppendCore(htmlContent);
/// <inheritdoc />
public override TagHelperContent AppendHtml(string encoded)
{
if (encoded == null)
{
return AppendCore(null);
}
return AppendCore(new HtmlString(encoded));
}
/// <inheritdoc />
public override void CopyTo(IHtmlContentBuilder destination)
{
ArgumentNullException.ThrowIfNull(destination);
if (!_hasContent)
{
return;
}
if (_isSingleContentSet)
{
CopyToCore(_singleContent, destination);
}
else
{
for (var i = 0; i < (_buffer?.Count ?? 0); i++)
{
CopyToCore(Buffer[i], destination);
}
}
}
/// <inheritdoc />
public override void MoveTo(IHtmlContentBuilder destination)
{
ArgumentNullException.ThrowIfNull(destination);
if (!_hasContent)
{
return;
}
if (_isSingleContentSet)
{
MoveToCore(_singleContent, destination);
}
else
{
for (var i = 0; i < (_buffer?.Count ?? 0); i++)
{
MoveToCore(Buffer[i], destination);
}
}
Clear();
}
/// <inheritdoc />
public override TagHelperContent Clear()
{
_hasContent = false;
_isModified = true;
_isSingleContentSet = false;
_buffer?.Clear();
return this;
}
/// <inheritdoc />
public override void Reinitialize()
{
Clear();
_isModified = false;
}
/// <inheritdoc />
public override string GetContent() => GetContent(HtmlEncoder.Default);
/// <inheritdoc />
public override string GetContent(HtmlEncoder encoder)
{
if (!_hasContent)
{
return string.Empty;
}
using (var writer = new StringWriter())
{
WriteTo(writer, encoder);
return writer.ToString();
}
}
/// <inheritdoc />
public override void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
ArgumentNullException.ThrowIfNull(writer);
ArgumentNullException.ThrowIfNull(encoder);
if (!_hasContent)
{
return;
}
if (_isSingleContentSet)
{
WriteToCore(_singleContent, writer, encoder);
return;
}
for (var i = 0; i < (_buffer?.Count ?? 0); i++)
{
WriteToCore(Buffer[i], writer, encoder);
}
}
private static void WriteToCore(object entry, TextWriter writer, HtmlEncoder encoder)
{
if (entry == null)
{
return;
}
if (entry is string stringValue)
{
encoder.Encode(writer, stringValue);
}
else
{
((IHtmlContent)entry).WriteTo(writer, encoder);
}
}
private static void CopyToCore(object entry, IHtmlContentBuilder destination)
{
if (entry == null)
{
return;
}
if (entry is string entryAsString)
{
destination.Append(entryAsString);
}
else if (entry is IHtmlContentContainer entryAsContainer)
{
entryAsContainer.CopyTo(destination);
}
else
{
destination.AppendHtml((IHtmlContent)entry);
}
}
private static void MoveToCore(object entry, IHtmlContentBuilder destination)
{
if (entry == null)
{
return;
}
if (entry is string entryAsString)
{
destination.Append(entryAsString);
}
else if (entry is IHtmlContentContainer entryAsContainer)
{
entryAsContainer.MoveTo(destination);
}
else
{
destination.AppendHtml((IHtmlContent)entry);
}
}
private static bool IsEmptyOrWhiteSpaceCore(object entry, EmptyOrWhiteSpaceWriter writer)
{
if (entry == null)
{
return true;
}
if (entry is string stringValue)
{
// Do not encode the string because encoded value remains whitespace from user's POV.
return string.IsNullOrWhiteSpace(stringValue);
}
// Use NullHtmlEncoder to avoid treating encoded whitespace as non-whitespace e.g. "\t" as "	".
((IHtmlContent)entry).WriteTo(writer, NullHtmlEncoder.Default);
return writer.IsEmptyOrWhiteSpace;
}
private TagHelperContent AppendCore(object entry)
{
if (!_hasContent)
{
_isSingleContentSet = true;
_singleContent = entry;
}
else
{
Buffer.Add(entry);
}
_isModified = true;
_hasContent = true;
return this;
}
private string DebuggerToString()
{
return GetContent();
}
// Overrides Write(string) to find if the content written is empty/whitespace.
| DefaultTagHelperContent |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Administration/Application/Members/GetMember/GetMemberQueryHandler.cs | {
"start": 257,
"end": 1626
} | internal class ____ : IQueryHandler<GetMemberQuery, MemberDto>
{
private readonly ISqlConnectionFactory _sqlConnectionFactory;
public GetMemberQueryHandler(ISqlConnectionFactory sqlConnectionFactory)
{
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task<MemberDto> Handle(GetMemberQuery query, CancellationToken cancellationToken)
{
var connection = _sqlConnectionFactory.GetOpenConnection();
const string sql = $"""
SELECT
[Member].[Id] AS [{nameof(MemberDto.Id)}],
[Member].[Login] AS [{nameof(MemberDto.Login)}],
[Member].[Email] AS [{nameof(MemberDto.Email)}],
[Member].[FirstName] AS [{nameof(MemberDto.FirstName)}],
[Member].[LastName] AS [{nameof(MemberDto.LastName)}],
[Member].[Name] AS [{nameof(MemberDto.Name)}]
FROM [administration].[v_Members] AS [Member]
WHERE [Member].[Id] = @MemberId
""";
return await connection.QuerySingleAsync<MemberDto>(sql, new { query.MemberId });
}
}
} | GetMemberQueryHandler |
csharp | AutoMapper__AutoMapper | src/UnitTests/MemberResolution.cs | {
"start": 28262,
"end": 28812
} | public class ____
{
public int someValueWithPascalName { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
var source = new Source {SomeValueWithPascalName = 5};
_result = Mapper.Map<Source, Destination>(source);
}
[Fact]
public void Should_match_to_PascalCased_source_member()
{
_result.someValueWithPascalName.ShouldBe(5);
}
}
| Destination |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.Telemetry.Abstractions/Logging/ITagCollector.cs | {
"start": 431,
"end": 466
} | interface ____ used.
/// </remarks>
| is |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/src/Analyzers/Infrastructure/RouteUsageCache.cs | {
"start": 552,
"end": 2898
} | internal sealed class ____
{
private static readonly BoundedCacheWithFactory<Compilation, RouteUsageCache> LazyRouteUsageCache = new();
public static RouteUsageCache GetOrCreate(Compilation compilation) =>
LazyRouteUsageCache.GetOrCreateValue(compilation, static c => new RouteUsageCache(c));
private readonly ConcurrentDictionary<SyntaxToken, RouteUsageModel?> _lazyRoutePatterns;
private readonly Compilation _compilation;
private RouteUsageCache(Compilation compilation)
{
_lazyRoutePatterns = new();
_compilation = compilation;
}
public RouteUsageModel? Get(SyntaxToken syntaxToken, CancellationToken cancellationToken)
{
if (_lazyRoutePatterns.TryGetValue(syntaxToken, out var routeUsageModel))
{
return routeUsageModel;
}
return GetAndCache(syntaxToken, cancellationToken);
}
private RouteUsageModel? GetAndCache(SyntaxToken syntaxToken, CancellationToken cancellationToken)
{
return _lazyRoutePatterns.GetOrAdd(syntaxToken, token =>
{
if (syntaxToken.SyntaxTree == null)
{
return null;
}
var semanticModel = _compilation.GetSemanticModel(syntaxToken.SyntaxTree);
if (!RouteStringSyntaxDetector.IsRouteStringSyntaxToken(token, semanticModel, cancellationToken, out var options))
{
return null;
}
var wellKnownTypes = WellKnownTypes.GetOrCreate(_compilation);
var usageContext = RouteUsageDetector.BuildContext(
options,
token,
semanticModel,
wellKnownTypes,
cancellationToken);
var virtualChars = CSharpVirtualCharService.Instance.TryConvertToVirtualChars(token);
var isMvc = usageContext.UsageType == RouteUsageType.MvcAction || usageContext.UsageType == RouteUsageType.MvcController;
var tree = RoutePatternParser.TryParse(virtualChars, usageContext.RoutePatternOptions);
if (tree == null)
{
return null;
}
return new RouteUsageModel
{
RoutePattern = tree,
UsageContext = usageContext
};
});
}
}
| RouteUsageCache |
csharp | files-community__Files | src/Files.App/Utils/Shell/PreviewHandler.cs | {
"start": 1255,
"end": 2084
} | partial class ____ : IPreviewHandlerFrame, IDisposable
{
bool disposed;
nint hwnd;
public PreviewHandlerFrame(nint frame)
{
disposed = true;
disposed = false;
hwnd = frame;
}
public void Dispose()
{
disposed = true;
}
public int GetWindowContext(out PreviewHandlerFrameInfo pinfo)
{
pinfo.AcceleratorTableHandle = IntPtr.Zero;
pinfo.AcceleratorEntryCount = 0;
if (disposed)
return E_FAIL;
return S_OK;
}
public int TranslateAccelerator(nint pmsg)
{
if (disposed)
return E_FAIL;
return S_FALSE;
}
}
#endregion IPreviewHandlerFrame support
#region IPreviewHandler major interfaces
[GeneratedComInterface, Guid("8895b1c6-b41f-4c1c-a562-0d564250836f"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
| PreviewHandlerFrame |
csharp | dotnet__aspire | src/Aspire.Hosting.GitHub.Models/api/Aspire.Hosting.GitHub.Models.cs | {
"start": 5475,
"end": 6265
} | public partial class ____ : ApplicationModel.Resource, ApplicationModel.IResourceWithConnectionString, ApplicationModel.IResource, ApplicationModel.IManifestExpressionProvider, ApplicationModel.IValueProvider, ApplicationModel.IValueWithReferences
{
public GitHubModelResource(string name, string model, ApplicationModel.ParameterResource? organization, ApplicationModel.ParameterResource key) : base(default!) { }
public ApplicationModel.ReferenceExpression ConnectionStringExpression { get { throw null; } }
public ApplicationModel.ParameterResource Key { get { throw null; } }
public string Model { get { throw null; } set { } }
public ApplicationModel.ParameterResource? Organization { get { throw null; } set { } }
}
} | GitHubModelResource |
csharp | smartstore__Smartstore | src/Smartstore/Imaging/IImageFactory.cs | {
"start": 68,
"end": 125
} | interface ____ imaging libraries.
/// </summary>
| for |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Input/GestureRecognizers/VelocityTracker.cs | {
"start": 402,
"end": 2112
} | record ____ Velocity(Vector PixelsPerSecond)
{
public Velocity ClampMagnitude(double minValue, double maxValue)
{
Debug.Assert(minValue >= 0.0);
Debug.Assert(maxValue >= 0.0 && maxValue >= minValue);
double valueSquared = PixelsPerSecond.SquaredLength;
if (valueSquared > maxValue * maxValue)
{
double length = PixelsPerSecond.Length;
return new Velocity(length != 0.0 ? (PixelsPerSecond / length) * maxValue : Vector.Zero);
// preventing double.NaN in Vector PixelsPerSecond is important -- if a NaN eventually gets into a
// ScrollGestureEventArgs it results in runtime errors.
}
if (valueSquared < minValue * minValue)
{
double length = PixelsPerSecond.Length;
return new Velocity(length != 0.0 ? (PixelsPerSecond / length) * minValue : Vector.Zero);
}
return this;
}
}
/// A two dimensional velocity estimate.
///
/// VelocityEstimates are computed by [VelocityTracker.getVelocityEstimate]. An
/// estimate's [confidence] measures how well the velocity tracker's position
/// data fit a straight line, [duration] is the time that elapsed between the
/// first and last position sample used to compute the velocity, and [offset]
/// is similarly the difference between the first and last positions.
///
/// See also:
///
/// * [VelocityTracker], which computes [VelocityEstimate]s.
/// * [Velocity], which encapsulates (just) a velocity vector and provides some
/// useful velocity operations.
| struct |
csharp | smartstore__Smartstore | src/Smartstore.Web.Common/TagHelpers/Shared/Forms/EditorTagHelper.cs | {
"start": 389,
"end": 3043
} | public class ____ : BaseFormTagHelper
{
const string EditorTagName = "editor";
const string TemplateAttributeName = "asp-template";
const string AdditionalViewDataAttributeName = "asp-additional-viewdata";
//const string ValueAttributeName = "asp-value";
const string PostfixAttributeName = "sm-postfix";
// TODO: (mh) (core) Find a way to propagate "required" metadata to template, 'cause FluentValidation obviously does not provide this info to MVC metadata.
/// <summary>
/// Specifies the editor template which will be used to render the field.
/// </summary>
[HtmlAttributeName(TemplateAttributeName)]
public string Template { get; set; }
/// <summary>
/// Specifies the value to set into editor input tag.
/// </summary>
//[HtmlAttributeName(ValueAttributeName)]
//public string Value { get; set; }
/// <summary>
/// The text which will be displayed inside the input as a post fix.
/// </summary>
[HtmlAttributeName(PostfixAttributeName)]
public string Postfix { get; set; }
/// <summary>
/// An anonymous <see cref="object"/> or <see cref="System.Collections.Generic.IDictionary{String, Object}"/>
/// that can contain additional view data that will be merged into the
/// <see cref="ViewDataDictionary{TModel}"/> instance created for the template.
/// </summary>
[HtmlAttributeName(AdditionalViewDataAttributeName)]
public object AdditionalViewData { get; set; }
protected override void ProcessCore(TagHelperContext context, TagHelperOutput output)
{
output.SuppressOutput();
var viewData = ConvertUtility.ObjectToDictionary(AdditionalViewData);
if (Postfix != null)
{
viewData["postfix"] = Postfix;
}
if (output.Attributes != null && output.Attributes.Count > 0)
{
var htmlAttributes = new Dictionary<string, object>();
foreach (var attr in output.Attributes)
{
htmlAttributes[attr.Name] = attr.ValueAsString();
}
viewData["htmlAttributes"] = htmlAttributes;
}
if (viewData.Count > 0)
{
output.Content.SetHtmlContent(HtmlHelper.EditorFor(For, Template, viewData));
}
else
{
output.Content.SetHtmlContent(HtmlHelper.EditorFor(For, Template));
}
}
}
}
| EditorTagHelper |
csharp | dotnet__maui | src/Controls/tests/Core.UnitTests/FlyoutPageUnitTests.cs | {
"start": 24059,
"end": 24972
} | public class ____ : NavigationPage
{
public NavigatedFromEventArgs NavigatedFromArgs { get; private set; }
public NavigatingFromEventArgs NavigatingFromArgs { get; private set; }
public NavigatedToEventArgs NavigatedToArgs { get; private set; }
public TrackingNavigationPage(Page root) : base(root) { }
public void ClearNavigationArgs()
{
NavigatedFromArgs = null;
NavigatingFromArgs = null;
NavigatedToArgs = null;
}
protected override void OnNavigatedFrom(NavigatedFromEventArgs args)
{
base.OnNavigatedFrom(args);
NavigatedFromArgs = args;
}
protected override void OnNavigatingFrom(NavigatingFromEventArgs args)
{
base.OnNavigatingFrom(args);
NavigatingFromArgs = args;
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
NavigatedToArgs = args;
}
}
}
}
| TrackingNavigationPage |
csharp | abpframework__abp | framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/IReadOnlyBasicRepository.cs | {
"start": 1138,
"end": 2500
} | public interface ____<TEntity, TKey> : IReadOnlyBasicRepository<TEntity>
where TEntity : class, IEntity<TKey>
{
/// <summary>
/// Gets an entity with given primary key.
/// Throws <see cref="EntityNotFoundException"/> if can not find an entity with given id.
/// </summary>
/// <param name="id">Primary key of the entity to get</param>
/// <param name="includeDetails">Set true to include all children of this entity</param>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>Entity</returns>
[NotNull]
Task<TEntity> GetAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default);
/// <summary>
/// Gets an entity with given primary key or null if not found.
/// </summary>
/// <param name="id">Primary key of the entity to get</param>
/// <param name="includeDetails">Set true to include all children of this entity</param>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>Entity or null</returns>
Task<TEntity?> FindAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default);
}
| IReadOnlyBasicRepository |
csharp | microsoft__PowerToys | src/modules/fancyzones/editor/FancyZonesEditor/Models/DefaultLayoutsModel.cs | {
"start": 342,
"end": 2452
} | public class ____ : INotifyPropertyChanged
{
private static int Count { get; } = Enum.GetValues(typeof(MonitorConfigurationType)).Length;
public Dictionary<MonitorConfigurationType, LayoutModel> Layouts { get; } = new Dictionary<MonitorConfigurationType, LayoutModel>(Count);
public DefaultLayoutsModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void Reset(MonitorConfigurationType type)
{
switch (type)
{
case MonitorConfigurationType.Horizontal:
Set(MainWindowSettingsModel.TemplateModels[(int)LayoutType.PriorityGrid], type);
break;
case MonitorConfigurationType.Vertical:
Set(MainWindowSettingsModel.TemplateModels[(int)LayoutType.Rows], type);
break;
}
}
public void Reset(string uuid)
{
if (Layouts[MonitorConfigurationType.Horizontal].Uuid == uuid)
{
Set(MainWindowSettingsModel.TemplateModels[(int)LayoutType.PriorityGrid], MonitorConfigurationType.Horizontal);
}
if (Layouts[MonitorConfigurationType.Vertical].Uuid == uuid)
{
Set(MainWindowSettingsModel.TemplateModels[(int)LayoutType.Rows], MonitorConfigurationType.Vertical);
}
}
public void Set(LayoutModel layout, MonitorConfigurationType type)
{
Layouts[type] = layout;
FirePropertyChanged();
}
public void Restore(Dictionary<MonitorConfigurationType, LayoutModel> layouts)
{
foreach (var monitorConfigurationType in layouts.Keys)
{
Set(layouts[monitorConfigurationType], monitorConfigurationType);
}
}
protected virtual void FirePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| DefaultLayoutsModel |
csharp | abpframework__abp | modules/blogging/src/Volo.Blogging.Admin.Web/Pages/Blogging/Admin/Blogs/Index.cshtml.cs | {
"start": 168,
"end": 690
} | public class ____ : BloggingAdminPageModel
{
private readonly IAuthorizationService _authorization;
public IndexModel(IAuthorizationService authorization)
{
_authorization = authorization;
}
public virtual async Task<ActionResult> OnGetAsync()
{
if (!await _authorization.IsGrantedAsync(BloggingPermissions.Blogs.Management))
{
return Redirect("/");
}
return Page();
}
}
}
| IndexModel |
csharp | unoplatform__uno | src/Uno.UI.Tests/Windows_UI_Xaml_Markup/XamlReaderTests/CreateFromString.cs | {
"start": 998,
"end": 1333
} | public class ____ : CreateFromStringBase
{
public CreateFromStringNonQualifiedMethodName(int value) : base(value)
{
}
public static CreateFromStringNonQualifiedMethodName ConversionMethod(string input)
{
return new CreateFromStringNonQualifiedMethodName(int.Parse(input) * 2);
}
}
| CreateFromStringNonQualifiedMethodName |
csharp | neuecc__MessagePack-CSharp | src/MessagePack/Formatters/ValueTupleFormatter.cs | {
"start": 7660,
"end": 10020
} | public sealed class ____<T1, T2, T3, T4, T5> : IMessagePackFormatter<ValueTuple<T1, T2, T3, T4, T5>>
{
public void Serialize(ref MessagePackWriter writer, ValueTuple<T1, T2, T3, T4, T5> value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(5);
IFormatterResolver resolver = options.Resolver;
resolver.GetFormatterWithVerify<T1>().Serialize(ref writer, value.Item1, options);
resolver.GetFormatterWithVerify<T2>().Serialize(ref writer, value.Item2, options);
resolver.GetFormatterWithVerify<T3>().Serialize(ref writer, value.Item3, options);
resolver.GetFormatterWithVerify<T4>().Serialize(ref writer, value.Item4, options);
resolver.GetFormatterWithVerify<T5>().Serialize(ref writer, value.Item5, options);
}
public ValueTuple<T1, T2, T3, T4, T5> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw MessagePackSerializationException.ThrowUnexpectedNilWhileDeserializing<ValueTuple<T1, T2, T3, T4, T5>>();
}
else
{
var count = reader.ReadArrayHeader();
if (count != 5)
{
throw new MessagePackSerializationException("Invalid ValueTuple count");
}
IFormatterResolver resolver = options.Resolver;
options.Security.DepthStep(ref reader);
try
{
T1 item1 = resolver.GetFormatterWithVerify<T1>().Deserialize(ref reader, options);
T2 item2 = resolver.GetFormatterWithVerify<T2>().Deserialize(ref reader, options);
T3 item3 = resolver.GetFormatterWithVerify<T3>().Deserialize(ref reader, options);
T4 item4 = resolver.GetFormatterWithVerify<T4>().Deserialize(ref reader, options);
T5 item5 = resolver.GetFormatterWithVerify<T5>().Deserialize(ref reader, options);
return new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
}
finally
{
reader.Depth--;
}
}
}
}
[Preserve]
| ValueTupleFormatter |
csharp | dotnet__aspnetcore | src/Components/Components/test/PersistentValueProviderComponentSubscriptionTests.cs | {
"start": 25874,
"end": 25958
} | private class ____
{
public string Value { get; set; }
}
| CustomData |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Bson/IO/JsonToken.cs | {
"start": 708,
"end": 2593
} | public enum ____
{
/// <summary>
/// An invalid token.
/// </summary>
Invalid,
/// <summary>
/// A begin array token (a '[').
/// </summary>
BeginArray,
/// <summary>
/// A begin object token (a '{').
/// </summary>
BeginObject,
/// <summary>
/// An end array token (a ']').
/// </summary>
EndArray,
/// <summary>
/// A left parenthesis (a '(').
/// </summary>
LeftParen,
/// <summary>
/// A right parenthesis (a ')').
/// </summary>
RightParen,
/// <summary>
/// An end object token (a '}').
/// </summary>
EndObject,
/// <summary>
/// A colon token (a ':').
/// </summary>
Colon,
/// <summary>
/// A comma token (a ',').
/// </summary>
Comma,
/// <summary>
/// A DateTime token.
/// </summary>
DateTime,
/// <summary>
/// A Double token.
/// </summary>
Double,
/// <summary>
/// An Int32 token.
/// </summary>
Int32,
/// <summary>
/// And Int64 token.
/// </summary>
Int64,
/// <summary>
/// An ObjectId token.
/// </summary>
ObjectId,
/// <summary>
/// A regular expression token.
/// </summary>
RegularExpression,
/// <summary>
/// A string token.
/// </summary>
String,
/// <summary>
/// An unquoted string token.
/// </summary>
UnquotedString,
/// <summary>
/// An end of file token.
/// </summary>
EndOfFile
}
/// <summary>
/// Represents a JSON token.
/// </summary>
| JsonTokenType |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI/Converters/DoubleToVisibilityConverter.cs | {
"start": 419,
"end": 841
} | public class ____ : DoubleToObjectConverter
{
/// <summary>
/// Initializes a new instance of the <see cref="DoubleToVisibilityConverter"/> class.
/// </summary>
public DoubleToVisibilityConverter()
{
TrueValue = Visibility.Visible;
FalseValue = Visibility.Collapsed;
NullValue = Visibility.Collapsed;
}
}
} | DoubleToVisibilityConverter |
csharp | MonoGame__MonoGame | build/BuildFrameworksTasks/BuildConsoleCheckTask.cs | {
"start": 60,
"end": 618
} | public sealed class ____ : FrostingTask<BuildContext>
{
public override bool ShouldRun(BuildContext context) => context.IsRunningOnWindows();
public override void Run(BuildContext context)
{
// ConsoleCheck is getting switched to netstandard2.1 target framework next week
// temporarely disable its compilation so that this compiles due to changes in TitleContainer.cs
//
// context.DotNetBuild(context.GetProjectPath(ProjectType.Framework, "ConsoleCheck"), context.DotNetBuildSettings);
}
}
| BuildConsoleCheckTask |
csharp | microsoft__FASTER | cs/src/core/VarLen/MemoryVarLenStruct.cs | {
"start": 206,
"end": 1980
} | public class ____<T> : IVariableLengthStruct<Memory<T>> where T : unmanaged
{
///<inheritdoc/>
public int GetInitialLength() => sizeof(int);
///<inheritdoc/>
public unsafe int GetLength(ref Memory<T> t) => sizeof(int) + t.Length * sizeof(T);
///<inheritdoc/>
public unsafe void Serialize(ref Memory<T> source, void* destination)
{
*(int*)destination = source.Length * sizeof(T);
MemoryMarshal.Cast<T, byte>(source.Span)
.CopyTo(new Span<byte>((byte*)destination + sizeof(int), source.Length * sizeof(T)));
}
[ThreadStatic]
static (UnmanagedMemoryManager<T>, Memory<T>)[] refCache;
[ThreadStatic]
static int count;
///<inheritdoc/>
public unsafe ref Memory<T> AsRef(void* source)
{
if (refCache == null)
{
refCache = new (UnmanagedMemoryManager<T>, Memory<T>)[8];
for (int i = 0; i < 8; i++) refCache[i] = (new UnmanagedMemoryManager<T>(), default);
}
count = (count + 1) % 8;
ref var cache = ref refCache[count];
var len = *(int*)source;
cache.Item1.SetDestination((T*)((byte*)source + sizeof(int)), len / sizeof(T));
cache.Item2 = cache.Item1.Memory;
return ref cache.Item2;
}
/// <inheritdoc/>
public unsafe void Initialize(void* source, void* end)
{
*(int*)source = (int)((long)end - (long)source) - sizeof(int);
}
}
/// <summary>
/// Input-specific IVariableLengthStruct implementation for Memory<T> where T is unmanaged, for Memory<T> as input
/// </summary>
| MemoryVarLenStruct |
csharp | EventStore__EventStore | src/Connectors/KurrentDB.Connectors/Planes/Control/ConnectorsActivator.cs | {
"start": 3644,
"end": 4479
} | public record ____(ActivateResultType Type, Exception? Error = null) {
public bool Success => Type is ActivateResultType.Activated;
public bool Failure => !Success;
public static ActivateResult Activated() => new(ActivateResultType.Activated);
public static ActivateResult RevisionAlreadyRunning() => new(ActivateResultType.RevisionAlreadyRunning);
public static ActivateResult InstanceTypeNotFound() => new(ActivateResultType.InstanceTypeNotFound);
public static ActivateResult InvalidConfiguration(ValidationException error) => new(ActivateResultType.InvalidConfiguration, error);
public static ActivateResult UnableToAcquireLock() => new(ActivateResultType.UnableToAcquireLock);
public static ActivateResult UnknownError(Exception error) => new(ActivateResultType.Unknown, error);
}
| ActivateResult |
csharp | ServiceStack__ServiceStack | ServiceStack.Redis/tests/ServiceStack.Redis.Tests/RedisClientHashTests.Async.cs | {
"start": 10586,
"end": 11608
} | public class ____
{
public int Id { get; set; }
public string Name { get; set; }
}
[Test]
public async Task Can_store_as_Hash()
{
var dto = new HashTest { Id = 1 };
await RedisAsync.StoreAsHashAsync(dto);
var storedHash = await RedisAsync.GetHashKeysAsync(dto.ToUrn());
Assert.That(storedHash, Is.EquivalentTo(new[] { "Id" }));
var hold = RedisClient.ConvertToHashFn;
RedisClient.ConvertToHashFn = o =>
{
var map = new Dictionary<string, string>();
o.ToObjectDictionary().Each(x => map[x.Key] = (x.Value ?? "").ToJsv());
return map;
};
await RedisAsync.StoreAsHashAsync(dto);
storedHash = await RedisAsync.GetHashKeysAsync(dto.ToUrn());
Assert.That(storedHash, Is.EquivalentTo(new[] { "Id", "Name" }));
RedisClient.ConvertToHashFn = hold;
}
}
} | HashTest |
csharp | microsoft__PowerToys | src/modules/PowerOCR/PowerOCR/Helpers/ImageMethods.cs | {
"start": 760,
"end": 10043
} | internal sealed class ____
{
internal static Bitmap PadImage(Bitmap image, int minW = 64, int minH = 64)
{
if (image.Height >= minH && image.Width >= minW)
{
return image;
}
int width = Math.Max(image.Width + 16, minW + 16);
int height = Math.Max(image.Height + 16, minH + 16);
// Create a compatible bitmap
Bitmap destination = new(width, height, image.PixelFormat);
using Graphics gd = Graphics.FromImage(destination);
gd.Clear(image.GetPixel(0, 0));
gd.DrawImageUnscaled(image, 8, 8);
return destination;
}
internal static ImageSource GetWindowBoundsImage(OCROverlay passedWindow)
{
Rectangle screenRectangle = passedWindow.GetScreenRectangle();
using Bitmap bmp = new(screenRectangle.Width, screenRectangle.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(screenRectangle.Left, screenRectangle.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
return BitmapToImageSource(bmp);
}
internal static Bitmap GetRegionAsBitmap(OCROverlay passedWindow, Rectangle selectedRegion)
{
Bitmap bmp = new(
selectedRegion.Width,
selectedRegion.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using Graphics g = Graphics.FromImage(bmp);
Rectangle screenRectangle = passedWindow.GetScreenRectangle();
g.CopyFromScreen(
screenRectangle.Left + selectedRegion.Left,
screenRectangle.Top + selectedRegion.Top,
0,
0,
bmp.Size,
CopyPixelOperation.SourceCopy);
bmp = PadImage(bmp);
return bmp;
}
internal static async Task<string> GetRegionsText(OCROverlay? passedWindow, Rectangle selectedRegion, Language? preferredLanguage)
{
if (passedWindow is null)
{
return string.Empty;
}
Bitmap bmp = GetRegionAsBitmap(passedWindow, selectedRegion);
string? resultText = await ExtractText(bmp, preferredLanguage);
return resultText != null ? resultText.Trim() : string.Empty;
}
internal static async Task<string> GetClickedWord(OCROverlay passedWindow, System.Windows.Point clickedPoint, Language? preferredLanguage)
{
Rectangle screenRectangle = passedWindow.GetScreenRectangle();
Bitmap bmp = new((int)screenRectangle.Width, (int)passedWindow.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
System.Windows.Point absPosPoint = passedWindow.GetAbsolutePosition();
g.CopyFromScreen((int)absPosPoint.X, (int)absPosPoint.Y, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
System.Windows.Point adjustedPoint = new(clickedPoint.X, clickedPoint.Y);
string resultText = await ExtractText(bmp, preferredLanguage, adjustedPoint);
return resultText.Trim();
}
internal static readonly char[] Separator = new char[] { '\n', '\r' };
public static async Task<string> ExtractText(Bitmap bmp, Language? preferredLanguage, System.Windows.Point? singlePoint = null)
{
Language? selectedLanguage = preferredLanguage ?? GetOCRLanguage();
if (selectedLanguage == null)
{
return string.Empty;
}
XmlLanguage lang = XmlLanguage.GetLanguage(selectedLanguage.LanguageTag);
CultureInfo culture = lang.GetEquivalentCulture();
bool isSpaceJoiningLang = LanguageHelper.IsLanguageSpaceJoining(selectedLanguage);
bool scaleBMP = true;
if (singlePoint != null
|| bmp.Width * 1.5 > OcrEngine.MaxImageDimension)
{
scaleBMP = false;
}
using Bitmap scaledBitmap = scaleBMP ? ScaleBitmapUniform(bmp, 1.5) : ScaleBitmapUniform(bmp, 1.0);
StringBuilder text = new();
await using MemoryStream memoryStream = new();
using WrappingStream wrappingStream = new(memoryStream);
scaledBitmap.Save(wrappingStream, ImageFormat.Bmp);
wrappingStream.Position = 0;
BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(wrappingStream.AsRandomAccessStream());
SoftwareBitmap softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync();
OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(selectedLanguage);
OcrResult ocrResult = await ocrEngine.RecognizeAsync(softwareBmp);
await memoryStream.DisposeAsync();
await wrappingStream.DisposeAsync();
GC.Collect();
if (singlePoint == null)
{
foreach (OcrLine ocrLine in ocrResult.Lines)
{
ocrLine.GetTextFromOcrLine(isSpaceJoiningLang, text);
}
}
else
{
Windows.Foundation.Point fPoint = new(singlePoint.Value.X, singlePoint.Value.Y);
foreach (OcrLine ocrLine in ocrResult.Lines)
{
foreach (OcrWord ocrWord in ocrLine.Words)
{
if (ocrWord.BoundingRect.Contains(fPoint))
{
_ = text.Append(ocrWord.Text);
}
}
}
}
if (culture.TextInfo.IsRightToLeft)
{
string[] textListLines = text.ToString().Split(Separator);
_ = text.Clear();
foreach (string textLine in textListLines)
{
List<string> wordArray = textLine.Split().ToList();
wordArray.Reverse();
_ = text.Append(string.Join(' ', wordArray));
if (textLine.Length > 0)
{
_ = text.Append('\n');
}
}
return text.ToString();
}
return text.ToString();
}
public static Bitmap ScaleBitmapUniform(Bitmap passedBitmap, double scale)
{
using MemoryStream memoryStream = new();
using WrappingStream wrappingStream = new(memoryStream);
passedBitmap.Save(wrappingStream, ImageFormat.Bmp);
wrappingStream.Position = 0;
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
bitmapImage.StreamSource = wrappingStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
TransformedBitmap transformedBmp = new();
transformedBmp.BeginInit();
transformedBmp.Source = bitmapImage;
transformedBmp.Transform = new ScaleTransform(scale, scale);
transformedBmp.EndInit();
transformedBmp.Freeze();
memoryStream.Dispose();
wrappingStream.Dispose();
GC.Collect();
return BitmapSourceToBitmap(transformedBmp);
}
public static Bitmap BitmapSourceToBitmap(BitmapSource source)
{
Bitmap bmp = new(
source.PixelWidth,
source.PixelHeight,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
BitmapData data = bmp.LockBits(
new Rectangle(System.Drawing.Point.Empty, bmp.Size),
ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
source.CopyPixels(
Int32Rect.Empty,
data.Scan0,
data.Height * data.Stride,
data.Stride);
bmp.UnlockBits(data);
GC.Collect();
return bmp;
}
internal static BitmapImage BitmapToImageSource(Bitmap bitmap)
{
using MemoryStream memoryStream = new();
using WrappingStream wrappingStream = new(memoryStream);
bitmap.Save(wrappingStream, ImageFormat.Bmp);
wrappingStream.Position = 0;
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
bitmapImage.StreamSource = wrappingStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
memoryStream.Dispose();
wrappingStream.Dispose();
GC.Collect();
return bitmapImage;
}
public static Language? GetOCRLanguage()
{
// use currently selected Language
string inputLang = InputLanguageManager.Current.CurrentInputLanguage.Name;
Language? selectedLanguage = new(inputLang);
List<Language> possibleOcrLanguages = OcrEngine.AvailableRecognizerLanguages.ToList();
if (possibleOcrLanguages.Count < 1)
{
MessageBox.Show("No possible OCR languages are installed.", "Text Grab");
return null;
}
if (possibleOcrLanguages.All(l => l.LanguageTag != selectedLanguage.LanguageTag))
{
List<Language>? similarLanguages = possibleOcrLanguages.Where(
la => la.AbbreviatedName == selectedLanguage.AbbreviatedName).ToList();
if (similarLanguages != null)
{
selectedLanguage = similarLanguages.Count > 0
? similarLanguages.FirstOrDefault()
: possibleOcrLanguages.FirstOrDefault();
}
}
return selectedLanguage;
}
}
| ImageMethods |
csharp | moq__moq4 | src/Moq.Tests/SetupFixture.cs | {
"start": 350,
"end": 15818
} | public class ____
{
[Fact]
public void IsMatched_becomes_true_as_soon_as_a_matching_invocation_is_made()
{
var mock = new Mock<object>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
Assert.False(setup.IsMatched);
_ = mock.Object.ToString();
Assert.True(setup.IsMatched);
}
[Fact]
public void IsMatched_of_setup_implicitly_created_by_SetupAllProperties_becomes_true_as_soon_as_matching_invocation_is_made()
{
var mock = new Mock<IX>();
mock.SetupAllProperties();
_ = mock.Object.Property;
var setup = mock.Setups.First();
Assert.True(setup.IsMatched);
}
[Fact]
public void IsMatched_of_setup_implicitly_created_by_multi_dot_expression_becomes_true_as_soon_as_matching_invocation_is_made()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property);
var setup = mock.Setups.First();
Assert.False(setup.IsMatched);
_ = mock.Object.Inner;
Assert.True(setup.IsMatched);
}
[Fact]
public void IsOverridden_does_not_become_true_if_another_setup_with_a_different_expression_is_added_to_the_mock()
{
var mock = new Mock<object>();
mock.Setup(m => m.Equals(1));
var setup = mock.Setups.First();
Assert.False(setup.IsOverridden);
mock.Setup(m => m.Equals(2));
Assert.False(setup.IsOverridden);
}
[Fact]
public void IsOverridden_becomes_true_as_soon_as_another_setup_with_an_equal_expression_is_added_to_the_mock()
{
var mock = new Mock<object>();
mock.Setup(m => m.Equals(1));
var setup = mock.Setups.First();
Assert.False(setup.IsOverridden);
mock.Setup(m => m.Equals(1));
Assert.True(setup.IsOverridden);
}
[Fact]
public void IsVerifiable_becomes_true_if_parameterless_Verifiable_setup_method_is_called()
{
var mock = new Mock<object>();
var setupBuilder = mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
Assert.False(setup.IsVerifiable);
setupBuilder.Verifiable();
Assert.True(setup.IsVerifiable);
}
[Fact]
public void IsVerifiable_becomes_true_if_parameterized_Verifiable_setup_method_is_called()
{
var mock = new Mock<object>();
var setupBuilder = mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
Assert.False(setup.IsVerifiable);
setupBuilder.Verifiable(failMessage: "...");
Assert.True(setup.IsVerifiable);
}
[Fact]
public void OriginalExpression_equal_to_Expression_for_simple_property_access()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner);
var setup = mock.Setups.First();
Assert.Equal(setup.Expression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_equal_to_Expression_for_simple_indexer_access()
{
var mock = new Mock<IX>();
mock.Setup(m => m[1]);
var setup = mock.Setups.First();
Assert.Equal(setup.Expression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_equal_to_Expression_for_simple_method_call()
{
var mock = new Mock<IX>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
Assert.Equal(setup.Expression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_returns_expression_different_from_Expression_for_multi_dot_expression()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.ToString());
var setup = mock.Setups.First();
Assert.NotEqual(setup.Expression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_returns_expression_different_from_Expression_for_multi_dot_expression_in_Mock_Of()
{
var mockObject = Mock.Of<IX>(m => m.Inner.Property == null);
var setup = Mock.Get(mockObject).Setups.First();
Assert.NotEqual(setup.Expression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_returns_whole_multi_dot_expression()
{
Expression<Func<IX, string>> originalExpression = m => m.Inner[1].ToString();
var mock = new Mock<IX>();
mock.Setup(originalExpression);
var setup = mock.Setups.First();
Assert.Equal(originalExpression, setup.OriginalExpression, ExpressionComparer.Default);
}
[Fact]
public void OriginalExpression_same_for_all_partial_setups_resulting_from_it()
{
Expression<Func<IX, string>> originalExpression = m => m.Inner[1].ToString();
var mock = new Mock<IX>();
mock.Setup(originalExpression);
var setups = new List<ISetup>();
for (var setup = mock.Setups.Single(); setup.InnerMock != null; setup = setup.InnerMock.Setups.Single())
{
setups.Add(setup);
}
// (using `HashSet` to automatically filter out duplicates:)
var originalExpressions = new HashSet<Expression>(setups.Select(s => s.OriginalExpression));
Assert.Single(originalExpressions);
}
[Fact]
public void OriginalExpression_is_null_for_implicit_stubbed_property_accessor_setup()
{
var mock = new Mock<IX>();
mock.SetupAllProperties();
_ = mock.Object.Property;
mock.Object.Property = null;
Assert.All(mock.Setups, s => Assert.Null(s.OriginalExpression));
}
[Fact]
public void OriginalExpression_is_null_for_implicit_DefaultValue_Mock_setup()
{
var mock = new Mock<IX>() { DefaultValue = DefaultValue.Mock };
_ = mock.Object.Inner.Property;
var setup = mock.Setups.First();
Assert.Null(setup.OriginalExpression);
}
[Fact]
public void InnerMock_is_null_if_return_value_cannot_be_determined_safely()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner).Returns(() => Mock.Of<IX>());
var setup = mock.Setups.First();
Assert.Null(setup.InnerMock);
}
[Fact]
public void InnerMock_is_null_if_return_value_can_be_determined_but_is_not_a_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner).Returns((IX)null);
var setup = mock.Setups.First();
Assert.Null(setup.InnerMock);
}
[Fact]
public void InnerMock_is_set_if_return_value_can_be_determined_and_is_a_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner).Returns(Mock.Of<IX>());
var setup = mock.Setups.First();
Assert.IsAssignableFrom<Mock<IX>>(setup.InnerMock);
}
[Fact]
public void InnerMock_is_set_if_Task_async_return_value_can_be_determined_and_is_a_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.GetInnerTaskAsync()).Returns(Task.FromResult<IX>(Mock.Of<IX>()));
var setup = mock.Setups.First();
Assert.IsAssignableFrom<Mock<IX>>(setup.InnerMock);
}
[Fact]
public void InnerMock_is_set_if_ValueTask_async_return_value_can_be_determined_and_is_a_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.GetInnerValueTaskAsync()).Returns(new ValueTask<IX>(Mock.Of<IX>()));
var setup = mock.Setups.First();
Assert.IsAssignableFrom<Mock<IX>>(setup.InnerMock);
}
[Fact]
public void InnerMock_returns_correct_inner_mock_explicitly_setup_up()
{
var expectedInnerMock = new Mock<IX>();
var mock = new Mock<IX>();
mock.Setup(m => m.Inner).Returns(expectedInnerMock.Object);
var setup = mock.Setups.First();
Assert.Same(expectedInnerMock, setup.InnerMock);
}
[Fact]
public void InnerMock_returns_correct_inner_mock_implicitly_setup_up_via_multi_dot_expression()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property);
var setup = mock.Setups.First();
var expectedInnerMock = Mock.Get(mock.Object.Inner);
Assert.Same(expectedInnerMock, setup.InnerMock);
}
[Fact]
public void Verify_fails_on_unmatched_setup_even_when_not_flagged_as_verifiable()
{
var mock = new Mock<object>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
Assert.False(setup.IsVerifiable); // the root setup should be verified despite this
Assert.False(setup.IsMatched);
Assert.Throws<MockException>(() => setup.Verify());
}
[Fact]
public void Verify_succeeds_on_matched_setup()
{
var mock = new Mock<object>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
_ = mock.Object.ToString();
Assert.False(setup.IsVerifiable);
Assert.True(setup.IsMatched);
setup.Verify();
}
[Fact]
public void Verify_fails_on_matched_setup_having_unmatched_verifiable_setup_on_inner_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property).Verifiable();
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
var innerMockSetup = Mock.Get(innerMock).Setups.First();
Assert.True(setup.IsMatched);
Assert.True(innerMockSetup.IsVerifiable);
Assert.False(innerMockSetup.IsMatched); // this should make recursive verification fail
Assert.Throws<MockException>(() => setup.Verify());
}
[Fact]
public void Verify_succeeds_on_matched_setup_having_unmatched_setup_on_inner_mock()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property);
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
var innerMockSetup = Mock.Get(innerMock).Setups.First();
Assert.True(setup.IsMatched);
Assert.False(innerMockSetup.IsVerifiable); // which means that the inner mock setup will be ignored
Assert.False(innerMockSetup.IsMatched); // this would make verification fail if that setup were not ignored
setup.Verify();
}
[Fact]
public void Verify_succeeds_on_matched_setup_having_unmatched_verifiable_setup_on_inner_mock_if_recursive_set_to_false()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property).Verifiable();
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
var innerMockSetup = Mock.Get(innerMock).Setups.First();
Assert.True(setup.IsMatched);
Assert.True(innerMockSetup.IsVerifiable);
Assert.False(innerMockSetup.IsMatched);
setup.Verify(recursive: false); // which means that verification will never get to `innerMockSetup`
}
[Fact]
public void VerifyAll_is_always_recursive()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property).Verifiable();
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
var innerMockSetup = Mock.Get(innerMock).Setups.First();
Assert.True(setup.IsMatched);
Assert.False(innerMockSetup.IsMatched); // this will make verification fail only if it is recursive
Assert.Throws<MockException>(() => setup.VerifyAll());
}
[Fact]
public void VerifyAll_includes_non_verifiable_setups()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property);
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
var innerMockSetup = Mock.Get(innerMock).Setups.First();
Assert.True(setup.IsMatched);
Assert.False(innerMockSetup.IsVerifiable); // this should not exclude the inner mock setup from verification
Assert.Throws<MockException>(() => setup.VerifyAll());
}
[Fact]
public void Verify_marks_invocations_matched_by_setup_as_verified()
{
var mock = new Mock<object>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
_ = mock.Object.ToString();
_ = mock.Object.ToString();
Assert.All(mock.Invocations, i => Assert.False(i.IsVerified));
setup.Verify();
Assert.All(mock.Invocations, i => Assert.True(i.IsVerified));
mock.VerifyNoOtherCalls();
}
[Fact]
public void VerifyAll_marks_invocations_matched_by_setup_as_verified()
{
var mock = new Mock<object>();
mock.Setup(m => m.ToString());
var setup = mock.Setups.First();
_ = mock.Object.ToString();
_ = mock.Object.ToString();
Assert.All(mock.Invocations, i => Assert.False(i.IsVerified));
setup.VerifyAll();
Assert.All(mock.Invocations, i => Assert.True(i.IsVerified));
mock.VerifyNoOtherCalls();
}
[Fact]
public void Verify_marks_invocation_matched_by_verifiable_inner_mock_setup_as_verified()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property).Verifiable();
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
_ = innerMock.Property;
var innerMockInvocation = Mock.Get(innerMock).Invocations.First();
Assert.False(innerMockInvocation.IsVerified);
setup.Verify();
Assert.True(innerMockInvocation.IsVerified);
mock.VerifyNoOtherCalls();
}
[Fact]
public void VerifyAll_marks_invocation_matched_by_inner_mock_setup_as_verified()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Inner.Property);
var setup = mock.Setups.First();
var innerMock = mock.Object.Inner;
_ = innerMock.Property;
var innerMockInvocation = Mock.Get(innerMock).Invocations.First();
Assert.False(innerMockInvocation.IsVerified);
setup.VerifyAll();
Assert.True(innerMockInvocation.IsVerified);
mock.VerifyNoOtherCalls();
}
| SetupFixture |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3095601,
"end": 3095982
} | public partial interface ____ : IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes, IDirectiveLocationAdded
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_DirectiveLocationAdded |
csharp | FluentValidation__FluentValidation | src/FluentValidation/Validators/IPropertyValidator.cs | {
"start": 1904,
"end": 2106
} | interface ____ not be implemented directly in your code as it is subject to change.
/// Please inherit from <see cref="PropertyValidator{T,TProperty}">PropertyValidator</see> instead.
/// </summary>
| should |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/ModelBinding/Metadata/MetadataDetailsProviderExtensions.cs | {
"start": 310,
"end": 1621
} | public static class ____
{
/// <summary>
/// Removes all metadata details providers of the specified type.
/// </summary>
/// <param name="list">The list of <see cref="IMetadataDetailsProvider"/>s.</param>
/// <typeparam name="TMetadataDetailsProvider">The type to remove.</typeparam>
public static void RemoveType<TMetadataDetailsProvider>(this IList<IMetadataDetailsProvider> list) where TMetadataDetailsProvider : IMetadataDetailsProvider
{
ArgumentNullException.ThrowIfNull(list);
RemoveType(list, typeof(TMetadataDetailsProvider));
}
/// <summary>
/// Removes all metadata details providers of the specified type.
/// </summary>
/// <param name="list">The list of <see cref="IMetadataDetailsProvider"/>s.</param>
/// <param name="type">The type to remove.</param>
public static void RemoveType(this IList<IMetadataDetailsProvider> list, Type type)
{
ArgumentNullException.ThrowIfNull(list);
ArgumentNullException.ThrowIfNull(type);
for (var i = list.Count - 1; i >= 0; i--)
{
var metadataDetailsProvider = list[i];
if (metadataDetailsProvider.GetType() == type)
{
list.RemoveAt(i);
}
}
}
}
| MetadataDetailsProviderExtensions |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/Menus/MenuItemConsts.cs | {
"start": 31,
"end": 220
} | public static class ____
{
public const int MaxDisplayNameLength = 64;
public const int MaxUrlLength = 1024;
public const int MaxRequiredPermissionNameLength = 128;
}
| MenuItemConsts |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/InterfaceTests.cs | {
"start": 13739,
"end": 15047
} | interface ____ {
value: String
}
type ConcreteTypeB implements SomeInterface {
value: String
specificToB: String
}
""");
using var gateway = await CreateCompositeSchemaAsync(
[
("A", server1),
("B", server2)
]);
// act
using var client = GraphQLHttpClient.Create(gateway.CreateClient());
var request = new OperationRequest(
"""
{
someField {
value
... on ConcreteTypeA {
specificToA
}
... on ConcreteTypeB {
specificToB
}
}
}
""");
using var result = await client.PostAsync(
request,
new Uri("http://localhost:5000/graphql"));
// assert
await MatchSnapshotAsync(gateway, request, result);
}
[Fact]
public async Task Interface_Field_With_Only_Type_Refinements_Exclusive_To_Other_Schema()
{
// arrange
var server1 = CreateSourceSchema(
"A",
"""
type Query {
someField: SomeInterface
}
| SomeInterface |
csharp | dotnet__orleans | src/Orleans.Runtime/Configuration/Options/DeploymentLoadPublisherOptions.cs | {
"start": 150,
"end": 556
} | public class ____
{
/// <summary>
/// Interval in which deployment statistics are published.
/// </summary>
public TimeSpan DeploymentLoadPublisherRefreshTime { get; set; } = DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME;
public static readonly TimeSpan DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME = TimeSpan.FromSeconds(1);
}
} | DeploymentLoadPublisherOptions |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/Internal/HalfSerializerTest.cs | {
"start": 412,
"end": 4875
} | public class ____
{
#pragma warning disable IDE0044 // Spurious suggestion to add readonly. Not appropriate because this is passed by ref
private int _wip;
#pragma warning restore IDE0044
private Exception _error;
private readonly Consumer _consumer = new();
[TestMethod]
public void HalfSerializer_OnNext()
{
HalfSerializer.ForwardOnNext(_consumer, 1, ref _wip, ref _error);
Assert.Equal(0, _wip);
Assert.Null(_error);
Assert.Equal(1, _consumer.Items.Count);
Assert.Equal(1, _consumer.Items[0]);
Assert.Equal(0, _consumer.Done);
Assert.Null(_consumer.Exc);
}
[TestMethod]
public void HalfSerializer_OnError()
{
var ex = new InvalidOperationException();
HalfSerializer.ForwardOnError(_consumer, ex, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
HalfSerializer.ForwardOnNext(_consumer, 2, ref _wip, ref _error);
Assert.Equal(0, _consumer.Items.Count);
Assert.Equal(0, _consumer.Done);
Assert.Equal(ex, _consumer.Exc);
}
[TestMethod]
public void HalfSerializer_OnError_Ignore_Further_Events()
{
var ex = new InvalidOperationException();
HalfSerializer.ForwardOnError(_consumer, ex, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
HalfSerializer.ForwardOnNext(_consumer, 2, ref _wip, ref _error);
var ex2 = new NotSupportedException();
HalfSerializer.ForwardOnError(_consumer, ex2, ref _wip, ref _error);
HalfSerializer.ForwardOnCompleted(_consumer, ref _wip, ref _error);
Assert.Equal(0, _consumer.Items.Count);
Assert.Equal(0, _consumer.Done);
Assert.Equal(ex, _consumer.Exc);
}
[TestMethod]
public void HalfSerializer_OnCompleted()
{
HalfSerializer.ForwardOnCompleted(_consumer, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
HalfSerializer.ForwardOnNext(_consumer, 2, ref _wip, ref _error);
Assert.Equal(0, _consumer.Items.Count);
Assert.Equal(1, _consumer.Done);
Assert.Null(_consumer.Exc);
}
[TestMethod]
public void HalfSerializer_OnCompleted_Ignore_Further_Events()
{
HalfSerializer.ForwardOnCompleted(_consumer, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
HalfSerializer.ForwardOnNext(_consumer, 2, ref _wip, ref _error);
var ex2 = new NotSupportedException();
HalfSerializer.ForwardOnError(_consumer, ex2, ref _wip, ref _error);
HalfSerializer.ForwardOnCompleted(_consumer, ref _wip, ref _error);
Assert.Equal(0, _consumer.Items.Count);
Assert.Equal(1, _consumer.Done);
Assert.Null(_consumer.Exc);
}
// Practically simulates concurrent invocation of the HalfSerializer methods
[TestMethod]
public void HalfSerializer_OnNext_Reentrant_Error()
{
var c = new ReentrantConsumer(this, true);
HalfSerializer.ForwardOnNext(c, 1, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
Assert.Equal(1, _consumer.Items.Count);
Assert.Equal(1, _consumer.Items[0]);
Assert.Equal(0, _consumer.Done);
Assert.Equal(c.X, _consumer.Exc);
}
// Practically simulates concurrent invocation of the HalfSerializer methods
[TestMethod]
public void HalfSerializer_OnNext_Reentrant_OnCompleted()
{
var c = new ReentrantConsumer(this, false);
HalfSerializer.ForwardOnNext(c, 1, ref _wip, ref _error);
Assert.Equal(1, _wip);
Assert.Equal(_error, ExceptionHelper.Terminated);
Assert.Equal(1, _consumer.Items.Count);
Assert.Equal(1, _consumer.Items[0]);
Assert.Equal(1, _consumer.Done);
Assert.Null(_consumer.Exc);
}
| HalfSerializerTest |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/Maui25141.xaml.cs | {
"start": 956,
"end": 1459
} | public class ____ : INotifyPropertyChanged
{
private bool _triggerFlag;
public bool TriggerFlag
{
get => _triggerFlag;
set
{
_triggerFlag = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TriggerFlag)));
}
}
private string _text;
public string Text
{
get => _text;
set
{
_text = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
| Maui25141ViewModel |
csharp | atata-framework__atata | src/Atata/UIComponentResolver.cs | {
"start": 19,
"end": 23248
} | public static class ____
{
private static readonly LockingConcurrentDictionary<ICustomAttributeProvider, Attribute[]> s_propertyAttributes =
new(ResolveAttributes);
private static readonly LockingConcurrentDictionary<Type, Attribute[]> s_classAttributes =
new(ResolveClassAttributes);
private static readonly LockingConcurrentDictionary<ICustomAttributeProvider, Attribute[]> s_assemblyAttributes =
new(ResolveAttributes);
private static readonly LockingConcurrentDictionary<Type, string> s_pageObjectNames =
new(ResolvePageObjectNameFromMetadata);
private static readonly ConcurrentDictionary<Type, Type> s_delegateControlsTypeMapping =
new()
{
[typeof(ClickableDelegate<>)] = typeof(Clickable<>),
[typeof(ClickableDelegate<,>)] = typeof(Clickable<,>),
[typeof(LinkDelegate<>)] = typeof(Link<>),
[typeof(LinkDelegate<,>)] = typeof(Link<,>),
[typeof(ButtonDelegate<>)] = typeof(Button<>),
[typeof(ButtonDelegate<,>)] = typeof(Button<,>)
};
private static readonly ConcurrentDictionary<Delegate, UIComponent> s_delegateControls =
new();
public static void RegisterDelegateControlMapping(Type delegateType, Type controlType) =>
s_delegateControlsTypeMapping[delegateType] = controlType;
public static void Resolve<TOwner>(UIComponent<TOwner> component)
where TOwner : PageObject<TOwner>
{
Type[] allTypes = [.. GetAllInheritedTypes(component.GetType()).Reverse()];
foreach (Type type in allTypes)
InitComponentTypeMembers(component, type);
}
private static IEnumerable<Type> GetAllInheritedTypes(Type type)
{
Type typeToCheck = type;
while (
typeToCheck != typeof(UIComponent) &&
(!typeToCheck.IsGenericType || (typeToCheck.GetGenericTypeDefinition() != typeof(UIComponent<>) && typeToCheck.GetGenericTypeDefinition() != typeof(PageObject<>))))
{
yield return typeToCheck;
typeToCheck = typeToCheck.BaseType;
}
}
// TODO: Refactor InitComponentTypeMembers method.
private static void InitComponentTypeMembers<TOwner>(UIComponent<TOwner> component, Type type)
where TOwner : PageObject<TOwner>
{
PropertyInfo[] suitableProperties = type
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty)
.Where(x => x.CanWrite && x.GetIndexParameters().Length == 0)
.Where(x => x.GetCustomAttribute<IgnoreInitAttribute>() == null)
.ToArray();
bool IsNullPropertyPredicate(PropertyInfo property) =>
property.GetValue(component) == null;
PropertyInfo[] controlProperties = suitableProperties
.Where(x => x.PropertyType.IsSubclassOfRawGeneric(typeof(Control<>)))
.Where(IsNullPropertyPredicate)
.ToArray();
foreach (var property in controlProperties)
InitControlProperty(component, property);
PropertyInfo[] componentPartProperties = suitableProperties
.Where(x => x.PropertyType.IsSubclassOfRawGeneric(typeof(UIComponentPart<>)))
.Where(IsNullPropertyPredicate)
.ToArray();
foreach (var property in componentPartProperties)
InitComponentPartProperty(component, property);
PropertyInfo[] delegateProperties = suitableProperties
.Where(x => typeof(MulticastDelegate).IsAssignableFrom(x.PropertyType.BaseType) && x.PropertyType.IsGenericType)
.Where(IsNullPropertyPredicate)
.ToArray();
foreach (var property in delegateProperties)
InitDelegateProperty(component, property);
}
private static void InitControlProperty<TOwner>(UIComponent<TOwner> parentComponent, PropertyInfo property)
where TOwner : PageObject<TOwner>
{
UIComponentMetadata metadata = CreateStaticControlMetadata(parentComponent, property);
UIComponent<TOwner> component = CreateComponent(parentComponent, metadata);
parentComponent.Controls.Add(component);
property.SetValue(parentComponent, component, null);
}
private static void InitDelegateProperty<TOwner>(UIComponent<TOwner> parentComponent, PropertyInfo property)
where TOwner : PageObject<TOwner>
{
Type? controlType = ResolveDelegateControlType(property.PropertyType);
if (controlType is not null)
{
UIComponentMetadata metadata = CreateStaticControlMetadata(parentComponent, property, controlType);
UIComponent<TOwner> component = CreateComponent(parentComponent, metadata);
parentComponent.Controls.Add(component);
Delegate clickDelegate = CreateDelegatePropertyDelegate(property, component);
property.SetValue(parentComponent, clickDelegate, null);
s_delegateControls[clickDelegate] = component;
}
}
private static Delegate CreateDelegatePropertyDelegate<TOwner>(PropertyInfo property, UIComponent<TOwner> component)
where TOwner : PageObject<TOwner>
{
Type navigableInterfaceType = component.GetType().GetGenericInterfaceType(typeof(INavigable<,>));
if (navigableInterfaceType != null)
{
var navigableGenericArguments = navigableInterfaceType.GetGenericArguments();
var clickAndGoMethod = typeof(INavigableExtensions)
.GetMethod(nameof(INavigableExtensions.ClickAndGo))
.MakeGenericMethod(navigableGenericArguments);
return Delegate.CreateDelegate(property.PropertyType, component, clickAndGoMethod);
}
else
{
return Delegate.CreateDelegate(property.PropertyType, component, "Click");
}
}
private static void InitComponentPartProperty<TOwner>(UIComponent<TOwner> parentComponent, PropertyInfo property)
where TOwner : PageObject<TOwner>
{
UIComponentPart<TOwner> componentPart = (UIComponentPart<TOwner>)ActivatorEx.CreateInstance(property.PropertyType);
componentPart.Component = parentComponent;
componentPart.ComponentPartName = property.Name.ToString(TermCase.MidSentence);
if (componentPart is ISupportsMetadata supportsMetadata)
{
supportsMetadata.Metadata = CreateStaticControlMetadata(parentComponent, property, supportsMetadata.ComponentType);
string? nameFromMetadata = GetControlNameFromNameAttribute(supportsMetadata.Metadata);
if (nameFromMetadata is not null)
componentPart.ComponentPartName = nameFromMetadata;
}
if (componentPart is IClearsCache cacheClearableComponentPart)
parentComponent.CacheClearableComponentParts.Add(cacheClearableComponentPart);
property.SetValue(parentComponent, componentPart, null);
}
private static Type? ResolveDelegateControlType(Type delegateType)
{
Type delegateGenericTypeDefinition = delegateType.GetGenericTypeDefinition();
if (s_delegateControlsTypeMapping.TryGetValue(delegateGenericTypeDefinition, out Type controlGenericTypeDefinition))
{
Type[] genericArguments = delegateType.GetGenericArguments();
return controlGenericTypeDefinition.MakeGenericType(genericArguments);
}
return null;
}
public static TComponentPart CreateComponentPart<TComponentPart, TOwner>(UIComponent<TOwner> parentComponent, string name, params Attribute[] attributes)
where TComponentPart : UIComponentPart<TOwner>
where TOwner : PageObject<TOwner>
{
Guard.ThrowIfNull(parentComponent);
Guard.ThrowIfNull(name);
TComponentPart componentPart = ActivatorEx.CreateInstance<TComponentPart>();
componentPart.Component = parentComponent;
componentPart.ComponentPartName = name;
attributes = attributes?.Where(x => x != null).ToArray() ?? [];
if (componentPart is ISupportsMetadata supportsMetadata)
{
supportsMetadata.Metadata = CreateComponentMetadata(
parentComponent,
name,
supportsMetadata.ComponentType,
attributes);
string? nameFromMetadata = GetControlNameFromNameAttribute(supportsMetadata.Metadata);
if (nameFromMetadata is not null)
componentPart.ComponentPartName = nameFromMetadata;
}
return componentPart;
}
public static TComponent CreateControl<TComponent, TOwner>(UIComponent<TOwner> parentComponent, string? name, params Attribute[] attributes)
where TComponent : UIComponent<TOwner>
where TOwner : PageObject<TOwner>
{
Guard.ThrowIfNull(parentComponent);
attributes = attributes?.Where(x => x != null).ToArray() ?? [];
if (!attributes.OfType<NameAttribute>().Any() && name is not null)
{
attributes =
[
.. attributes,
new NameAttribute(name)
];
}
UIComponentMetadata metadata = CreateComponentMetadata(
parentComponent,
name,
typeof(TComponent),
attributes);
return (TComponent)CreateComponent(parentComponent, metadata);
}
public static TComponent CreateControlForProperty<TComponent, TOwner>(UIComponent<TOwner> parentComponent, string propertyName, params Attribute[] attributes)
where TComponent : UIComponent<TOwner>
where TOwner : PageObject<TOwner>
{
PropertyInfo property = parentComponent.GetType().GetPropertyWithThrowOnError(propertyName, typeof(TComponent), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
UIComponentMetadata metadata = CreateStaticControlMetadata(parentComponent, property);
if (attributes != null)
metadata.Push(attributes);
var component = (TComponent)CreateComponent(parentComponent, metadata);
parentComponent.Controls.Add(component);
return component;
}
private static UIComponent<TOwner> CreateComponent<TOwner>(UIComponent<TOwner> parentComponent, UIComponentMetadata metadata)
where TOwner : PageObject<TOwner>
{
UIComponent<TOwner> component = (UIComponent<TOwner>)ActivatorEx.CreateInstance(metadata.ComponentType);
InitComponent(component, parentComponent, metadata);
Resolve(component);
return component;
}
private static void InitComponent<TOwner>(UIComponent<TOwner> component, UIComponent<TOwner> parentComponent, UIComponentMetadata metadata)
where TOwner : PageObject<TOwner>
{
component.Owner = parentComponent.Owner ?? (TOwner)parentComponent;
component.Parent = parentComponent;
InitComponentLocator(component);
component.ComponentName = ResolveControlName(metadata);
component.ComponentTypeName = ResolveControlTypeName(metadata);
component.Metadata = metadata;
}
private static void InitComponentLocator(UIComponent component) =>
component.ScopeLocator = new StrategyScopeLocator(
new StrategyScopeLocatorExecutionDataCollector(component),
StrategyScopeLocatorExecutor.Default);
private static string ResolveControlName(UIComponentMetadata metadata) =>
GetControlNameFromNameAttribute(metadata)
?? GetControlNameFromFindAttribute(metadata)
?? GetComponentNameFromMetadata(metadata);
private static string? GetControlNameFromNameAttribute(UIComponentMetadata metadata)
{
NameAttribute? nameAttribute = metadata.Get<NameAttribute>();
return nameAttribute is not null && !string.IsNullOrWhiteSpace(nameAttribute.Value)
? nameAttribute.Value
: null;
}
private static string? GetControlNameFromFindAttribute(UIComponentMetadata metadata)
{
FindAttribute findAttribute = metadata.ResolveFindAttribute();
if (findAttribute is FindByLabelAttribute findByLabelAttribute && findByLabelAttribute.Match == TermMatch.Equals)
{
string[]? terms = findByLabelAttribute.ResolveValues(metadata);
if (terms?.Length > 0)
{
return string.Join("/", terms);
}
}
return null;
}
private static string GetComponentNameFromMetadata(UIComponentMetadata metadata)
{
if (metadata.Name is null)
{
FindAttribute findAttribute = metadata.ResolveFindAttribute();
return findAttribute.BuildComponentName(metadata);
}
else
{
return metadata.ComponentDefinitionAttribute
.NormalizeNameIgnoringEnding(metadata.Name)
.ToString(TermCase.Title);
}
}
private static UIComponentMetadata CreateStaticControlMetadata<TOwner>(
UIComponent<TOwner> parentComponent,
PropertyInfo property,
Type? propertyType = null)
where TOwner : PageObject<TOwner>
=>
CreateComponentMetadata(
parentComponent,
property.Name,
propertyType ?? property.PropertyType,
GetPropertyAttributes(property));
private static UIComponentMetadata CreateComponentMetadata<TOwner>(
UIComponent<TOwner>? parentComponent,
string? name,
Type componentType,
Attribute[] declaredAttributes)
where TOwner : PageObject<TOwner>
{
Type? parentComponentType = parentComponent?.GetType();
UIComponentMetadata metadata = new(name, componentType, parentComponentType);
AtataAttributesContext contextAttributes = (parentComponent?.Session?.Context ?? AtataContext.ResolveCurrent()).Attributes;
// Declared:
metadata.DeclaredAttributesList.AddRange(declaredAttributes);
if (parentComponent is not null && name is not null)
{
var propertyContextAttributes = contextAttributes.PropertyMap
.Where(x => x.Key.PropertyName == name)
.Select(pair => new { Depth = parentComponentType!.GetDepthOfInheritance(pair.Key.Type), Attributes = pair.Value })
.Where(x => x.Depth != null)
.OrderBy(x => x.Depth)
.SelectMany(x => x.Attributes.AsEnumerable().Reverse());
metadata.DeclaredAttributesList.InsertRange(0, propertyContextAttributes);
// Parent:
metadata.ParentDeclaredAttributesList = parentComponent.Metadata.DeclaredAttributesList;
metadata.ParentComponentAttributesList = parentComponent.Metadata.ComponentAttributesList;
}
Assembly ownerAssembly = typeof(TOwner).Assembly;
FillComponentMetadata(metadata, contextAttributes, ownerAssembly);
return metadata;
}
internal static void FillComponentMetadata(
UIComponentMetadata metadata,
AtataAttributesContext contextAttributes,
Assembly ownerAssembly)
{
// Assembly:
if (contextAttributes.AssemblyMap.TryGetValue(ownerAssembly, out var contextAssemblyAttributes))
metadata.AssemblyAttributesList.AddRange(contextAssemblyAttributes.AsEnumerable().Reverse());
metadata.AssemblyAttributesList.AddRange(GetAssemblyAttributes(ownerAssembly));
// Global:
metadata.GlobalAttributesList.AddRange(contextAttributes.Global.AsEnumerable().Reverse());
// Component:
Type componentType = metadata.ComponentType;
var componentContextAttributes = contextAttributes.ComponentMap
.Select(pair => new { Depth = componentType.GetDepthOfInheritance(pair.Key), Attributes = pair.Value })
.Where(x => x.Depth != null)
.OrderBy(x => x.Depth)
.SelectMany(x => x.Attributes.AsEnumerable().Reverse());
metadata.ComponentAttributesList.AddRange(componentContextAttributes);
metadata.ComponentAttributesList.AddRange(GetClassAttributes(componentType));
}
private static Attribute[] ResolveAndCacheAttributes(LockingConcurrentDictionary<ICustomAttributeProvider, Attribute[]> cache, ICustomAttributeProvider attributeProvider)
{
if (attributeProvider == null)
return [];
return cache.GetOrAdd(attributeProvider);
}
private static Attribute[] GetPropertyAttributes(PropertyInfo property) =>
ResolveAndCacheAttributes(s_propertyAttributes, property);
private static Attribute[] GetClassAttributes(Type type) =>
s_classAttributes.GetOrAdd(type);
private static Attribute[] ResolveAttributes(ICustomAttributeProvider attributeProvider) =>
attributeProvider.GetCustomAttributes(true)
.Cast<Attribute>()
.ToArray();
private static Attribute[] ResolveClassAttributes(Type type)
{
var classOwnAttributes = type.GetCustomAttributes(false).Cast<Attribute>();
return (type.BaseType == null || type.BaseType == typeof(object)
? classOwnAttributes
: classOwnAttributes.Concat(GetClassAttributes(type.BaseType)))
.ToArray();
}
private static Attribute[] GetAssemblyAttributes(Assembly assembly) =>
ResolveAndCacheAttributes(s_assemblyAttributes, assembly);
public static string ResolvePageObjectFullName<TPageObject>()
where TPageObject : PageObject<TPageObject>
=>
$"\"{ResolvePageObjectName<TPageObject>()}\" {ResolvePageObjectTypeName<TPageObject>()}";
public static string ResolvePageObjectName<TPageObject>()
where TPageObject : PageObject<TPageObject>
=>
s_pageObjectNames.GetOrAdd(typeof(TPageObject));
private static string ResolvePageObjectNameFromMetadata(Type type)
{
NameAttribute nameAttribute = GetClassAttributes(type).OfType<NameAttribute>().FirstOrDefault();
return nameAttribute?.Value?.Length > 0
? nameAttribute.Value
: ResolvePageObjectNameFromType(type);
}
private static string ResolvePageObjectNameFromType(Type type)
{
string typeName = NormalizeTypeName(type);
return GetPageObjectDefinition(type)
.NormalizeNameIgnoringEnding(typeName)
.ToString(TermCase.Title);
}
public static string ResolvePageObjectTypeName<TPageObject>()
where TPageObject : PageObject<TPageObject>
=>
GetPageObjectDefinition(typeof(TPageObject)).ComponentTypeName ?? "page object";
public static string ResolveControlTypeName<TControl>()
where TControl : UIComponent
=>
ResolveControlTypeName(typeof(TControl));
public static string ResolveControlTypeName(Type type)
{
ControlDefinitionAttribute controlDefinitionAttribute = GetControlDefinition(type);
return ResolveControlTypeName(controlDefinitionAttribute, type);
}
public static string ResolveControlTypeName(UIComponentMetadata metadata)
{
ControlDefinitionAttribute controlDefinitionAttribute = GetControlDefinition(metadata);
return ResolveControlTypeName(controlDefinitionAttribute, metadata.ComponentType);
}
public static string ResolveControlTypeName(ControlDefinitionAttribute controlDefinitionAttribute, Type controlType) =>
controlDefinitionAttribute.ComponentTypeName
?? NormalizeTypeName(controlType).ToString(TermCase.MidSentence);
public static string ResolveControlName<TControl, TOwner>(Expression<Func<TControl, bool>> predicateExpression)
where TControl : Control<TOwner>
where TOwner : PageObject<TOwner>
=>
$"[{ObjectExpressionStringBuilder.ExpressionToString(predicateExpression)}]";
private static string NormalizeTypeName(Type type)
{
string typeName = type.Name;
return typeName.Contains("`")
? typeName[..typeName.IndexOf('`')]
: typeName;
}
public static string? ResolveComponentFullName<TOwner>(object? component)
where TOwner : PageObject<TOwner>
=>
component is IUIComponent<TOwner> uiComponent
? uiComponent.ComponentFullName
: component is UIComponentPart<TOwner> uiComponentPart
? $"{uiComponentPart.Component.ComponentFullName} {uiComponentPart.ComponentPartName}"
: component is IObjectProvider<object, TOwner> objectProvider
? objectProvider.ProviderName
: null;
public static ControlDefinitionAttribute GetControlDefinition(Type type) =>
GetClassAttributes(type).OfType<ControlDefinitionAttribute>().FirstOrDefault() ?? new ControlDefinitionAttribute();
public static ControlDefinitionAttribute GetControlDefinition(UIComponentMetadata metadata) =>
(metadata.ComponentDefinitionAttribute as ControlDefinitionAttribute) ?? new ControlDefinitionAttribute();
public static PageObjectDefinitionAttribute GetPageObjectDefinition(Type type) =>
GetClassAttributes(type).OfType<PageObjectDefinitionAttribute>().FirstOrDefault() ?? new PageObjectDefinitionAttribute();
public static PageObjectDefinitionAttribute GetPageObjectDefinition(UIComponentMetadata metadata) =>
(metadata.ComponentDefinitionAttribute as PageObjectDefinitionAttribute) ?? new PageObjectDefinitionAttribute();
internal static Control<TOwner> GetControlByDelegate<TOwner>(Delegate controlDelegate)
where TOwner : PageObject<TOwner>
{
Guard.ThrowIfNull(controlDelegate);
if (s_delegateControls.TryGetValue(controlDelegate, out UIComponent control))
return (Control<TOwner>)control;
else
throw new ArgumentException($"Failed to find mapped control by specified '{nameof(controlDelegate)}'.", nameof(controlDelegate));
}
public static Control<TOwner> GetChildControl<TOwner>(IUIComponent<TOwner> parent, string controlName)
where TOwner : PageObject<TOwner>
{
PropertyInfo property = typeof(TOwner).GetPropertyWithThrowOnError(controlName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty);
if (!property.PropertyType.IsSubclassOfRawGeneric(typeof(Control<>)))
throw new InvalidOperationException($"Incorrect type of \"{controlName}\" property.");
return (Control<TOwner>)property.GetValue(parent);
}
public static void CleanUpPageObjects(IEnumerable<UIComponent> pageObjects)
{
foreach (var item in pageObjects)
CleanUpPageObject(item);
}
public static void CleanUpPageObject(UIComponent pageObject)
{
var delegatesToRemove = s_delegateControls.Where(x => x.Value.Owner == pageObject).Select(x => x.Key).ToArray();
foreach (var item in delegatesToRemove)
s_delegateControls.TryRemove(item, out _);
pageObject.CleanUp();
}
}
| UIComponentResolver |
csharp | unoplatform__uno | src/Uno.UWP/Devices/Sensors/Helpers/INativeHingeAngleSensor.cs | {
"start": 243,
"end": 386
} | public interface ____
{
bool DeviceHasHinge { get; }
event EventHandler<NativeHingeAngleReading> ReadingChanged;
}
}
| INativeHingeAngleSensor |
csharp | abpframework__abp | modules/blogging/src/Volo.Blogging.Web/Pages/Blogs/Index.cshtml.cs | {
"start": 279,
"end": 1297
} | public class ____ : AbpPageModel
{
private readonly IBlogAppService _blogAppService;
private readonly BloggingUrlOptions _blogOptions;
public IReadOnlyList<BlogDto> Blogs { get; private set; }
public IndexModel(IBlogAppService blogAppService, IOptions<BloggingUrlOptions> blogOptions)
{
_blogAppService = blogAppService;
_blogOptions = blogOptions.Value;
}
public virtual async Task<IActionResult> OnGetAsync()
{
if (_blogOptions.SingleBlogMode.Enabled)
{
return RedirectToPage("./Posts/Index");
}
var result = await _blogAppService.GetListAsync();
if (result.Items.Count == 1)
{
var blog = result.Items[0];
return RedirectToPage("./Posts/Index", new { blogShortName = blog.ShortName });
}
Blogs = result.Items;
return Page();
}
}
}
| IndexModel |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/Converters/Corners.cs | {
"start": 202,
"end": 729
} | public enum ____
{
/// <summary>
/// No corner.
/// </summary>
None,
/// <summary>
/// The TopLeft corner.
/// </summary>
TopLeft = 1,
/// <summary>
/// The TopRight corner.
/// </summary>
TopRight = 2,
/// <summary>
/// The BottomLeft corner.
/// </summary>
BottomLeft = 4,
/// <summary>
/// The BottomRight corner.
/// </summary>
BottomRight = 8
}
}
| Corners |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/Interfaces/ICompletable.cs | {
"start": 57,
"end": 191
} | internal interface ____
{
void AppendStormLog(StringBuilder sb);
bool TryComplete(bool isAsync);
}
}
| ICompletable |
csharp | SixLabors__ImageSharp | src/ImageSharp/Metadata/Profiles/ICC/Enums/IccColorantEncoding.cs | {
"start": 185,
"end": 724
} | internal enum ____ : ushort
{
/// <summary>
/// Unknown colorant encoding
/// </summary>
Unknown = 0x0000,
/// <summary>
/// ITU-R BT.709-2 colorant encoding
/// </summary>
ItuRBt709_2 = 0x0001,
/// <summary>
/// SMPTE RP145 colorant encoding
/// </summary>
SmpteRp145 = 0x0002,
/// <summary>
/// EBU Tech.3213-E colorant encoding
/// </summary>
EbuTech3213E = 0x0003,
/// <summary>
/// P22 colorant encoding
/// </summary>
P22 = 0x0004,
}
| IccColorantEncoding |
csharp | smartstore__Smartstore | src/Smartstore.Web/Models/Catalog/ProductDetailsModel.cs | {
"start": 12184,
"end": 12496
} | public partial class ____ : EntityModelBase
{
public int Quantity { get; set; }
public bool HideThumbnail { get; set; }
public bool Visible { get; set; }
public bool IsBundleItemPricing { get; set; }
}
#endregion
}
}
| ProductBundleItemModel |
csharp | Antaris__RazorEngine | src/source/RazorEngine.Core/Templating/DefaultCachingProvider.cs | {
"start": 500,
"end": 3053
} | public class ____ : ICachingProvider
{
/// <summary>
/// We wrap it without calling any memory leaking API.
/// </summary>
private InvalidatingCachingProvider inner;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultCachingProvider"/> class.
/// </summary>
public DefaultCachingProvider() : this(null)
{
inner = new InvalidatingCachingProvider();
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultCachingProvider"/> class.
/// </summary>
/// <param name="registerForCleanup">callback for files which need to be cleaned up.</param>
public DefaultCachingProvider(Action<string> registerForCleanup)
{
inner = new InvalidatingCachingProvider(registerForCleanup);
}
/// <summary>
/// The manages <see cref="TypeLoader"/>. See <see cref="ICachingProvider.TypeLoader"/>
/// </summary>
public TypeLoader TypeLoader
{
get
{
return inner.TypeLoader;
}
}
/// <summary>
/// Get the key used within a dictionary for a modelType.
/// </summary>
public static Type GetModelTypeKey(Type modelType)
{
return InvalidatingCachingProvider.GetModelTypeKey(modelType);
}
/// <summary>
/// Caches a template. See <see cref="ICachingProvider.CacheTemplate"/>.
/// </summary>
/// <param name="template"></param>
/// <param name="templateKey"></param>
public void CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey)
{
inner.CacheTemplate(template, templateKey);
}
/// <summary>
/// Try to retrieve a template from the cache. See <see cref="ICachingProvider.TryRetrieveTemplate"/>.
/// </summary>
/// <param name="templateKey"></param>
/// <param name="modelType"></param>
/// <param name="compiledTemplate"></param>
/// <returns></returns>
public bool TryRetrieveTemplate(ITemplateKey templateKey, Type modelType, out ICompiledTemplate compiledTemplate)
{
return inner.TryRetrieveTemplate(templateKey, modelType, out compiledTemplate);
}
/// <summary>
/// Dispose the instance.
/// </summary>
public void Dispose()
{
inner.Dispose();
}
}
}
| DefaultCachingProvider |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Tax.Avalara/Controllers/AvalaraWebhookController.cs | {
"start": 120,
"end": 670
} | public class ____ : Controller
{
#region Fields
protected readonly AvalaraTaxManager _avalaraTaxManager;
#endregion
#region Ctor
public AvalaraWebhookController(AvalaraTaxManager avalaraTaxManager)
{
_avalaraTaxManager = avalaraTaxManager;
}
#endregion
#region Methods
[HttpPost]
public async Task<IActionResult> ItemClassificationWebhook()
{
await _avalaraTaxManager.HandleItemClassificationWebhookAsync(Request);
return Ok();
}
#endregion
} | AvalaraWebhookController |
csharp | dotnet__orleans | src/Orleans.Core.Abstractions/IDs/GrainType.cs | {
"start": 244,
"end": 6092
} | struct ____ : IEquatable<GrainType>, IComparable<GrainType>, ISerializable, ISpanFormattable
{
[Id(0)]
private readonly IdSpan _value;
/// <summary>
/// Initializes a new instance of the <see cref="GrainType"/> struct.
/// </summary>
/// <param name="id">
/// The id.
/// </param>
public GrainType(IdSpan id) => _value = id;
/// <summary>
/// Initializes a new instance of the <see cref="GrainType"/> struct.
/// </summary>
/// <param name="value">
/// The raw id value.
/// </param>
public GrainType(byte[] value) => _value = new IdSpan(value);
/// <summary>
/// Initializes a new instance of the <see cref="GrainType"/> struct.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The context.
/// </param>
private GrainType(SerializationInfo info, StreamingContext context)
{
_value = IdSpan.UnsafeCreate((byte[]?)info.GetValue("v", typeof(byte[])), info.GetInt32("h"));
}
/// <summary>
/// Gets the underlying value.
/// </summary>
public IdSpan Value => _value;
/// <summary>
/// Returns a span representation of this instance.
/// </summary>
/// <returns>
/// A <see cref="ReadOnlySpan{Byte}"/> representation of the value.
/// </returns>
public ReadOnlySpan<byte> AsSpan() => _value.AsSpan();
/// <summary>
/// Creates a new <see cref="GrainType"/> instance.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The newly created <see cref="GrainType"/> instance.
/// </returns>
public static GrainType Create(string value)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(value);
return new GrainType(Encoding.UTF8.GetBytes(value));
}
/// <summary>
/// Converts a <see cref="GrainType"/> to a <see cref="IdSpan"/>.
/// </summary>
/// <param name="kind">The grain type to convert.</param>
/// <returns>The corresponding <see cref="IdSpan"/>.</returns>
public static explicit operator IdSpan(GrainType kind) => kind._value;
/// <summary>
/// Converts a <see cref="IdSpan"/> to a <see cref="GrainType"/>.
/// </summary>
/// <param name="id">The id span to convert.</param>
/// <returns>The corresponding <see cref="GrainType"/>.</returns>
public static explicit operator GrainType(IdSpan id) => new GrainType(id);
/// <summary>
/// Gets a value indicating whether this instance is the default value.
/// </summary>
public bool IsDefault => _value.IsDefault;
/// <inheritdoc/>
public override bool Equals(object? obj) => obj is GrainType kind && Equals(kind);
/// <inheritdoc/>
public bool Equals(GrainType obj) => _value.Equals(obj._value);
/// <inheritdoc/>
public override int GetHashCode() => _value.GetHashCode();
/// <summary>
/// Generates a uniform, stable hash code for this grain type.
/// </summary>
/// <returns>
/// A uniform, stable hash of this instance.
/// </returns>
public uint GetUniformHashCode() => _value.GetUniformHashCode();
/// <summary>
/// Returns the array underlying a grain type instance.
/// </summary>
/// <param name="id">The grain type.</param>
/// <returns>The array underlying a grain type instance.</returns>
/// <remarks>
/// The returned array must not be modified.
/// </remarks>
public static byte[]? UnsafeGetArray(GrainType id) => IdSpan.UnsafeGetArray(id._value);
/// <inheritdoc/>
public int CompareTo(GrainType other) => _value.CompareTo(other._value);
/// <inheritdoc/>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("v", IdSpan.UnsafeGetArray(_value));
info.AddValue("h", _value.GetHashCode());
}
/// <summary>
/// Returns a string representation of this instance, decoding the value as UTF8.
/// </summary>
/// <returns>
/// A <see cref="string"/> representation of this instance.
/// </returns>
public override string? ToString() => _value.ToString();
string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString() ?? "";
bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
=> _value.TryFormat(destination, out charsWritten);
/// <summary>
/// Compares the provided operands for equality.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns><see langword="true"/> if the provided values are equal, otherwise <see langword="false"/>.</returns>
public static bool operator ==(GrainType left, GrainType right) => left.Equals(right);
/// <summary>
/// Compares the provided operands for inequality.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns><see langword="true"/> if the provided values are not equal, otherwise <see langword="false"/>.</returns>
public static bool operator !=(GrainType left, GrainType right) => !(left == right);
}
}
| GrainType |
csharp | files-community__Files | src/Files.App/Actions/Display/SortAction.cs | {
"start": 3143,
"end": 3633
} | partial class ____ : SortByAction
{
protected override SortOption SortOption
=> SortOption.OriginalFolder;
public override string Label
=> Strings.OriginalFolder.GetLocalizedResource();
public override string Description
=> Strings.SortByOriginalFolderDescription.GetLocalizedResource();
protected override bool GetIsExecutable(ContentPageTypes pageType)
=> pageType is ContentPageTypes.RecycleBin;
}
[GeneratedRichCommand]
internal sealed | SortByOriginalFolderAction |
csharp | icsharpcode__ILSpy | ILSpy/Views/ManageAssemblyLIstsDialog.xaml.cs | {
"start": 1390,
"end": 1903
} | public partial class ____ : Window
{
public ManageAssemblyListsDialog(SettingsService settingsService)
{
InitializeComponent();
DataContext = new ManageAssemblyListsViewModel(this, settingsService);
}
private void PreconfiguredAssemblyListsMenuClick(object sender, RoutedEventArgs e)
{
var menu = (ContextMenu)Resources["PreconfiguredAssemblyListsMenu"];
menu.PlacementTarget = (Button)sender;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
}
}
| ManageAssemblyListsDialog |
csharp | dotnet__aspnetcore | src/Http/Http.Extensions/test/ParameterBindingMethodCacheTests.cs | {
"start": 52369,
"end": 52415
} | private abstract class ____ { }
| AbstractClass |
csharp | smartstore__Smartstore | src/Smartstore/Data/Hooks/DefaultDbHookActivator.cs | {
"start": 75,
"end": 1510
} | public class ____ : IDbHookActivator
{
private readonly Dictionary<HookMetadata, IDbSaveHook> _instances = new();
private readonly ILifetimeScope _scope;
public DefaultDbHookActivator(ILifetimeScope scope)
{
_scope = scope;
}
public virtual IDbSaveHook Activate(HookMetadata hook)
{
if (hook == null)
{
throw new ArgumentNullException(nameof(hook));
}
if (_instances.TryGetValue(hook, out var instance))
{
return instance;
}
try
{
for (var i = 0; i < hook.ServiceTypes.Length; i++)
{
if (_scope.TryResolve(hook.ServiceTypes[i], out var obj) && obj is IDbSaveHook saveHook)
{
instance = _instances[hook] = saveHook;
break;
}
}
if (instance == null)
{
throw new DependencyResolutionException(
$"None of the provided service types [{string.Join(", ", hook.ServiceTypes.AsEnumerable())}] can resolve the hook '{hook.ImplType}'.");
}
return instance;
}
catch
{
throw;
}
}
}
}
| DefaultDbHookActivator |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Exceptions/AsyncFunctionExceptionAssertionSpecs.cs | {
"start": 46971,
"end": 47384
} | internal static class ____
{
public static Task Async<TException>()
where TException : Exception, new() =>
Async(new TException());
public static async Task Async(Exception expcetion)
{
await Task.Yield();
throw expcetion;
}
public static async ValueTask AsyncValueTask(Exception expcetion)
{
await Task.Yield();
throw expcetion;
}
}
| Throw |
csharp | reactiveui__ReactiveUI | src/ReactiveUI/Registration/Registrations.cs | {
"start": 812,
"end": 997
} | public class ____ : IWantsToRegisterStuff
{
/// <inheritdoc/>
[SuppressMessage("Trimming", "IL2046:'RequiresUnreferencedCodeAttribute' annotations must match across all | Registrations |
csharp | MaterialDesignInXAML__MaterialDesignInXamlToolkit | src/MaterialDesignThemes.Wpf/CalendarFormatInfo.cs | {
"start": 9261,
"end": 12475
} | public struct ____
{
/// <summary>
/// Gets the custom format string for a day of week value.
/// </summary>
public string Pattern { get; }
/// <summary>
/// Gets the string that separates MonthDay and DayOfWeek.
/// </summary>
public string Separator { get; }
/// <summary>
/// Gets a value indicating whether DayOfWeek is before MonthDay.
/// </summary>
public bool IsFirst { get; }
private const string EthiopicWordspace = "\u1361";
private const string EthiopicComma = "\u1363";
private const string EthiopicColon = "\u1365";
private const string ArabicComma = "\u060c";
private const string SeparatorChars = "," + ArabicComma + EthiopicWordspace + EthiopicComma + EthiopicColon;
/// <summary>
/// Initializes a new instance of the <see cref="DayOfWeekStyle"/> struct.
/// </summary>
/// <param name="pattern">A custom format string for a day of week value.</param>
/// <param name="separator">A string that separates MonthDay and DayOfWeek.</param>
/// <param name="isFirst">A value indicating whether DayOfWeek is before MonthDay.</param>
public DayOfWeekStyle(string pattern, string separator, bool isFirst)
{
Pattern = pattern ?? string.Empty;
Separator = separator ?? string.Empty;
IsFirst = isFirst;
}
/// <summary>
/// Extracts the <see cref="DayOfWeekStyle"/> from the date format string.
/// </summary>
/// <param name="s">the date format string.</param>
/// <returns>The <see cref="DayOfWeekStyle"/> struct.</returns>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is null.</exception>
public static DayOfWeekStyle Parse(string s)
{
if (s is null)
throw new ArgumentNullException(nameof(s));
if (s.StartsWith(ShortDayOfWeek, StringComparison.Ordinal))
{
var index = 3;
if (index < s.Length && s[index] == 'd')
index++;
for (; index < s.Length && IsSpace(s[index]); index++)
;
var separator = index < s.Length && IsSeparator(s[index]) ? s[index].ToString() : string.Empty;
return new DayOfWeekStyle(ShortDayOfWeek, separator, true);
}
else if (s.EndsWith(ShortDayOfWeek, StringComparison.Ordinal))
{
var index = s.Length - 4;
if (index >= 0 && s[index] == 'd')
index--;
for (; index >= 0 && IsSpace(s[index]); index--)
;
var separator = index >= 0 && IsSeparator(s[index]) ? s[index].ToString() : string.Empty;
return new DayOfWeekStyle(ShortDayOfWeek, separator, false);
}
return new DayOfWeekStyle(ShortDayOfWeek, string.Empty, true);
static bool IsSpace(char c) => c == ' ' || c == '\'';
static bool IsSeparator(char c) => SeparatorChars.IndexOf(c) >= 0;
}
}
}
| DayOfWeekStyle |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Perception.Spatial/SpatialLocation.cs | {
"start": 301,
"end": 6069
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal SpatialLocation()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Quaternion AbsoluteAngularAcceleration
{
get
{
throw new global::System.NotImplementedException("The member Quaternion SpatialLocation.AbsoluteAngularAcceleration is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Quaternion%20SpatialLocation.AbsoluteAngularAcceleration");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Quaternion AbsoluteAngularVelocity
{
get
{
throw new global::System.NotImplementedException("The member Quaternion SpatialLocation.AbsoluteAngularVelocity is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Quaternion%20SpatialLocation.AbsoluteAngularVelocity");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 AbsoluteLinearAcceleration
{
get
{
throw new global::System.NotImplementedException("The member Vector3 SpatialLocation.AbsoluteLinearAcceleration is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20SpatialLocation.AbsoluteLinearAcceleration");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 AbsoluteLinearVelocity
{
get
{
throw new global::System.NotImplementedException("The member Vector3 SpatialLocation.AbsoluteLinearVelocity is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20SpatialLocation.AbsoluteLinearVelocity");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Quaternion Orientation
{
get
{
throw new global::System.NotImplementedException("The member Quaternion SpatialLocation.Orientation is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Quaternion%20SpatialLocation.Orientation");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 Position
{
get
{
throw new global::System.NotImplementedException("The member Vector3 SpatialLocation.Position is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20SpatialLocation.Position");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 AbsoluteAngularAccelerationAxisAngle
{
get
{
throw new global::System.NotImplementedException("The member Vector3 SpatialLocation.AbsoluteAngularAccelerationAxisAngle is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20SpatialLocation.AbsoluteAngularAccelerationAxisAngle");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 AbsoluteAngularVelocityAxisAngle
{
get
{
throw new global::System.NotImplementedException("The member Vector3 SpatialLocation.AbsoluteAngularVelocityAxisAngle is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20SpatialLocation.AbsoluteAngularVelocityAxisAngle");
}
}
#endif
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.Position.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.Orientation.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteLinearVelocity.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteLinearAcceleration.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteAngularVelocity.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteAngularAcceleration.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteAngularVelocityAxisAngle.get
// Forced skipping of method Windows.Perception.Spatial.SpatialLocation.AbsoluteAngularAccelerationAxisAngle.get
}
}
| SpatialLocation |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3441850,
"end": 3444027
} | public partial record ____ : global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ICommitFusionConfigurationPublishInputInfo
{
public virtual global::System.Boolean Equals(CommitFusionConfigurationPublishInput? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (Configuration.Equals(other.Configuration)) && RequestId.Equals(other.RequestId);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * Configuration.GetHashCode();
hash ^= 397 * RequestId.GetHashCode();
return hash;
}
}
private global::StrawberryShake.Upload _value_configuration;
private global::System.Boolean _set_configuration;
private global::System.String _value_requestId = default !;
private global::System.Boolean _set_requestId;
public global::StrawberryShake.Upload Configuration
{
get => _value_configuration;
init
{
_set_configuration = true;
_value_configuration = value;
}
}
global::System.Boolean global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ICommitFusionConfigurationPublishInputInfo.IsConfigurationSet => _set_configuration;
public global::System.String RequestId
{
get => _value_requestId;
init
{
_set_requestId = true;
_value_requestId = value;
}
}
global::System.Boolean global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ICommitFusionConfigurationPublishInputInfo.IsRequestIdSet => _set_requestId;
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| CommitFusionConfigurationPublishInput |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/FilterDefinitionBuilderTests.cs | {
"start": 41917,
"end": 42476
} | private class ____
{
[BsonElement("fn")]
public string FirstName { get; set; }
[BsonElement("colors")]
public string[] FavoriteColors { get; set; }
[BsonElement("age")]
public int Age { get; set; }
[BsonElement("favoritePet")]
public Animal FavoritePet { get; set; }
[BsonElement("pets")]
public Animal[] Pets { get; set; }
[BsonElement("loc")]
public int[] Location { get; set; }
}
| Person |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/Processing/Convolution/GaussianBlurTest.cs | {
"start": 276,
"end": 1149
} | public class ____ : BaseImageOperationsExtensionTest
{
[Fact]
public void GaussianBlur_GaussianBlurProcessorDefaultsSet()
{
this.operations.GaussianBlur();
GaussianBlurProcessor processor = this.Verify<GaussianBlurProcessor>();
Assert.Equal(3f, processor.Sigma);
}
[Fact]
public void GaussianBlur_amount_GaussianBlurProcessorDefaultsSet()
{
this.operations.GaussianBlur(0.2f);
GaussianBlurProcessor processor = this.Verify<GaussianBlurProcessor>();
Assert.Equal(.2f, processor.Sigma);
}
[Fact]
public void GaussianBlur_amount_rect_GaussianBlurProcessorDefaultsSet()
{
this.operations.GaussianBlur(this.rect, 0.6f);
GaussianBlurProcessor processor = this.Verify<GaussianBlurProcessor>(this.rect);
Assert.Equal(.6f, processor.Sigma);
}
}
| GaussianBlurTest |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Metrics/Unit/ParserTests.StrongTypes.cs | {
"start": 20974,
"end": 21191
} | partial class ____
{
[Histogram(typeof(MyClassA))]
static partial TotalCount CreateTotalCountCounter(Meter meter);
}");
Assert.Empty(d);
}
}
| MetricClass |
csharp | SixLabors__ImageSharp | src/ImageSharp/Formats/Icon/IconDir.cs | {
"start": 224,
"end": 1173
} | internal struct ____(ushort reserved, IconFileType type, ushort count)
{
public const int Size = 3 * sizeof(ushort);
/// <summary>
/// Reserved. Must always be 0.
/// </summary>
public ushort Reserved = reserved;
/// <summary>
/// Specifies image type: 1 for icon (.ICO) image, 2 for cursor (.CUR) image. Other values are invalid.
/// </summary>
public IconFileType Type = type;
/// <summary>
/// Specifies number of images in the file.
/// </summary>
public ushort Count = count;
public IconDir(IconFileType type)
: this(type, 0)
{
}
public IconDir(IconFileType type, ushort count)
: this(0, type, count)
{
}
public static IconDir Parse(ReadOnlySpan<byte> data)
=> MemoryMarshal.Cast<byte, IconDir>(data)[0];
public readonly unsafe void WriteTo(Stream stream)
=> stream.Write(MemoryMarshal.Cast<IconDir, byte>([this]));
}
| IconDir |
csharp | dotnet__orleans | test/Orleans.Serialization.UnitTests/BuiltInCodecTests.cs | {
"start": 79146,
"end": 80065
} | public class ____(ITestOutputHelper output) : CopierTester<long, IDeepCopier<long>>(output)
{
protected override long CreateValue()
{
var msb = (ulong)Guid.NewGuid().GetHashCode() << 32;
var lsb = (ulong)Guid.NewGuid().GetHashCode();
return (long)(msb | lsb);
}
protected override long[] TestValues =>
[
long.MinValue,
-1,
0,
1,
(long)sbyte.MaxValue - 1,
sbyte.MaxValue,
(long)sbyte.MaxValue + 1,
(long)short.MaxValue - 1,
short.MaxValue,
(long)short.MaxValue + 1,
(long)int.MaxValue - 1,
int.MaxValue,
(long)int.MaxValue + 1,
long.MaxValue,
];
protected override Action<Action<long>> ValueProvider => Gen.Long.ToValueProvider();
}
| Int64CopierTests |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/RazorRockstars.Console.Files/AppHost.cs | {
"start": 5190,
"end": 5461
} | public class ____
{
[DataMember]
public int Total { get; set; }
[DataMember]
public int? Aged { get; set; }
[DataMember]
public List<Rockstar> Results { get; set; }
}
[Route("/ilist1/{View}")]
| RockstarsResponse |
csharp | dotnet__aspire | src/Aspire.Dashboard/Model/Otlp/SpanWaterfallViewModel.cs | {
"start": 439,
"end": 4021
} | public sealed class ____
{
public required List<SpanWaterfallViewModel> Children { get; init; }
public required OtlpSpan Span { get; init; }
public required double LeftOffset { get; init; }
public required double Width { get; init; }
public required int Depth { get; init; }
public required bool LabelIsRight { get; init; }
public required string? UninstrumentedPeer { get; init; }
public required List<SpanLogEntryViewModel> SpanLogs { get; init; }
public bool IsHidden { get; set; }
[MemberNotNullWhen(true, nameof(UninstrumentedPeer))]
public bool HasUninstrumentedPeer => !string.IsNullOrEmpty(UninstrumentedPeer);
public bool IsError => Span.Status == OtlpSpanStatusCode.Error;
public bool IsCollapsed
{
get;
set
{
field = value;
UpdateHidden();
}
}
public string GetTooltip(List<OtlpResource> allResources)
{
var tooltip = GetTitle(Span, allResources);
if (IsError)
{
tooltip += Environment.NewLine + "Status = Error";
}
if (HasUninstrumentedPeer)
{
tooltip += Environment.NewLine + $"Outgoing call to {UninstrumentedPeer}";
}
return tooltip;
}
public bool MatchesFilter(string filter, TelemetryFilter? typeFilter, Func<OtlpResourceView, string> getResourceName, [NotNullWhen(true)] out IEnumerable<SpanWaterfallViewModel>? matchedDescendents)
{
if (Filter(this))
{
matchedDescendents = Children.SelectMany(GetWithDescendents);
return true;
}
foreach (var child in Children)
{
if (child.MatchesFilter(filter, typeFilter, getResourceName, out var matchedChildDescendents))
{
matchedDescendents = [child, ..matchedChildDescendents];
return true;
}
}
matchedDescendents = null;
return false;
bool Filter(SpanWaterfallViewModel viewModel)
{
if (typeFilter != null)
{
if (!typeFilter.Apply(viewModel.Span))
{
return false;
}
}
if (string.IsNullOrWhiteSpace(filter))
{
return true;
}
return viewModel.Span.SpanId.Contains(filter, StringComparison.CurrentCultureIgnoreCase)
|| getResourceName(viewModel.Span.Source).Contains(filter, StringComparison.CurrentCultureIgnoreCase)
|| viewModel.Span.GetDisplaySummary().Contains(filter, StringComparison.CurrentCultureIgnoreCase)
|| viewModel.UninstrumentedPeer?.Contains(filter, StringComparison.CurrentCultureIgnoreCase) is true;
}
static IEnumerable<SpanWaterfallViewModel> GetWithDescendents(SpanWaterfallViewModel s)
{
var stack = new Stack<SpanWaterfallViewModel>();
stack.Push(s);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
foreach (var child in current.Children)
{
stack.Push(child);
}
}
}
}
private void UpdateHidden(bool isParentCollapsed = false)
{
IsHidden = isParentCollapsed;
foreach (var child in Children)
{
child.UpdateHidden(isParentCollapsed || IsCollapsed);
}
}
private readonly | SpanWaterfallViewModel |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ViewFeatures/test/Filters/AntiforgeryApplicationModelProviderTest.cs | {
"start": 7210,
"end": 7341
} | private class ____ : AntiforgeryMetadataController
{
}
[ValidateAntiForgeryToken]
| DerivedAntiforgeryMetadataController |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests.Provider.Duckdb/Duckdb/DuckdbCodeFirstTest.cs | {
"start": 83220,
"end": 89404
} | class ____
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public TimeOnly testFieldTimeOnly { get; set; }
[Column(ServerTime = DateTimeKind.Local)]
public DateTime testFieldDateTime { get; set; }
public DateOnly testFieldDateOnly { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public char testFieldChar { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public TimeOnly? testFieldTimeOnlyNullable { get; set; }
[Column(ServerTime = DateTimeKind.Local)]
public DateTime? testFieldDateTimeNullable { get; set; }
public DateOnly? testFieldDateOnlyNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public BitArray testFieldBitArray { get; set; }
public Dictionary<string, object> testFieldStruct { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
/* array */
public bool[] testFieldBoolArray { get; set; }
public sbyte[] testFieldSByteArray { get; set; }
public short[] testFieldShortArray { get; set; }
public int[] testFieldIntArray { get; set; }
public long[] testFieldLongArray { get; set; }
public ushort[] testFieldUShortArray { get; set; }
public uint[] testFieldUIntArray { get; set; }
public ulong[] testFieldULongArray { get; set; }
public double[] testFieldDoubleArray { get; set; }
public float[] testFieldFloatArray { get; set; }
public decimal[] testFieldDecimalArray { get; set; }
public TimeSpan[] testFieldTimeSpanArray { get; set; }
public TimeOnly[] testFieldTimeOnlyArray { get; set; }
public DateTime[] testFieldDateTimeArray { get; set; }
public DateOnly[] testFieldDateOnlyArray { get; set; }
public byte[][] testFieldBytesArray { get; set; }
public string[] testFieldStringArray { get; set; }
public Guid[] testFieldGuidArray { get; set; }
public bool?[] testFieldBoolArrayNullable { get; set; }
public sbyte?[] testFieldSByteArrayNullable { get; set; }
public short?[] testFieldShortArrayNullable { get; set; }
public int?[] testFieldIntArrayNullable { get; set; }
public long?[] testFielLongArrayNullable { get; set; }
public byte?[] testFieldByteArrayNullable { get; set; }
public ushort?[] testFieldUShortArrayNullable { get; set; }
public uint?[] testFieldUIntArrayNullable { get; set; }
public ulong?[] testFieldULongArrayNullable { get; set; }
public double?[] testFieldDoubleArrayNullable { get; set; }
public float?[] testFieldFloatArrayNullable { get; set; }
public decimal?[] testFieldDecimalArrayNullable { get; set; }
public TimeSpan?[] testFieldTimeSpanArrayNullable { get; set; }
public TimeOnly?[] testFieldTimeOnlyArrayNullable { get; set; }
public DateTime?[] testFieldDateTimeArrayNullable { get; set; }
public DateOnly?[] testFieldDateOnlyArrayNullable { get; set; }
public Guid?[] testFieldGuidArrayNullable { get; set; }
public BitArray[] testFieldBitArrayArray { get; set; }
public Dictionary<string, object>[] testFieldStructArray { get; set; }
public TableAllTypeEnumType1[] testFieldEnum1Array { get; set; }
public TableAllTypeEnumType1?[] testFieldEnum1ArrayNullable { get; set; }
public TableAllTypeEnumType2[] testFieldEnum2Array { get; set; }
public TableAllTypeEnumType2?[] testFieldEnum2ArrayNullable { get; set; }
}
[Fact]
public void TestNormalIndex()
{
fsql.CodeFirst.SyncStructure<TableNormalIndexTest>();
}
[Fact]
public void TestCompoundIndex()
{
fsql.CodeFirst.SyncStructure<TableCompoundIndexTest>();
}
[Fact]
public void TestIsIdentity()
{
fsql.CodeFirst.SyncStructure<TableIsIdentityTest>();
}
[Table(Name = "index_normal_test")]
| TableAllType |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Certificates/with_certificate_files.cs | {
"start": 13143,
"end": 14148
} | public class ____ : with_certificate_chain_of_length_3 {
private string _certPath;
private const string Password = null;
[SetUp]
public void Setup() {
_certPath = $"{PathName}/bundle.p12";
using var rsa = RSA.Create();
rsa.ImportRSAPrivateKey(_leaf.GetRSAPrivateKey()!.ExportRSAPrivateKey(), out _);
var builder = new Pkcs12Builder();
var safeContents = new Pkcs12SafeContents();
var pbeParams = new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 2048);
safeContents.AddShroudedKey(rsa, Password, pbeParams);
builder.AddSafeContentsEncrypted(safeContents, Password, pbeParams);
builder.SealWithMac(Password, HashAlgorithmName.SHA256, 2048);
File.WriteAllBytes(_certPath, builder.Encode());
}
[Test]
public void cannot_load_certificate() {
var ex = Assert.Throws<Exception>(
() => CertificateUtils.LoadFromFile(_certPath, null, Password)
);
Assert.AreEqual(ex!.Message, "No certificates found");
}
}
| with_pkcs12_bundle_having_no_certificates |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Razor.RuntimeCompilation/test/CSharpCompilerTest.cs | {
"start": 11325,
"end": 11905
} | private class ____ : CSharpCompiler
{
private readonly DependencyContextCompilationOptions _options;
public TestCSharpCompiler(
RazorReferenceManager referenceManager,
IWebHostEnvironment hostingEnvironment,
DependencyContextCompilationOptions options)
: base(referenceManager, hostingEnvironment)
{
_options = options;
}
protected internal override DependencyContextCompilationOptions GetDependencyContextCompilationOptions()
=> _options;
}
}
| TestCSharpCompiler |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/CsvReaderMappingTests.cs | {
"start": 7364,
"end": 7637
} | private sealed class ____ : ClassMap<TestClass>
{
public ConvertUsingBlockMap()
{
Map(m => m.IntColumn).Convert(args =>
{
var x = args.Row.GetField<int>(0);
var y = args.Row.GetField<int>(1);
return x + y;
});
}
}
| ConvertUsingBlockMap |
csharp | atata-framework__atata | test/Atata.UnitTests/WebDriver/WebDriverSessionBuilderTests.cs | {
"start": 749,
"end": 2103
} | public sealed class ____
{
[Test]
public void WhenThereAreNoDrivers()
{
// Arrange
var builder = WebDriverSession.CreateBuilder();
// Act
builder.UseDriver(WebDriverAliases.Edge);
// Assert
builder.DriverFactories.Should().HaveCount(1);
builder.DriverFactoryToUse!.Alias.Should().Be(WebDriverAliases.Edge);
}
[Test]
public void WhenThereAreNoDrivers_CallTwice()
{
// Arrange
var builder = WebDriverSession.CreateBuilder();
// Act
builder.UseDriver(WebDriverAliases.Edge);
builder.UseDriver(WebDriverAliases.Edge);
// Assert
builder.DriverFactories.Should().HaveCount(1);
builder.DriverFactoryToUse!.Alias.Should().Be(WebDriverAliases.Edge);
}
[Test]
public void WhenThereIsSuchDriver()
{
// Arrange
var builder = WebDriverSession.CreateBuilder();
builder.UseEdge();
// Act
builder.UseDriver(WebDriverAliases.Edge);
// Assert
builder.DriverFactories.Should().HaveCount(1);
builder.DriverFactoryToUse!.Alias.Should().Be(WebDriverAliases.Edge);
}
}
| UseDriver_WithAlias |
csharp | PrismLibrary__Prism | tests/Prism.Core.Tests/Commands/DelegateCommandFixture.cs | {
"start": 242,
"end": 31449
} | public class ____ : BindableBase
{
[Fact]
public void WhenConstructedWithGenericTypeOfObject_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<object>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeOfNullable_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<int?>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeIsNonNullableValueType_Throws()
{
Assert.Throws<InvalidCastException>(() =>
{
var actual = new DelegateCommand<int>(param => { });
});
}
[Fact]
public void ExecuteCallsPassedInExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
object parameter = new object();
command.Execute(parameter);
Assert.Same(parameter, handlers.ExecuteParameter);
}
[Fact]
public void CanExecuteCallsPassedInCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute, handlers.CanExecute);
object parameter = new object();
handlers.CanExecuteReturnValue = true;
bool retVal = command.CanExecute(parameter);
Assert.Same(parameter, handlers.CanExecuteParameter);
Assert.Equal(handlers.CanExecuteReturnValue, retVal);
}
[Fact]
public void CanExecuteReturnsTrueWithouthCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool retVal = command.CanExecute(null);
Assert.True(retVal);
}
[Fact]
public void RaiseCanExecuteChangedRaisesCanExecuteChanged()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool canExecuteChangedRaised = false;
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
command.RaiseCanExecuteChanged();
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void CanRemoveCanExecuteChangedHandler()
{
var command = new DelegateCommand<object>((o) => { });
bool canExecuteChangedRaised = false;
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
command.CanExecuteChanged += handler;
command.CanExecuteChanged -= handler;
command.RaiseCanExecuteChanged();
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void ShouldPassParameterInstanceOnExecute()
{
bool executeCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>(delegate (MyClass parameter)
{
Assert.Same(testClass, parameter);
executeCalled = true;
});
command.Execute(testClass);
Assert.True(executeCalled);
}
[Fact]
public void ShouldPassParameterInstanceOnCanExecute()
{
bool canExecuteCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>((p) => { }, delegate (MyClass parameter)
{
Assert.Same(testClass, parameter);
canExecuteCalled = true;
return true;
});
command.CanExecute(testClass);
Assert.True(canExecuteCalled);
}
[Fact]
public void ShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null, null);
});
}
[Fact]
public void ShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null);
});
}
[Fact]
public void ShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>((o) => { }, null);
});
}
[Fact]
public void DelegateCommandShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null, null);
});
}
[Fact]
public void DelegateCommandShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null);
});
}
[Fact]
public void DelegateCommandGenericShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>((o) => { }, null);
});
}
[Fact]
public void IsActivePropertyIsFalseByDeafult()
{
var command = new DelegateCommand<object>(DoNothing);
Assert.False(command.IsActive);
}
[Fact]
public void IsActivePropertyChangeFiresEvent()
{
bool fired = false;
var command = new DelegateCommand<object>(DoNothing);
command.IsActiveChanged += delegate { fired = true; };
command.IsActive = true;
Assert.True(fired);
}
[Fact]
public void NonGenericDelegateCommandExecuteShouldInvokeExecuteAction()
{
bool executed = false;
var command = new DelegateCommand(() => { executed = true; });
command.Execute();
Assert.True(executed);
}
[Fact]
public void NonGenericDelegateCommandCanExecuteShouldInvokeCanExecuteFunc()
{
bool invoked = false;
var command = new DelegateCommand(() => { }, () => { invoked = true; return true; });
bool canExecute = command.CanExecute();
Assert.True(invoked);
Assert.True(canExecute);
}
[Fact]
public void NonGenericDelegateCommandShouldDefaultCanExecuteToTrue()
{
var command = new DelegateCommand(() => { });
Assert.True(command.CanExecute());
}
[Fact]
public void NonGenericDelegateThrowsIfDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null, null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfCanExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(() => { }, null);
});
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute(() => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute(() => BoolProperty).ObservesCanExecute(() => BoolProperty);
});
}
[Fact]
public void NonGenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
[Fact]
public void NonGenericDelegateCommandObservingPropertyShouldRaiseOnNullPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(null);
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandObservingPropertyShouldRaiseOnEmptyPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(string.Empty);
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveOneComplexProperty()
{
ComplexProperty = new ComplexType()
{
InnerComplexProperty = new ComplexType()
};
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { })
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
ComplexProperty.InnerComplexProperty.IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandNotObservingPropertiesShouldNotRaiseOnEmptyPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { });
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(null);
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveComplexPropertyWhenRootPropertyIsNull()
{
bool canExecuteChangedRaise = false;
ComplexProperty = null;
var command = new DelegateCommand(() => { })
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaise = true;
};
var newComplexObject = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
IntProperty = 10
}
};
ComplexProperty = newComplexObject;
Assert.True(canExecuteChangedRaise);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveComplexPropertyWhenParentPropertyIsNull()
{
bool canExecuteChangedRaise = false;
ComplexProperty = new ComplexType();
var command = new DelegateCommand(() => { })
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaise = true;
};
var newComplexObject = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
IntProperty = 10
}
};
ComplexProperty.InnerComplexProperty = newComplexObject;
Assert.True(canExecuteChangedRaise);
}
[Fact]
public void NonGenericDelegateCommandPropertyObserverUnsubscribeUnusedListeners()
{
int canExecuteChangedRaiseCount = 0;
ComplexProperty = new ComplexType()
{
IntProperty = 1,
InnerComplexProperty = new ComplexType()
{
IntProperty = 1,
InnerComplexProperty = new ComplexType()
{
IntProperty = 1
}
}
};
var command = new DelegateCommand(() => { })
.ObservesProperty(() => ComplexProperty.IntProperty)
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.InnerComplexProperty.IntProperty)
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaiseCount++;
};
ComplexProperty.IntProperty = 2;
ComplexProperty.InnerComplexProperty.InnerComplexProperty.IntProperty = 2;
ComplexProperty.InnerComplexProperty.IntProperty = 2;
Assert.Equal(3, canExecuteChangedRaiseCount);
var innerInnerComplexProp = ComplexProperty.InnerComplexProperty.InnerComplexProperty;
var innerComplexProp = ComplexProperty.InnerComplexProperty;
var complexProp = ComplexProperty;
ComplexProperty = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
InnerComplexProperty = new ComplexType()
}
};
Assert.Equal(0, innerInnerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, innerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, complexProp.GetPropertyChangedSubscribledLenght());
innerInnerComplexProp = ComplexProperty.InnerComplexProperty.InnerComplexProperty;
innerComplexProp = ComplexProperty.InnerComplexProperty;
complexProp = ComplexProperty;
ComplexProperty = null;
Assert.Equal(0, innerInnerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, innerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, complexProp.GetPropertyChangedSubscribledLenght());
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandWithNullableParameterShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<int?>((o) => { }).ObservesCanExecute(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute(() => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command =
new DelegateCommand<object>((o) => { }).ObservesCanExecute(() => BoolProperty)
.ObservesCanExecute(() => BoolProperty);
});
}
[Fact]
public void GenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand<object> command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
[Fact]
public void GenericDelegateCommandObservingPropertyShouldRaiseOnNullPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(null);
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandObservingPropertyShouldRaiseOnEmptyPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(string.Empty);
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandNotObservingPropertiesShouldNotRaiseOnEmptyPropertyName()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { });
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
RaisePropertyChanged(null);
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldObserveComplexPropertyWhenParentPropertyIsNull()
{
bool canExecuteChangedRaise = false;
ComplexProperty = new ComplexType();
var command = new DelegateCommand<object>((o) => { })
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaise = true;
};
var newComplexObject = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
IntProperty = 10
}
};
ComplexProperty.InnerComplexProperty = newComplexObject;
Assert.True(canExecuteChangedRaise);
}
[Fact]
public void GenericDelegateCommandShouldObserveComplexPropertyWhenRootPropertyIsNull()
{
bool canExecuteChangedRaise = false;
ComplexProperty = null;
var command = new DelegateCommand<object>((o) => { })
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaise = true;
};
var newComplexObject = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
IntProperty = 10
}
};
ComplexProperty = newComplexObject;
Assert.True(canExecuteChangedRaise);
}
[Fact]
public void GenericDelegateCommandPropertyObserverUnsubscribeUnusedListeners()
{
int canExecuteChangedRaiseCount = 0;
ComplexProperty = new ComplexType()
{
IntProperty = 1,
InnerComplexProperty = new ComplexType()
{
IntProperty = 1,
InnerComplexProperty = new ComplexType()
{
IntProperty = 1
}
}
};
var command = new DelegateCommand<object>((o) => { })
.ObservesProperty(() => ComplexProperty.IntProperty)
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.InnerComplexProperty.IntProperty)
.ObservesProperty(() => ComplexProperty.InnerComplexProperty.IntProperty);
command.CanExecuteChanged += delegate
{
canExecuteChangedRaiseCount++;
};
ComplexProperty.IntProperty = 2;
ComplexProperty.InnerComplexProperty.InnerComplexProperty.IntProperty = 2;
ComplexProperty.InnerComplexProperty.IntProperty = 2;
Assert.Equal(3, canExecuteChangedRaiseCount);
var innerInnerComplexProp = ComplexProperty.InnerComplexProperty.InnerComplexProperty;
var innerComplexProp = ComplexProperty.InnerComplexProperty;
var complexProp = ComplexProperty;
ComplexProperty = new ComplexType()
{
InnerComplexProperty = new ComplexType()
{
InnerComplexProperty = new ComplexType()
}
};
Assert.Equal(0, innerInnerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, innerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, complexProp.GetPropertyChangedSubscribledLenght());
innerInnerComplexProp = ComplexProperty.InnerComplexProperty.InnerComplexProperty;
innerComplexProp = ComplexProperty.InnerComplexProperty;
complexProp = ComplexProperty;
ComplexProperty = null;
Assert.Equal(0, innerInnerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, innerComplexProp.GetPropertyChangedSubscribledLenght());
Assert.Equal(0, complexProp.GetPropertyChangedSubscribledLenght());
}
[Fact]
public void DelegateCommand_Catch_CatchesException()
{
var caught = false;
var command = new DelegateCommand(() => { throw new Exception(); })
.Catch<Exception>(ex => caught = true);
command.Execute();
Assert.True(caught);
}
[Fact]
public void DelegateCommandT_Catch_CatchesException()
{
var caught = false;
var command = new DelegateCommand<MyClass>(x => { throw new Exception(); })
.Catch<Exception>(ex => caught = true);
command.Execute(new MyClass());
Assert.True(caught);
}
[Fact]
public void DelegateCommand_Catch_CatchesExceptionWithParameter()
{
var caught = false;
object parameter = new object();
var command = new DelegateCommand(() => { throw new Exception(); })
.Catch<Exception>((ex, value) =>
{
caught = true;
parameter = value;
});
command.Execute();
Assert.True(caught);
Assert.Null(parameter);
}
[Fact]
public void DelegateCommandT_Catch_InvalidCastException()
{
var caught = false;
ICommand command = new DelegateCommand<MyClass>(x => { })
.Catch<Exception>(ex =>
{
Assert.IsType<InvalidCastException>(ex);
caught = true;
});
command.Execute("Test");
Assert.True(caught);
}
[Fact]
public void DelegateCommandT_Catch_CatchesExceptionWithParameter()
{
var caught = false;
var parameter = new object();
var command = new DelegateCommand<MyClass>(x => { throw new Exception(); })
.Catch<Exception>((ex, value) =>
{
caught = true;
parameter = value;
});
command.Execute(new MyClass { Value = 3 });
Assert.True(caught);
Assert.IsType<MyClass>(parameter);
Assert.Equal(3, ((MyClass)parameter).Value);
}
[Fact]
public void DelegateCommand_Catch_CatchesSpecificException()
{
var caught = false;
var command = new DelegateCommand(() => { throw new FileNotFoundException(); })
.Catch<FileNotFoundException>(ex => caught = true);
command.Execute();
Assert.True(caught);
}
[Fact]
public void DelegateCommandT_Catch_CatchesSpecificException()
{
var caught = false;
var command = new DelegateCommand<MyClass>(x => { throw new FileNotFoundException(); })
.Catch<FileNotFoundException>(ex => caught = true);
command.Execute(new MyClass());
Assert.True(caught);
}
[Fact]
public void DelegateCommand_Catch_CatchesChildException()
{
var caught = false;
var command = new DelegateCommand(() => { throw new FileNotFoundException(); })
.Catch<IOException>(ex => caught = true);
command.Execute();
Assert.True(caught);
}
[Fact]
public void DelegateCommandT_Catch_CatchesChildException()
{
var caught = false;
var command = new DelegateCommand<MyClass>(x => { throw new FileNotFoundException(); })
.Catch<IOException>(ex => caught = true);
command.Execute(new MyClass());
Assert.True(caught);
}
[Fact]
public void DelegateCommand_Throws_CatchesException()
{
var caught = false;
var command = new DelegateCommand(() => { throw new Exception(); })
.Catch<FileNotFoundException>(ex => caught = true);
var ex = Record.Exception(() => command.Execute());
Assert.False(caught);
Assert.NotNull(ex);
Assert.IsType<Exception>(ex);
}
[Fact]
public void DelegateCommandT_Throws_CatchesException()
{
var caught = false;
var command = new DelegateCommand<MyClass>(x => { throw new Exception(); })
.Catch<FileNotFoundException>(ex => caught = true);
var ex = Record.Exception(() => command.Execute(new MyClass()));
Assert.False(caught);
Assert.NotNull(ex);
Assert.IsType<Exception>(ex);
}
| DelegateCommandFixture |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core/Services/Processing/EventByType/EventByTypeIndexEventReader.IndexBased.cs | {
"start": 797,
"end": 13793
} | private class ____ : State,
IHandle<ClientMessage.ReadStreamEventsForwardCompleted>,
IHandle<ClientMessage.ReadStreamEventsBackwardCompleted>,
IHandle<ProjectionManagementMessage.Internal.ReadTimeout> {
private readonly Dictionary<string, string> _streamToEventType;
private readonly HashSet<string> _eventsRequested = new HashSet<string>();
private readonly HashSet<Guid> _validRequests = new HashSet<Guid>();
private bool _indexCheckpointStreamRequested;
private long _lastKnownIndexCheckpointEventNumber = -1;
private TFPos? _lastKnownIndexCheckpointPosition = null;
private readonly Dictionary<string, Queue<PendingEvent>> _buffers =
new Dictionary<string, Queue<PendingEvent>>();
private readonly Dictionary<string, bool> _eofs;
private bool _disposed;
private bool _indexStreamEof = false;
private readonly IPublisher _publisher;
private readonly Dictionary<string, Guid> _pendingRequests;
private readonly object _lock = new object();
public IndexBased(HashSet<string> eventTypes, EventByTypeIndexEventReader reader, ClaimsPrincipal readAs)
: base(reader, readAs) {
_streamToEventType = eventTypes.ToDictionary(v => "$et-" + v, v => v);
_eofs = _streamToEventType.Keys.ToDictionary(v => v, v => false);
// whatever the first event returned is (even if we start from the same position as the last processed event
// let subscription handle this
_publisher = _reader._publisher;
_pendingRequests = new Dictionary<string, Guid>();
_pendingRequests.Add("$et", Guid.Empty);
foreach (var stream in _streamToEventType.Keys) {
_pendingRequests.Add(stream, Guid.Empty);
}
}
private TFPos GetTargetEventPosition(PendingEvent head) {
return head.TfPosition;
}
public void Handle(ClientMessage.ReadStreamEventsForwardCompleted message) {
if (_disposed)
return;
if (message.Result == ReadStreamResult.AccessDenied) {
SendNotAuthorized();
return;
}
//we may receive read replies in any order (we read multiple streams)
if (message.TfLastCommitPosition > _reader._lastPosition)
_reader._lastPosition = message.TfLastCommitPosition;
if (message.EventStreamId is "$et") {
ReadIndexCheckpointStreamCompleted(message.Result, message.Events);
return;
}
if (!_validRequests.Contains(message.CorrelationId))
return;
lock (_lock) {
if (!_pendingRequests.Values.Any(x => x == message.CorrelationId))
return;
}
if (!_streamToEventType.ContainsKey(message.EventStreamId))
throw new InvalidOperationException(
String.Format("Invalid stream name: {0}", message.EventStreamId));
if (!_eventsRequested.Contains(message.EventStreamId))
throw new InvalidOperationException("Read events has not been requested");
if (_reader.Paused)
throw new InvalidOperationException("Paused");
switch (message.Result) {
case ReadStreamResult.NoStream:
_eofs[message.EventStreamId] = true;
ProcessBuffersAndContinue(eventStreamId: message.EventStreamId);
break;
case ReadStreamResult.Success:
_reader.UpdateNextStreamPosition(message.EventStreamId, message.NextEventNumber);
_eofs[message.EventStreamId] = message.Events is [] && message.IsEndOfStream;
EnqueueEvents(message);
ProcessBuffersAndContinue(eventStreamId: message.EventStreamId);
break;
default:
throw new NotSupportedException(
String.Format("ReadEvents result code was not recognized. Code: {0}", message.Result));
}
}
public void Handle(ProjectionManagementMessage.Internal.ReadTimeout message) {
if (_disposed)
return;
if (_reader.Paused)
return;
lock (_lock) {
if (!_pendingRequests.Values.Any(x => x == message.CorrelationId))
return;
}
if (message.StreamId == "$et") {
_indexCheckpointStreamRequested = false;
}
_eventsRequested.Remove(message.StreamId);
_reader.PauseOrContinueProcessing();
}
private void ProcessBuffersAndContinue(string eventStreamId) {
ProcessBuffers();
if (eventStreamId != null)
_eventsRequested.Remove(eventStreamId);
_reader.PauseOrContinueProcessing();
CheckSwitch();
}
private void CheckSwitch() {
if (ShouldSwitch()) {
Dispose();
_reader.DoSwitch(_lastKnownIndexCheckpointPosition.Value);
}
}
public void Handle(ClientMessage.ReadStreamEventsBackwardCompleted message) {
if (_disposed)
return;
//we may receive read replies in any order (we read multiple streams)
if (message.TfLastCommitPosition > _reader._lastPosition)
_reader._lastPosition = message.TfLastCommitPosition;
if (message.Result == ReadStreamResult.AccessDenied) {
SendNotAuthorized();
return;
}
ReadIndexCheckpointStreamCompleted(message.Result, message.Events);
}
private void EnqueueEvents(ClientMessage.ReadStreamEventsForwardCompleted message) {
for (int index = 0; index < message.Events.Count; index++) {
var @event = message.Events[index].Event;
var @link = message.Events[index].Link;
EventRecord positionEvent = (link ?? @event);
var queue = GetStreamQueue(positionEvent);
//TODO: progress calculation below is incorrect. sum(current)/sum(last_event) where sum by all streams
var tfPosition =
positionEvent.Metadata.ParseCheckpointTagJson().Position;
var progress = 100.0f * (link ?? @event).EventNumber / message.LastEventNumber;
var pendingEvent = new PendingEvent(message.Events[index], tfPosition, progress);
queue.Enqueue(pendingEvent);
}
}
private Queue<PendingEvent> GetStreamQueue(EventRecord positionEvent) {
Queue<PendingEvent> queue;
if (!_buffers.TryGetValue(positionEvent.EventStreamId, out queue)) {
queue = new Queue<PendingEvent>();
_buffers.Add(positionEvent.EventStreamId, queue);
}
return queue;
}
private bool BeforeTheLastKnownIndexCheckpoint(TFPos tfPosition) {
return _lastKnownIndexCheckpointPosition != null && tfPosition <= _lastKnownIndexCheckpointPosition;
}
private void ReadIndexCheckpointStreamCompleted(
ReadStreamResult result, IReadOnlyList<KurrentDB.Core.Data.ResolvedEvent> events) {
if (_disposed)
return;
if (!_indexCheckpointStreamRequested)
throw new InvalidOperationException("Read index checkpoint has not been requested");
if (_reader.Paused)
throw new InvalidOperationException("Paused");
_indexCheckpointStreamRequested = false;
switch (result) {
case ReadStreamResult.NoStream:
_indexStreamEof = true;
_lastKnownIndexCheckpointPosition = default(TFPos);
ProcessBuffersAndContinue(null);
break;
case ReadStreamResult.Success:
if (events is []) {
_indexStreamEof = true;
if (_lastKnownIndexCheckpointPosition == null)
_lastKnownIndexCheckpointPosition = default(TFPos);
} else {
_indexStreamEof = false;
//NOTE: only one event if backward order was requested
foreach (var @event in events) {
var data = @event.Event.Data.ParseCheckpointTagJson();
_lastKnownIndexCheckpointEventNumber = @event.Event.EventNumber;
_lastKnownIndexCheckpointPosition = data.Position;
// reset eofs before this point - probably some where updated so we cannot go
// forward with this position without making sure nothing appeared
// NOTE: performance is not very good, but we should switch to TF mode shortly
foreach (var corrId in _validRequests) {
_publisher.Publish(new AwakeServiceMessage.UnsubscribeAwake(corrId));
}
_validRequests.Clear();
_eventsRequested.Clear();
//TODO: cancel subscribeAwake
//TODO: reissue read requests
//TODO: make sure async completions of awake do not work
foreach (var key in _eofs.Keys.ToArray())
_eofs[key] = false;
}
}
ProcessBuffersAndContinue(null);
break;
default:
throw new NotSupportedException(
String.Format("ReadEvents result code was not recognized. Code: {0}", result));
}
}
private void ProcessBuffers() {
if (_disposed) // max N reached
return;
while (true) {
var minStreamId = "";
var minPosition = new TFPos(Int64.MaxValue, Int64.MaxValue);
var any = false;
var anyEof = false;
foreach (var streamId in _streamToEventType.Keys) {
Queue<PendingEvent> buffer;
_buffers.TryGetValue(streamId, out buffer);
if ((buffer == null || buffer.Count == 0))
if (_eofs[streamId]) {
anyEof = true;
continue; // eof - will check if it was safe later
} else
return; // still reading
var head = buffer.Peek();
var targetEventPosition = GetTargetEventPosition(head);
if (targetEventPosition < minPosition) {
minPosition = targetEventPosition;
minStreamId = streamId;
any = true;
}
}
if (!any)
break;
if (!anyEof || BeforeTheLastKnownIndexCheckpoint(minPosition)) {
var minHead = _buffers[minStreamId].Dequeue();
DeliverEventRetrievedByIndex(minHead.ResolvedEvent, minHead.Progress, minPosition);
} else
return; // no safe events to deliver
if (_buffers[minStreamId].Count == 0)
_reader.PauseOrContinueProcessing();
}
}
private void RequestCheckpointStream(bool delay) {
if (_disposed)
throw new InvalidOperationException("Disposed");
if (_reader.PauseRequested || _reader.Paused)
throw new InvalidOperationException("Paused or pause requested");
if (_indexCheckpointStreamRequested)
return;
_indexCheckpointStreamRequested = true;
var pendingRequestCorrelationId = Guid.NewGuid();
lock (_lock) {
_pendingRequests["$et"] = pendingRequestCorrelationId;
}
Message readRequest;
if (_lastKnownIndexCheckpointEventNumber == -1) {
readRequest = new ClientMessage.ReadStreamEventsBackward(
pendingRequestCorrelationId, pendingRequestCorrelationId, new SendToThisEnvelope(this), "$et",
-1, 1, false, false, null,
_readAs, replyOnExpired: false);
} else {
readRequest = new ClientMessage.ReadStreamEventsForward(
pendingRequestCorrelationId, pendingRequestCorrelationId, new SendToThisEnvelope(this), "$et",
_lastKnownIndexCheckpointEventNumber + 1, 100, false, false, null, _readAs, replyOnExpired: false);
}
var timeoutMessage = TimerMessage.Schedule.Create(
TimeSpan.FromMilliseconds(ESConsts.ReadRequestTimeout),
new SendToThisEnvelope(this),
new ProjectionManagementMessage.Internal.ReadTimeout(pendingRequestCorrelationId, "$et"));
_reader.PublishIORequest(delay, readRequest, timeoutMessage, pendingRequestCorrelationId);
}
private void RequestEvents(string stream, bool delay) {
if (_disposed)
throw new InvalidOperationException("Disposed");
if (_reader.PauseRequested || _reader.Paused)
throw new InvalidOperationException("Paused or pause requested");
if (_eventsRequested.Contains(stream))
return;
Queue<PendingEvent> queue;
if (_buffers.TryGetValue(stream, out queue) && queue.Count > 0)
return;
_eventsRequested.Add(stream);
var corrId = Guid.NewGuid();
_validRequests.Add(corrId);
lock (_lock) {
_pendingRequests[stream] = corrId;
}
var readEventsForward = new ClientMessage.ReadStreamEventsForward(
corrId, corrId, new SendToThisEnvelope(this), stream,
_reader._fromPositions[stream], MaxReadCount, _reader._resolveLinkTos,
false, null,
_readAs,
replyOnExpired: false);
var timeoutMessage = TimerMessage.Schedule.Create(
TimeSpan.FromMilliseconds(ESConsts.ReadRequestTimeout),
new SendToThisEnvelope(this),
new ProjectionManagementMessage.Internal.ReadTimeout(corrId, stream));
_reader.PublishIORequest(delay, readEventsForward, timeoutMessage, corrId);
}
private void DeliverEventRetrievedByIndex(KurrentDB.Core.Data.ResolvedEvent pair, float progress,
TFPos position) {
//TODO: add event sequence validation for inside the index stream
var resolvedEvent = new ResolvedEvent(pair, null);
DeliverEvent(progress, resolvedEvent, position, pair);
}
public override bool AreEventsRequested() {
return _eventsRequested.Count != 0 || _indexCheckpointStreamRequested;
}
public override void Dispose() {
_disposed = true;
}
public override void RequestEvents() {
foreach (var stream in _streamToEventType.Keys)
RequestEvents(stream, delay: _eofs[stream]);
RequestCheckpointStream(delay: _indexStreamEof);
}
private bool ShouldSwitch() {
if (_disposed)
return false;
if (_reader.Paused || _reader.PauseRequested)
return false;
Queue<PendingEvent> q;
var shouldSwitch = _lastKnownIndexCheckpointPosition != null
&& _streamToEventType.Keys.All(
v =>
_eofs[v]
|| _buffers.TryGetValue(v, out q) && q.Count > 0
&&
!BeforeTheLastKnownIndexCheckpoint(
q.Peek().TfPosition));
return shouldSwitch;
}
}
}
| IndexBased |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/AutoMappingTests.cs | {
"start": 37828,
"end": 39482
} | struct ____
{
public int Id { get; }
public D(int id) => Id = id;
public static explicit operator D(C from) => new D(from.Id);
}
[Test]
public void Can_convert_between_structs_with_explicit_casts()
{
var c = new C(1);
var d = (D)c;
Assert.That(d.Id, Is.EqualTo(c.Id));
d = c.ConvertTo<D>();
Assert.That(d.Id, Is.EqualTo(c.Id));
}
[Test]
public void Can_Convert_from_ObjectDictionary_Containing_Another_Object_Dictionary()
{
var map = new Dictionary<string, object>
{
{ "name", "Foo" },
{ "otherNames", new List<object>
{
new Dictionary<string, object> { { "name", "Fu" } },
new Dictionary<string, object> { { "name", "Fuey" } }
}
}
};
var fromDict = map.ConvertTo<AutoMappingObjectDictionaryTests.PersonWithIdentities>();
Assert.That(fromDict.Name, Is.EqualTo("Foo"));
Assert.That(fromDict.OtherNames.Count, Is.EqualTo(2));
Assert.That(fromDict.OtherNames.First().Name, Is.EqualTo("Fu"));
Assert.That(fromDict.OtherNames.Last().Name, Is.EqualTo("Fuey"));
var toDict = fromDict.ConvertTo<Dictionary<string,object>>();
Assert.That(toDict["Name"], Is.EqualTo("Foo"));
Assert.That(toDict["OtherNames"], Is.EqualTo(fromDict.OtherNames));
var toObjDict = fromDict.ConvertTo<ObjectDictionary>();
Assert.That(toObjDict["Name"], Is.EqualTo("Foo"));
Assert.That(toObjDict["OtherNames"], Is.EqualTo(fromDict.OtherNames));
}
| D |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.