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 | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/Serializers/ArraySerializerTests.cs | {
"start": 4969,
"end": 5060
} | private enum ____
{
None,
A,
B
}
| E |
csharp | nuke-build__nuke | source/Nuke.Build/Execution/ExecutableTargetFactory.cs | {
"start": 458,
"end": 5785
} | internal static class ____
{
public static IReadOnlyCollection<ExecutableTarget> CreateAll<T>(
T build,
params Expression<Func<T, Target>>[] defaultTargetExpressions)
where T : INukeBuild
{
var buildType = build.GetType();
var targetProperties = GetTargetProperties(build.GetType()).ToList();
var defaultTargets = defaultTargetExpressions.Select(x => x.Compile().Invoke(build)).ToList();
ExecutableTarget Create(PropertyInfo property)
{
var baseMembers = buildType
.Descendants(x => x.BaseType)
.Select(x => x.GetProperty(property.Name))
.Where(x => x != null && x.DeclaringType == x.ReflectedType)
.Reverse().ToList();
var definition = new TargetDefinition(property, build, new Stack<PropertyInfo>(baseMembers));
var factory = (Delegate) property.GetValue(build);
factory.DynamicInvokeUnwrap(definition);
return new ExecutableTarget
{
Name = definition.Name,
Member = property,
Definition = definition,
Intercept = definition.Intercept,
Description = definition.Description,
Factory = factory,
IsDefault = defaultTargets.Contains(factory),
DynamicConditions = definition.DynamicConditions,
StaticConditions = definition.StaticConditions,
DependencyBehavior = definition.DependencyBehavior,
ProceedAfterFailure = definition.IsProceedAfterFailure,
AssuredAfterFailure = definition.IsAssuredAfterFailure || factory is Cleanup,
DelegateRequirements = definition.DelegateRequirements,
ToolRequirements = definition.ToolRequirements,
Actions = definition.Actions,
Listed = !definition.IsInternal,
PartitionSize = definition.PartitionSize,
ArtifactProducts = definition.ArtifactProducts
};
}
var executables = targetProperties.Select(Create).ToList();
executables.ForEach(x => ApplyDependencies(x, executables));
return executables;
}
private static void ApplyDependencies(ExecutableTarget executable, IReadOnlyCollection<ExecutableTarget> executables)
{
IEnumerable<ExecutableTarget> GetDependencies(
Func<TargetDefinition, IReadOnlyList<Delegate>> directDependenciesSelector,
Func<TargetDefinition, IReadOnlyList<Delegate>> indirectDependenciesSelector)
{
foreach (var factoryDependency in directDependenciesSelector(executable.Definition))
yield return executables.Single(x => x.Factory == factoryDependency);
foreach (var otherExecutables in executables.Where(x => x != executable))
{
var otherDependencies = indirectDependenciesSelector(otherExecutables.Definition);
if (otherDependencies.Any(x => x == executable.Factory))
yield return otherExecutables;
}
}
executable.ExecutionDependencies.AddRange(GetDependencies(x => x.DependsOnTargets, x => x.DependentForTargets));
executable.OrderDependencies.AddRange(GetDependencies(x => x.AfterTargets, x => x.BeforeTargets));
executable.TriggerDependencies.AddRange(GetDependencies(x => x.TriggeredByTargets, x => x.TriggersTargets));
executable.Triggers.AddRange(GetDependencies(x => x.TriggersTargets, x => x.TriggeredByTargets));
Assert.True(executable.ExecutionDependencies
.Concat(executable.OrderDependencies)
.Concat(executable.TriggerDependencies)
.Concat(executable.Triggers)
.All(x => x != executable),
$"Target '{executable.Name}' cannot have a dependency on itself");
if (executable.Factory is Setup)
{
var cleanup = executables
.Where(x => x.Factory is Cleanup)
.Single(x => x.Member.DeclaringType == executable.Member.DeclaringType);
executable.Triggers.Add(cleanup);
cleanup.TriggerDependencies.Add(executable);
}
foreach (var artifactDependency in executable.Definition.ArtifactDependencies)
{
var dependency = executables.Single(x => x.Factory.Equals(artifactDependency.Key));
foreach (var artifacts in artifactDependency)
executable.ArtifactDependencies.AddRange(dependency, artifacts.Length > 0 ? artifacts : dependency.ArtifactProducts);
}
}
internal static IEnumerable<PropertyInfo> GetTargetProperties(Type buildType)
{
// TODO: static targets?
return buildType.GetAllMembers(
x => x is PropertyInfo property && new[] { typeof(Target), typeof(Setup), typeof(Cleanup) }.Contains(property.PropertyType),
bindingFlags: ReflectionUtility.Instance,
allowAmbiguity: false,
filterQuasiOverridden: true).Cast<PropertyInfo>();
}
}
| ExecutableTargetFactory |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/DragDrop/DragDropExtension.wasm.cs | {
"start": 15922,
"end": 16831
} | private struct ____
{
#pragma warning disable CS0649 // error CS0649: Field 'DragDropExtension.DataEntry.kind' is never assigned to, and will always have its default value null
[global::System.Text.Json.Serialization.JsonIncludeAttribute]
public int id;
[global::System.Text.Json.Serialization.JsonIncludeAttribute]
public string kind;
[global::System.Text.Json.Serialization.JsonIncludeAttribute]
public string type;
#pragma warning restore CS0649 // error CS0649: Field 'DragDropExtension.DataEntry.kind' is never assigned to, and will always have its default value null
/// <inheritdoc />
public override string ToString()
=> $"[#{id}: {kind} {type}]";
}
[JsonSerializable(typeof(DataEntry[]))]
[JsonSerializable(typeof(DataEntry))]
#if __WASM__
[JsonSerializable(typeof(NativeStorageItemInfo[]))]
[JsonSerializable(typeof(NativeStorageItemInfo))]
#endif
| DataEntry |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Midi/MidiChannelPressureMessage.cs | {
"start": 255,
"end": 1344
} | public partial class ____ : global::Windows.Devices.Midi.IMidiMessage
{
// Skipping already declared property Channel
// Skipping already declared property Pressure
// Skipping already declared property RawData
// Skipping already declared property Timestamp
// Skipping already declared property Type
// Skipping already declared method Windows.Devices.Midi.MidiChannelPressureMessage.MidiChannelPressureMessage(byte, byte)
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.MidiChannelPressureMessage(byte, byte)
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.Channel.get
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.Pressure.get
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.Timestamp.get
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.RawData.get
// Forced skipping of method Windows.Devices.Midi.MidiChannelPressureMessage.Type.get
// Processing: Windows.Devices.Midi.IMidiMessage
}
}
| MidiChannelPressureMessage |
csharp | abpframework__abp | framework/src/Volo.Abp.Core/System/IO/AbpStreamExtensions.cs | {
"start": 78,
"end": 2160
} | public static class ____
{
public static byte[] GetAllBytes(this Stream stream)
{
if (stream is MemoryStream memoryStream)
{
return memoryStream.ToArray();
}
using (var ms = stream.CreateMemoryStream())
{
return ms.ToArray();
}
}
public static async Task<byte[]> GetAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default)
{
if (stream is MemoryStream memoryStream)
{
return memoryStream.ToArray();
}
using (var ms = await stream.CreateMemoryStreamAsync(cancellationToken))
{
return ms.ToArray();
}
}
public static Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
return stream.CopyToAsync(
destination,
81920, //this is already the default value, but needed to set to be able to pass the cancellationToken
cancellationToken
);
}
public async static Task<MemoryStream> CreateMemoryStreamAsync(this Stream stream, CancellationToken cancellationToken = default)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream, cancellationToken);
if (stream.CanSeek)
{
stream.Position = 0;
}
memoryStream.Position = 0;
return memoryStream;
}
public static MemoryStream CreateMemoryStream(this Stream stream)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
if (stream.CanSeek)
{
stream.Position = 0;
}
memoryStream.Position = 0;
return memoryStream;
}
}
| AbpStreamExtensions |
csharp | xunit__xunit | src/xunit.v3.assert.tests/Asserts/EquivalenceAssertsTests.cs | {
"start": 7067,
"end": 7831
} | public class ____
{
[Fact]
public void Success()
{
Assert.Equivalent(new { x = 42, y = 2112 }, new { y = 2112, x = 42 });
}
[Fact]
public void Success_IgnorePrivateValue()
{
var expected = new PrivateMembersClass(1, "help");
var actual = new PrivateMembersClass(2, "me");
Assert.Equivalent(expected, actual);
}
[Fact]
public void Failure()
{
var ex = Record.Exception(() => Assert.Equivalent(new { x = 42, y = 2600 }, new { y = 2600, x = 2112 }));
Assert.IsType<EquivalentException>(ex);
Assert.Equal(
"Assert.Equivalent() Failure: Mismatched value on member 'x'" + Environment.NewLine +
"Expected: 42" + Environment.NewLine +
"Actual: 2112",
ex.Message
);
}
}
| AnonymousTypes_Compatible_Shallow |
csharp | smartstore__Smartstore | src/Smartstore/Threading/IAsyncState.cs | {
"start": 102,
"end": 557
} | public class ____
{
// used for serialization compatibility
public static readonly string Version = "1";
public object Progress { get; set; } = default!;
public DateTime CreatedOnUtc { get; set; }
public DateTime LastAccessUtc { get; set; }
public TimeSpan Duration { get; set; }
}
/// <summary>
/// Stores status information about long-running processes.
/// </summary>
| AsyncStateInfo |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12500.cs | {
"start": 114,
"end": 634
} | public class ____ : _IssuesUITest
{
public override string Issue => "Shell does not always raise Navigating event on Windows";
public Issue12500(TestDevice device) : base(device)
{
}
[Test]
[Category(UITestCategories.Shell)]
public void ShellNavigatingShouldTrigger()
{
App.WaitForElement("Issue12500MainPage");
App.WaitForElement("Events");
App.Tap("Events");
var result = App.WaitForElement("Issue12500EventPage").GetText();
Assert.That(result, Is.EqualTo("Navigating to //EventPage"));
}
}
| Issue12500 |
csharp | EventStore__EventStore | src/KurrentDB.Core/Messages/AuthenticationMessage.cs | {
"start": 468,
"end": 549
} | public partial class ____ : Message {
}
}
| AuthenticationProviderInitializationFailed |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.Composition.Tests/SourceSchemaValidationRules/ProvidesInvalidFieldsRuleTests.cs | {
"start": 60,
"end": 2017
} | public sealed class ____ : RuleTestBase
{
protected override object Rule { get; } = new ProvidesInvalidFieldsRule();
// In the following example, the @provides directive references a valid field ("hobbies") on the
// "UserDetails" type.
[Fact]
public void Validate_ProvidesValidFields_Succeeds()
{
AssertValid(
[
"""
type User @key(fields: "id") {
id: ID!
details: UserDetails @provides(fields: "hobbies")
}
type UserDetails {
hobbies: [String]
}
"""
]);
}
// In the following example, the @provides directive specifies a field named "unknownField"
// which is not defined on "UserDetails". This raises a PROVIDES_INVALID_FIELDS error.
[Fact]
public void Validate_ProvidesInvalidFields_Fails()
{
AssertInvalid(
[
"""
type User @key(fields: "id") {
id: ID!
details: UserDetails @provides(fields: "unknownField")
}
type UserDetails {
hobbies: [String]
}
"""
],
[
"""
{
"message": "The @provides directive on field 'User.details' in schema 'A' specifies an invalid field selection.",
"code": "PROVIDES_INVALID_FIELDS",
"severity": "Error",
"coordinate": "User.details",
"member": "provides",
"schema": "A",
"extensions": {
"errors": [
"The field 'unknownField' does not exist on the type 'UserDetails'."
]
}
}
"""
]);
}
}
| ProvidesInvalidFieldsRuleTests |
csharp | ShareX__ShareX | ShareX.UploadersLib/URLShorteners/IsgdURLShortener.cs | {
"start": 1117,
"end": 1524
} | public class ____ : URLShortenerService
{
public override UrlShortenerType EnumValue { get; } = UrlShortenerType.ISGD;
public override bool CheckConfig(UploadersConfig config) => true;
public override URLShortener CreateShortener(UploadersConfig config, TaskReferenceHelper taskInfo)
{
return new IsgdURLShortener();
}
}
| IsgdURLShortenerService |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ViewFeatures/test/Infrastructure/TempDataSerializerTestBase.cs | {
"start": 233,
"end": 9991
} | public abstract class ____
{
[Fact]
public void DeserializeTempData_ReturnsEmptyDictionary_DataIsEmpty()
{
// Arrange
var serializer = GetTempDataSerializer();
// Act
var tempDataDictionary = serializer.Deserialize(new byte[0]);
// Assert
Assert.NotNull(tempDataDictionary);
Assert.Empty(tempDataDictionary);
}
[Fact]
public void RoundTripTest_NullValue()
{
// Arrange
var key = "NullKey";
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, null }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
Assert.True(values.ContainsKey(key));
Assert.Null(values[key]);
}
[Theory]
[InlineData(-10)]
[InlineData(3340)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
public void RoundTripTest_IntValue(int value)
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, value },
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<int>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Theory]
[InlineData(null)]
[InlineData(10)]
public void RoundTripTest_NullableInt(int? value)
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, value },
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = (int?)values[key];
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_StringValue()
{
// Arrange
var key = "test-key";
var value = "test-value";
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, value },
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<string>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_Enum()
{
// Arrange
var key = "test-key";
var value = DayOfWeek.Friday;
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, value },
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = (DayOfWeek)values[key];
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_DateTimeValue()
{
// Arrange
var key = "test-key";
var value = new DateTime(2009, 1, 1, 12, 37, 43);
var testProvider = GetTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, value },
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<DateTime>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_GuidValue()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = Guid.NewGuid();
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<Guid>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public virtual void RoundTripTest_DateTimeToString()
{
// Documents the behavior of round-tripping a DateTime value as a string
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new DateTime(2009, 1, 1, 12, 37, 43);
var input = new Dictionary<string, object>
{
{ key, value.ToString(CultureInfo.InvariantCulture) }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<string>(values[key]);
Assert.Equal(value.ToString(CultureInfo.InvariantCulture), roundTripValue);
}
[Fact]
public virtual void RoundTripTest_StringThatIsNotCompliantGuid()
{
// Documents the behavior of round-tripping a Guid with a non-default format specifier
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = Guid.NewGuid();
var input = new Dictionary<string, object>
{
{ key, value.ToString("N") }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<string>(values[key]);
Assert.Equal(value.ToString("N"), roundTripValue);
}
[Fact]
public virtual void RoundTripTest_GuidToString()
{
// Documents the behavior of round-tripping a Guid value as a string
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = Guid.NewGuid();
var input = new Dictionary<string, object>
{
{ key, value.ToString() }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<Guid>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_CollectionOfInts()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new[] { 1, 2, 4, 3 };
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<int[]>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_ArrayOfStringss()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new[] { "Hello", "world" };
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<string[]>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_ListOfStringss()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new List<string> { "Hello", "world" };
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<string[]>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public void RoundTripTest_DictionaryOfString()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new Dictionary<string, string>
{
{ "Key1", "Value1" },
{ "Key2", "Value2" },
};
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<Dictionary<string, string>>(values[key]);
Assert.Equal(value, roundTripValue);
}
[Fact]
public virtual void RoundTripTest_DictionaryOfInt()
{
// Arrange
var key = "test-key";
var testProvider = GetTempDataSerializer();
var value = new Dictionary<string, int>
{
{ "Key1", 7 },
{ "Key2", 24 },
};
var input = new Dictionary<string, object>
{
{ key, value }
};
// Act
var bytes = testProvider.Serialize(input);
var values = testProvider.Deserialize(bytes);
// Assert
var roundTripValue = Assert.IsType<Dictionary<string, int>>(values[key]);
Assert.Equal(value, roundTripValue);
}
protected abstract TempDataSerializer GetTempDataSerializer();
}
| TempDataSerializerTestBase |
csharp | cake-build__cake | src/Cake/Features/Building/BuildFeature.cs | {
"start": 651,
"end": 1170
} | public interface ____
{
/// <summary>
/// Runs the build feature with the specified arguments and settings.
/// </summary>
/// <param name="arguments">The Cake arguments.</param>
/// <param name="settings">The build feature settings.</param>
/// <returns>The exit code.</returns>
int Run(ICakeArguments arguments, BuildFeatureSettings settings);
}
/// <summary>
/// Represents a feature for building Cake scripts.
/// </summary>
| IBuildFeature |
csharp | pythonnet__pythonnet | src/testing/indexertest.cs | {
"start": 1436,
"end": 1707
} | public class ____ : IndexerBase
{
public PrivateIndexerTest() : base()
{
}
private string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
| PrivateIndexerTest |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/MetricIdentifierV2.cs | {
"start": 641,
"end": 827
} | class ____ designed to be serialized and deserialized in YAML format and is
/// often used in conjunction with other Kubernetes resource configurations.
/// </remarks>
[YamlSerializable]
| is |
csharp | bitwarden__server | src/Api/Jobs/AliveJob.cs | {
"start": 78,
"end": 394
} | public class ____ : BaseJob
{
public AliveJob(ILogger<AliveJob> logger)
: base(logger) { }
protected override Task ExecuteJobAsync(IJobExecutionContext context)
{
_logger.LogInformation(Constants.BypassFiltersEventId, null, "It's alive!");
return Task.FromResult(0);
}
}
| AliveJob |
csharp | abpframework__abp | modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Claims/AbpOpenIddictClaimsPrincipalHandlerContext.cs | {
"start": 109,
"end": 643
} | public class ____
{
public IServiceProvider ScopeServiceProvider { get; }
public OpenIddictRequest OpenIddictRequest { get; }
public ClaimsPrincipal Principal { get;}
public AbpOpenIddictClaimsPrincipalHandlerContext(IServiceProvider scopeServiceProvider, OpenIddictRequest openIddictRequest, ClaimsPrincipal principal)
{
ScopeServiceProvider = scopeServiceProvider;
OpenIddictRequest = openIddictRequest;
Principal = principal;
}
}
| AbpOpenIddictClaimsPrincipalHandlerContext |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/PlatformRenderer.cs | {
"start": 149,
"end": 3546
} | internal class ____ : UIViewController
{
bool _disposed;
[Microsoft.Maui.Controls.Internals.Preserve(Conditional = true)]
internal PlatformRenderer(Platform platform)
{
Platform = platform;
}
public Platform Platform { get; set; }
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].GetSupportedInterfaceOrientations();
}
return base.GetSupportedInterfaceOrientations();
}
public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].PreferredInterfaceOrientationForPresentation();
}
return base.PreferredInterfaceOrientationForPresentation();
}
public override UIViewController ChildViewControllerForStatusBarHidden()
{
return (UIViewController)Platform.GetRenderer(Platform.Page);
}
public override UIViewController ChildViewControllerForStatusBarStyle()
{
return ChildViewControllers?.LastOrDefault();
}
public override UIViewController ChildViewControllerForHomeIndicatorAutoHidden
{
get => (UIViewController)Platform.GetRenderer(Platform.Page);
}
#pragma warning disable CA1416, CA1422 // TODO: The API has [UnsupportedOSPlatform("ios6.0")]
public override bool ShouldAutorotate()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].ShouldAutorotate();
}
return base.ShouldAutorotate();
}
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
}
return base.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
#pragma warning restore CA1416, CA1422
}
public override bool ShouldAutomaticallyForwardRotationMethods => true;
public override void ViewDidAppear(bool animated)
{
// For some reason iOS calls this after it's already been disposed
// while it's being replaced on the Window.RootViewController with a new MainPage
if (!_disposed)
Platform.DidAppear();
base.ViewDidAppear(animated);
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
Platform.LayoutSubviews();
}
public override void ViewWillAppear(bool animated)
{
// For some reason iOS calls this after it's already been disposed
// while it's being replaced on the Window.RootViewController with a new MainPage
if (!_disposed)
{
View.BackgroundColor = ColorExtensions.BackgroundColor;
Platform.WillAppear();
}
base.ViewWillAppear(animated);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
SetNeedsStatusBarAppearanceUpdate();
if (OperatingSystem.IsIOSVersionAtLeast(11))
SetNeedsUpdateOfHomeIndicatorAutoHidden();
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
Platform.UnsubscribeFromAlertsAndActionsSheets();
Platform.CleanUpPages();
}
base.Dispose(disposing);
}
}
}
| PlatformRenderer |
csharp | smartstore__Smartstore | src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingMethodHandler.cs | {
"start": 244,
"end": 5929
} | public class ____ : ICheckoutHandler
{
private readonly IShippingService _shippingService;
private readonly ShippingSettings _shippingSettings;
private readonly ShoppingCartSettings _shoppingCartSettings;
public ShippingMethodHandler(
IShippingService shippingService,
ShippingSettings shippingSettings,
ShoppingCartSettings shoppingCartSettings)
{
_shippingService = shippingService;
_shippingSettings = shippingSettings;
_shoppingCartSettings = shoppingCartSettings;
}
public async Task<CheckoutResult> ProcessAsync(CheckoutContext context)
{
var cart = context.Cart;
var customer = cart.Customer;
var ga = customer.GenericAttributes;
var options = ga.OfferedShippingOptions;
CheckoutError[] errors = null;
var saveAttributes = false;
if (!cart.IsShippingRequired)
{
if (ga.SelectedShippingOption != null || ga.OfferedShippingOptions != null)
{
ga.SelectedShippingOption = null;
ga.OfferedShippingOptions = null;
await ga.SaveChangesAsync();
}
return new(true, null, true);
}
if (context.Model != null
&& context.Model is string shippingOption
&& context.IsCurrentRoute(HttpMethods.Post, CheckoutActionNames.ShippingMethod))
{
var splittedOption = shippingOption.SplitSafe("___").ToArray();
if (splittedOption.Length != 2)
{
return new(false);
}
var selectedId = splittedOption[0].ToInt();
var providerSystemName = splittedOption[1];
if (options.IsNullOrEmpty())
{
// Shipping option was not found in customer attributes. Load via shipping service.
(options, errors) = await GetShippingOptions(context, providerSystemName);
}
else
{
// Loaded cached results. Filter result by a chosen shipping rate computation method.
options = options.Where(x => x.ShippingRateComputationMethodSystemName.EqualsNoCase(providerSystemName)).ToList();
}
var selectedOption = options.FirstOrDefault(x => x.ShippingMethodId == selectedId);
if (selectedOption != null)
{
ga.SelectedShippingOption = selectedOption;
ga.PreferredShippingOption = selectedOption;
await ga.SaveChangesAsync();
}
return new(selectedOption != null, errors);
}
if (options.IsNullOrEmpty())
{
(options, errors) = await GetShippingOptions(context);
if (options.Count == 0)
{
return new(false, errors);
}
// Performance optimization. Cache returned shipping options.
// We will use them later (after a customer has selected an option).
ga.OfferedShippingOptions = options;
saveAttributes = true;
}
var skip = _shippingSettings.SkipShippingIfSingleOption && options.Count == 1;
if (skip)
{
ga.SelectedShippingOption = options[0];
saveAttributes = true;
}
if (_shoppingCartSettings.QuickCheckoutEnabled && ga.SelectedShippingOption == null)
{
var preferredOption = ga.PreferredShippingOption;
if (preferredOption != null && preferredOption.ShippingMethodId != 0)
{
if (preferredOption.ShippingRateComputationMethodSystemName.HasValue())
{
ga.SelectedShippingOption = options.FirstOrDefault(x => x.ShippingMethodId == preferredOption.ShippingMethodId &&
x.ShippingRateComputationMethodSystemName.EqualsNoCase(preferredOption.ShippingRateComputationMethodSystemName));
}
ga.SelectedShippingOption ??= options
.Where(x => x.ShippingMethodId == preferredOption.ShippingMethodId)
.OrderBy(x => x.Rate)
.FirstOrDefault();
}
saveAttributes = ga.SelectedShippingOption != null;
}
if (saveAttributes)
{
await ga.SaveChangesAsync();
}
return new(ga.SelectedShippingOption != null, errors, skip);
}
private async Task<(List<ShippingOption> Options, CheckoutError[] Errors)> GetShippingOptions(CheckoutContext context, string providerSystemName = null)
{
CheckoutError[] errors = null;
var response = await _shippingService.GetShippingOptionsAsync(context.Cart, context.Cart.Customer.ShippingAddress, providerSystemName, context.Cart.StoreId);
if (response.ShippingOptions.Count == 0 && context.IsCurrentRoute(HttpMethods.Get, CheckoutActionNames.ShippingMethod))
{
errors = response.Errors
.Select(x => new CheckoutError(string.Empty, x))
.ToArray();
}
return (response.ShippingOptions, errors);
}
}
}
| ShippingMethodHandler |
csharp | NEventStore__NEventStore | src/NEventStore.Persistence.AcceptanceTests/PersistenceTests.Async.cs | {
"start": 13635,
"end": 14556
} | public class ____ : PersistenceEngineConcernAsync
{
private CommitAttempt? _attemptWithSameRevision;
private Exception? _thrown;
protected override async Task ContextAsync()
{
var commit = await Persistence.CommitSingleAsync();
_attemptWithSameRevision = commit!.StreamId.BuildAttempt();
}
protected override async Task BecauseAsync()
{
_thrown = await Catch.ExceptionAsync(() => Persistence.CommitAsync(_attemptWithSameRevision!, CancellationToken.None));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.Should().BeOfType<ConcurrencyException>();
}
}
// This test ensure the uniqueness of BucketId+StreamId+CommitSequence
// to avoid concurrency issues
#if MSTEST
[TestClass]
#endif
| when_committing_a_stream_with_the_same_revision |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Diagnostics/Diagnostics/ViewModels/EventTreeNode.cs | {
"start": 241,
"end": 4171
} | internal class ____ : EventTreeNodeBase
{
private readonly EventsPageViewModel _parentViewModel;
private bool _isRegistered;
private FiredEvent? _currentEvent;
public EventTreeNode(EventOwnerTreeNode parent, RoutedEvent @event, EventsPageViewModel vm)
: base(parent, @event.Name)
{
Event = @event ?? throw new ArgumentNullException(nameof(@event));
_parentViewModel = vm ?? throw new ArgumentNullException(nameof(vm));
}
public RoutedEvent Event { get; }
public override bool? IsEnabled
{
get => base.IsEnabled;
set
{
if (base.IsEnabled != value)
{
base.IsEnabled = value;
UpdateTracker();
if (Parent != null && _updateParent)
{
try
{
Parent._updateChildren = false;
Parent.UpdateChecked();
}
finally
{
Parent._updateChildren = true;
}
}
}
}
}
private void UpdateTracker()
{
if (IsEnabled.GetValueOrDefault() && !_isRegistered)
{
var allRoutes = RoutingStrategies.Direct | RoutingStrategies.Tunnel | RoutingStrategies.Bubble;
// FIXME: This leaks event handlers.
Event.AddClassHandler(typeof(object), HandleEvent, allRoutes, handledEventsToo: true);
Event.RouteFinished.Subscribe(HandleRouteFinished);
_isRegistered = true;
}
}
private void HandleEvent(object? sender, RoutedEventArgs e)
{
if (!_isRegistered || IsEnabled == false)
return;
if (sender is Visual v && v.DoesBelongToDevTool())
return;
var s = sender!;
var handled = e.Handled;
var route = e.Route;
var triggerTime = DateTime.Now;
void handler()
{
if (_currentEvent == null || !_currentEvent.IsPartOfSameEventChain(e))
{
_currentEvent = new FiredEvent(e, new EventChainLink(s, handled, route), triggerTime);
_parentViewModel.RecordedEvents.Add(_currentEvent);
while (_parentViewModel.RecordedEvents.Count > 100)
_parentViewModel.RecordedEvents.RemoveAt(0);
}
else
{
_currentEvent.AddToChain(new EventChainLink(s, handled, route));
}
};
if (!Dispatcher.UIThread.CheckAccess())
Dispatcher.UIThread.Post(handler);
else
handler();
}
private void HandleRouteFinished(RoutedEventArgs e)
{
if (!_isRegistered || IsEnabled == false)
return;
if (e.Source is Visual v && v.DoesBelongToDevTool())
return;
var s = e.Source;
var handled = e.Handled;
var route = e.Route;
void handler()
{
if (_currentEvent != null && handled)
{
var linkIndex = _currentEvent.EventChain.Count - 1;
var link = _currentEvent.EventChain[linkIndex];
link.Handled = true;
_currentEvent.HandledBy ??= link;
}
}
if (!Dispatcher.UIThread.CheckAccess())
Dispatcher.UIThread.Post(handler);
else
handler();
}
}
}
| EventTreeNode |
csharp | JoshClose__CsvHelper | src/CsvHelper/Configuration/Attributes/HasHeaderRecordAttribute.cs | {
"start": 543,
"end": 1202
} | public class ____ : Attribute, IClassMapper
{
/// <summary>
/// Gets a value indicating whether the CSV file has a header record.
/// </summary>
public bool HasHeaderRecord { get; private set; }
/// <summary>
/// A value indicating whether the CSV file has a header record.
/// </summary>
/// <param name="hasHeaderRecord">A value indicating whether the CSV file has a header record.</param>
public HasHeaderRecordAttribute(bool hasHeaderRecord = true)
{
HasHeaderRecord = hasHeaderRecord;
}
/// <inheritdoc />
public void ApplyTo(CsvConfiguration configuration)
{
configuration.HasHeaderRecord = HasHeaderRecord;
}
}
| HasHeaderRecordAttribute |
csharp | files-community__Files | src/Files.App.Controls/BreadcrumbBar/BreadcrumbBarItemAutomationPeer.cs | {
"start": 190,
"end": 1336
} | public partial class ____ : FrameworkElementAutomationPeer, IInvokeProvider
{
/// <summary>
/// Initializes a new instance of the BreadcrumbBarItemAutomationPeer class.
/// </summary>
/// <param name="owner"></param>
public BreadcrumbBarItemAutomationPeer(BreadcrumbBarItem owner) : base(owner)
{
}
// IAutomationPeerOverrides
protected override string GetLocalizedControlTypeCore()
{
return "breadcrumb bar item";
}
protected override object GetPatternCore(PatternInterface patternInterface)
{
if (patternInterface is PatternInterface.ExpandCollapse or PatternInterface.Invoke)
return this;
return base.GetPatternCore(patternInterface);
}
protected override string GetClassNameCore()
{
return nameof(BreadcrumbBarItem);
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.SplitButton;
}
protected override bool IsControlElementCore()
{
return true;
}
/// <inheritdoc/>
public void Invoke()
{
if (Owner is not BreadcrumbBarItem item)
return;
item.OnItemClicked();
}
}
}
| BreadcrumbBarItemAutomationPeer |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCropper/AspectRatioConfig.cs | {
"start": 264,
"end": 399
} | public class ____
{
public string Name { get; set; }
public double? AspectRatio { get; set; }
}
} | AspectRatioConfig |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/TestClasses/LogPropertiesExtensions.cs | {
"start": 8688,
"end": 9308
} | internal class ____
{
public int MyProperty { get; set; }
public override string ToString()
=> DateTime
.Parse("2021-11-15", CultureInfo.InvariantCulture)
.ToString("D", CultureInfo.InvariantCulture);
}
[LoggerMessage(1, LogLevel.Information, "Both {StringProperty} and {ComplexParam} as params")]
public static partial void LogMethodTwoParams(ILogger logger, string StringProperty, [LogProperties] ClassAsParam? complexParam);
[LoggerMessage(2, LogLevel.Information, "Testing non-nullable | ClassAsParam |
csharp | icsharpcode__SharpZipLib | src/ICSharpCode.SharpZipLib/Checksum/Adler32.cs | {
"start": 2318,
"end": 4835
} | public sealed class ____ : IChecksum
{
#region Instance Fields
/// <summary>
/// largest prime smaller than 65536
/// </summary>
private static readonly uint BASE = 65521;
/// <summary>
/// The CRC data checksum so far.
/// </summary>
private uint checkValue;
#endregion Instance Fields
/// <summary>
/// Initialise a default instance of <see cref="Adler32"></see>
/// </summary>
public Adler32()
{
Reset();
}
/// <summary>
/// Resets the Adler32 data checksum as if no update was ever called.
/// </summary>
public void Reset()
{
checkValue = 1;
}
/// <summary>
/// Returns the Adler32 data checksum computed so far.
/// </summary>
public long Value
{
get
{
return checkValue;
}
}
/// <summary>
/// Updates the checksum with the byte b.
/// </summary>
/// <param name="bval">
/// The data value to add. The high byte of the int is ignored.
/// </param>
public void Update(int bval)
{
// We could make a length 1 byte array and call update again, but I
// would rather not have that overhead
uint s1 = checkValue & 0xFFFF;
uint s2 = checkValue >> 16;
s1 = (s1 + ((uint)bval & 0xFF)) % BASE;
s2 = (s1 + s2) % BASE;
checkValue = (s2 << 16) + s1;
}
/// <summary>
/// Updates the Adler32 data checksum with the bytes taken from
/// a block of data.
/// </summary>
/// <param name="buffer">Contains the data to update the checksum with.</param>
public void Update(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
Update(new ArraySegment<byte>(buffer, 0, buffer.Length));
}
/// <summary>
/// Update Adler32 data checksum based on a portion of a block of data
/// </summary>
/// <param name = "segment">
/// The chunk of data to add
/// </param>
public void Update(ArraySegment<byte> segment)
{
//(By Per Bothner)
uint s1 = checkValue & 0xFFFF;
uint s2 = checkValue >> 16;
var count = segment.Count;
var offset = segment.Offset;
while (count > 0)
{
// We can defer the modulo operation:
// s1 maximally grows from 65521 to 65521 + 255 * 3800
// s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31
int n = 3800;
if (n > count)
{
n = count;
}
count -= n;
while (--n >= 0)
{
s1 = s1 + (uint)(segment.Array[offset++] & 0xff);
s2 = s2 + s1;
}
s1 %= BASE;
s2 %= BASE;
}
checkValue = (s2 << 16) | s1;
}
}
}
| Adler32 |
csharp | microsoft__semantic-kernel | dotnet/samples/Demos/TelemetryWithAppInsights/TestConfiguration.cs | {
"start": 181,
"end": 2083
} | public sealed class ____
{
private readonly IConfigurationRoot _configRoot;
private static TestConfiguration? s_instance;
private TestConfiguration(IConfigurationRoot configRoot)
{
this._configRoot = configRoot;
}
public static void Initialize(IConfigurationRoot configRoot)
{
s_instance = new TestConfiguration(configRoot);
}
public static AzureOpenAIConfig? AzureOpenAI => LoadSection<AzureOpenAIConfig>();
public static AzureAIInferenceConfig? AzureAIInference => LoadSection<AzureAIInferenceConfig>();
public static ApplicationInsightsConfig ApplicationInsights => LoadRequiredSection<ApplicationInsightsConfig>();
public static GoogleAIConfig? GoogleAI => LoadSection<GoogleAIConfig>();
public static HuggingFaceConfig? HuggingFace => LoadSection<HuggingFaceConfig>();
public static MistralAIConfig? MistralAI => LoadSection<MistralAIConfig>();
private static T? LoadSection<T>([CallerMemberName] string? caller = null)
{
if (s_instance is null)
{
throw new InvalidOperationException(
"TestConfiguration must be initialized with a call to Initialize(IConfigurationRoot) before accessing configuration values.");
}
if (string.IsNullOrEmpty(caller))
{
throw new ArgumentNullException(nameof(caller));
}
return s_instance._configRoot.GetSection(caller).Get<T>();
}
private static T LoadRequiredSection<T>([CallerMemberName] string? caller = null)
{
var section = LoadSection<T>(caller);
if (section is not null)
{
return section;
}
throw new KeyNotFoundException($"Could not find configuration section {caller}");
}
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor.
| TestConfiguration |
csharp | kgrzybek__modular-monolith-with-ddd | src/BuildingBlocks/Application/Events/IDomainEventNotification.cs | {
"start": 232,
"end": 328
} | public interface ____ : INotification
{
Guid Id { get; }
}
} | IDomainEventNotification |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Telemetry/GraphQLTelemetryProvider.cs | {
"start": 3913,
"end": 4596
} | record ____ operation type and the operation name (which may be specified within the
// document even if not specified in the request)
options.Listeners.Add(new TelemetryListener(this, activity, options));
// execute the request
ExecutionResult result;
try
{
result = await next(options).ConfigureAwait(false);
}
catch (Exception ex)
{
// Since DocumentExecuter catches and wraps most exceptions, this should only be thrown
// if the request was canceled or if ThrowOnUnhandledException is true. And since
// OperationCanceledExceptions are not a fault, we do not | the |
csharp | microsoft__semantic-kernel | dotnet/src/Agents/UnitTests/OpenAI/OpenAIResponseAgentExtensionsTests.cs | {
"start": 310,
"end": 8106
} | public sealed class ____
{
[Fact]
public void AsAIAgent_WithValidOpenAIResponseAgent_ReturnsSemanticKernelAIAgent()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient);
// Act
var result = responseAgent.AsAIAgent();
// Assert
Assert.NotNull(result);
Assert.IsType<SemanticKernelAIAgent>(result);
}
[Fact]
public void AsAIAgent_WithNullOpenAIResponseAgent_ThrowsArgumentNullException()
{
// Arrange
OpenAIResponseAgent nullAgent = null!;
// Act & Assert
Assert.Throws<ArgumentNullException>(() => nullAgent.AsAIAgent());
}
[Fact]
public void AsAIAgent_CreatesWorkingThreadFactoryStoreTrue()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient)
{
StoreEnabled = true
};
// Act
var result = responseAgent.AsAIAgent();
var thread = result.GetNewThread();
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<OpenAIResponseAgentThread>(threadAdapter.InnerThread);
}
[Fact]
public void AsAIAgent_CreatesWorkingThreadFactoryStoreFalse()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient)
{
StoreEnabled = false
};
// Act
var result = responseAgent.AsAIAgent();
var thread = result.GetNewThread();
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithNullAgentId_CreatesNewThread()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient)
{
StoreEnabled = true
};
var jsonElement = JsonSerializer.SerializeToElement((string?)null);
// Act
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<OpenAIResponseAgentThread>(threadAdapter.InnerThread);
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithValidAgentId_CreatesThreadWithId()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient)
{
StoreEnabled = true
};
var threadId = "test-agent-id";
var jsonElement = JsonSerializer.SerializeToElement(threadId);
// Act
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<OpenAIResponseAgentThread>(threadAdapter.InnerThread);
Assert.Equal(threadId, threadAdapter.InnerThread.Id);
}
[Fact]
public void AsAIAgent_ThreadSerializer_SerializesThreadId()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient)
{
StoreEnabled = true
};
var expectedThreadId = "test-thread-id";
var responseThread = new OpenAIResponseAgentThread(responseClient, expectedThreadId);
var jsonElement = JsonSerializer.SerializeToElement(expectedThreadId);
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Act
var serializedElement = thread.Serialize();
// Assert
Assert.Equal(JsonValueKind.String, serializedElement.ValueKind);
Assert.Equal(expectedThreadId, serializedElement.GetString());
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithNullJson_CreatesThreadWithEmptyChatHistory()
{
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient);
var jsonElement = JsonSerializer.SerializeToElement((string?)null);
// Act
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
var chatHistoryAgentThread = Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
Assert.Empty(chatHistoryAgentThread.ChatHistory);
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithChatHistory_CreatesThreadWithChatHistory()
{
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient);
var expectedChatHistory = new ChatHistory("mock message", AuthorRole.User);
var jsonElement = JsonSerializer.SerializeToElement(expectedChatHistory);
// Act
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
var chatHistoryAgentThread = Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
Assert.Single(chatHistoryAgentThread.ChatHistory);
var firstMessage = chatHistoryAgentThread.ChatHistory[0];
Assert.Equal(AuthorRole.User, firstMessage.Role);
Assert.Equal("mock message", firstMessage.Content);
}
[Fact]
public void AsAIAgent_ThreadSerializer_SerializesChatHistory()
{
// Arrange
var responseClient = new OpenAIResponseClient("model", "apikey");
var responseAgent = new OpenAIResponseAgent(responseClient);
var expectedChatHistory = new ChatHistory("mock message", AuthorRole.User);
var jsonElement = JsonSerializer.SerializeToElement(expectedChatHistory);
var result = responseAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Act
var serializedElement = thread.Serialize();
// Assert
Assert.Equal(JsonValueKind.Array, serializedElement.ValueKind);
Assert.Equal(1, serializedElement.GetArrayLength());
var firstMessage = serializedElement[0];
Assert.True(firstMessage.TryGetProperty("Role", out var roleProp));
Assert.Equal("user", roleProp.GetProperty("Label").GetString());
Assert.True(firstMessage.TryGetProperty("Items", out var itemsProp));
Assert.Equal(1, itemsProp.GetArrayLength());
var firstItem = itemsProp[0];
Assert.Equal("TextContent", firstItem.GetProperty("$type").GetString());
Assert.Equal("mock message", firstItem.GetProperty("Text").GetString());
}
}
| OpenAIResponseAgentExtensionsTests |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/ContentPartSettingsViewModel.cs | {
"start": 147,
"end": 447
} | public class ____
{
public bool Attachable { get; set; }
public bool Reusable { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
[BindNever]
public ContentPartDefinition ContentPartDefinition { get; set; }
}
| ContentPartSettingsViewModel |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Calls/PhoneLineWatcher.cs | {
"start": 305,
"end": 8937
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal PhoneLineWatcher()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.ApplicationModel.Calls.PhoneLineWatcherStatus Status
{
get
{
throw new global::System.NotImplementedException("The member PhoneLineWatcherStatus PhoneLineWatcher.Status is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=PhoneLineWatcherStatus%20PhoneLineWatcher.Status");
}
}
#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 void Start()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "void PhoneLineWatcher.Start()");
}
#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 void Stop()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "void PhoneLineWatcher.Stop()");
}
#endif
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineAdded.add
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineAdded.remove
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineRemoved.add
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineRemoved.remove
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineUpdated.add
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.LineUpdated.remove
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.EnumerationCompleted.add
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.EnumerationCompleted.remove
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.Stopped.add
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.Stopped.remove
// Forced skipping of method Windows.ApplicationModel.Calls.PhoneLineWatcher.Status.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Calls.PhoneLineWatcher, object> EnumerationCompleted
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, object> PhoneLineWatcher.EnumerationCompleted");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, object> PhoneLineWatcher.EnumerationCompleted");
}
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Calls.PhoneLineWatcher, global::Windows.ApplicationModel.Calls.PhoneLineWatcherEventArgs> LineAdded
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineAdded");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineAdded");
}
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Calls.PhoneLineWatcher, global::Windows.ApplicationModel.Calls.PhoneLineWatcherEventArgs> LineRemoved
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineRemoved");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineRemoved");
}
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Calls.PhoneLineWatcher, global::Windows.ApplicationModel.Calls.PhoneLineWatcherEventArgs> LineUpdated
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineUpdated");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, PhoneLineWatcherEventArgs> PhoneLineWatcher.LineUpdated");
}
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Calls.PhoneLineWatcher, object> Stopped
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, object> PhoneLineWatcher.Stopped");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Calls.PhoneLineWatcher", "event TypedEventHandler<PhoneLineWatcher, object> PhoneLineWatcher.Stopped");
}
}
#endif
}
}
| PhoneLineWatcher |
csharp | xunit__xunit | src/xunit.v2.tests/Extensions/ReflectionAbstractionExtensionsTests.cs | {
"start": 1413,
"end": 2306
} | public class ____
{
[Fact]
public static void WhenUsingReflectionTypeInfo_ReturnsExistingType()
{
var typeInfo = Mocks.ReflectionTypeInfo<ToRuntimeType>();
var result = typeInfo.ToRuntimeType();
Assert.NotNull(result);
Assert.Same(typeInfo.Type, result);
}
[Fact]
public static void WhenUsingNonReflectionTypeInfo_TypeExists_ReturnsType()
{
var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeType", assemblyFileName: "xunit.v2.tests.dll");
var result = typeInfo.ToRuntimeType();
Assert.NotNull(result);
Assert.Same(typeof(ToRuntimeType), result);
}
[Fact]
public static void WhenUsingNonReflectionTypeInfo_TypeDoesNotExist_ReturnsNull()
{
var typeInfo = Mocks.TypeInfo("UnknownType", assemblyFileName: "xunit.v2.tests.dll");
var result = typeInfo.ToRuntimeType();
Assert.Null(result);
}
}
}
| ToRuntimeType |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/ServerEventsFeature.cs | {
"start": 71666,
"end": 71733
} | public interface ____
{
void WriteEvent(string msg);
}
| IWriteEvent |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.MemoryCache/MemoryDocumentCache.cs | {
"start": 4793,
"end": 9001
} | record ____ always contains the query (or document id)
/// plus an extra property computed via the delegate supplied in options.
/// </summary>
private CacheItem GetCacheKey(ExecutionOptions options)
{
// Compute the extra value via the delegate. By default, this returns the schema.
var selector = _options.AdditionalCacheKeySelector
?? DefaultSelector;
var extra = selector.Invoke(options);
return new CacheItem(options, extra);
static object? DefaultSelector(ExecutionOptions options)
{
// pull the schema; omit the selector if the schema is not present
var schema = options.Schema;
if (schema == null)
return null;
// for schema-first or manually created schemas, return the schema instance
var schemaType = schema.GetType();
if (schemaType == typeof(Schema))
return schema;
// for code-first and type-first schemas, return the schema type, thus supporting scoped schemas
return schemaType;
}
}
/// <summary>
/// Gets a document in the cache. Must be thread-safe.
/// </summary>
/// <param name="options"><see cref="ExecutionOptions"/></param>
/// <returns>The cached document object. Returns <see langword="null"/> if no entry is found.</returns>
protected virtual ValueTask<GraphQLDocument?> GetAsync(ExecutionOptions options) =>
new(_memoryCache.TryGetValue<GraphQLDocument>(GetCacheKey(options), out var value) ? value : null);
/// <summary>
/// Sets a document in the cache. Must be thread-safe.
/// </summary>
/// <param name="options"><see cref="ExecutionOptions"/></param>
/// <param name="value">The document object to cache.</param>
protected virtual ValueTask SetAsync(ExecutionOptions options, GraphQLDocument value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
_memoryCache.Set(GetCacheKey(options), value, GetMemoryCacheEntryOptions(options, value));
return default;
}
/// <summary>
/// Creates an <see cref="ExecutionResult"/> containing the provided error.
/// Override this method to change the error response.
/// </summary>
protected virtual ExecutionResult CreateExecutionResult(ExecutionError error) => new(error);
/// <inheritdoc />
public virtual async Task<ExecutionResult> ExecuteAsync(ExecutionOptions options, ExecutionDelegate next)
{
if (options.Document == null && (options.Query != null || options.DocumentId != null))
{
// Ensure that both documentId and query are not provided.
if (options.DocumentId != null && options.Query != null)
return CreateExecutionResult(new InvalidRequestError());
var document = await GetAsync(options).ConfigureAwait(false);
if (document != null) // Cache hit.
{
options.Document = document;
// None of the default validation rules are dependent on the inputs; thus,
// a successfully cached document should not need additional validation.
options.ValidationRules = options.CachedDocumentValidationRules ?? Array.Empty<IValidationRule>();
}
var result = await next(options).ConfigureAwait(false);
if (result.Executed && // Validation succeeded.
document == null && // Cache miss.
result.Document != null)
{
// Note: At this point, the persisted document handler may have set Query.
// In that case, both Query and DocumentId are set and caching is based on DocumentId only.
await SetAsync(options, result.Document).ConfigureAwait(false);
}
return result;
}
else
{
return await next(options).ConfigureAwait(false);
}
}
/// <inheritdoc/>
public virtual float SortOrder => 200;
// Private cache key type that includes the query (or document id) plus an extra value.
| that |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Vulkan/UnmanagedInterop/VulkanEnums.cs | {
"start": 83308,
"end": 83633
} | enum ____
{
VK_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001,
// Provided by VK_VERSION_1_1
VK_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002,
// Provided by VK_KHR_device_group_creation
VK_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR = VK_MEMORY_HEAP_MULTI_INSTANCE_BIT,
}
| VkMemoryHeapFlags |
csharp | dotnet__aspire | src/Aspire.Hosting/api/Aspire.Hosting.cs | {
"start": 66306,
"end": 67030
} | public partial class ____ : IManifestExpressionProvider, IValueProvider, IValueWithReferences
{
public ConnectionStringReference(IResourceWithConnectionString resource, bool optional) { }
string IManifestExpressionProvider.ValueExpression { get { throw null; } }
System.Collections.Generic.IEnumerable<object> IValueWithReferences.References { get { throw null; } }
public bool Optional { get { throw null; } }
public IResourceWithConnectionString Resource { get { throw null; } }
System.Threading.Tasks.ValueTask<string?> IValueProvider.GetValueAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
}
public sealed | ConnectionStringReference |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedDropSearchIndexOperation.cs | {
"start": 766,
"end": 2094
} | public class ____ : IUnifiedEntityTestOperation
{
private readonly IMongoCollection<BsonDocument> _collection;
private readonly string _indexName;
public UnifiedDropSearchIndexOperation(IMongoCollection<BsonDocument> collection, string indexName)
{
_collection = Ensure.IsNotNull(collection, nameof(collection));
_indexName = Ensure.IsNotNullOrEmpty(indexName, nameof(indexName));
}
public OperationResult Execute(CancellationToken cancellationToken)
{
try
{
_collection.SearchIndexes.DropOne(_indexName, cancellationToken);
return OperationResult.Empty();
}
catch (Exception exception)
{
return OperationResult.FromException(exception);
}
}
public async Task<OperationResult> ExecuteAsync(CancellationToken cancellationToken)
{
try
{
await _collection.SearchIndexes.DropOneAsync(_indexName, cancellationToken);
return OperationResult.Empty();
}
catch (Exception exception)
{
return OperationResult.FromException(exception);
}
}
}
| UnifiedDropSearchIndexOperation |
csharp | dotnet__aspire | tests/Aspire.Hosting.Analyzers.Tests/ResourceNameAnalyzerTests.cs | {
"start": 296,
"end": 1797
} | public class ____
{
[Theory]
[ClassData(typeof(TestData.InvalidModelNames))]
public async Task ResourceNameInvalid(string resourceName)
{
Assert.False(ModelName.TryValidateName("Resource", resourceName, out var message));
var diagnostic = AppHostAnalyzer.Diagnostics.s_modelNameMustBeValid;
var test = AnalyzerTest.Create<AppHostAnalyzer>($$"""
using Aspire.Hosting;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddParameter("{{resourceName}}");
""",
[CompilerError(diagnostic.Id).WithLocation(5, 22).WithMessage(message)]);
await test.RunAsync();
}
[Theory]
[ClassData(typeof(TestData.InvalidModelNames))]
public async Task ResourceNameInvalidMultipleParameters(string resourceName)
{
Assert.False(ModelName.TryValidateName("Resource", $"{resourceName}-one", out var message1));
Assert.False(ModelName.TryValidateName("Resource", $"{resourceName}-two", out var message2));
var diagnostic = AppHostAnalyzer.Diagnostics.s_modelNameMustBeValid;
var test = AnalyzerTest.Create<AppHostAnalyzer>($$"""
using Aspire.Hosting;
using Aspire.Hosting.ApplicationModel;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddMultipleParameters(
"{{resourceName}}-one",
"{{resourceName}}-two");
| ResourceNameAnalyzerTests |
csharp | icsharpcode__SharpZipLib | src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs | {
"start": 1069,
"end": 1127
} | public class ____ : DeflaterOutputStream
{
| GZipOutputStream |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/ConditionalTests.cs | {
"start": 34525,
"end": 36078
} | interface ____ {
id: ID!
}
type Discussion implements Node {
id: ID!
title: String
}
""");
using var gateway = await CreateCompositeSchemaAsync(
[
("A", server1)
]);
// act
using var client = GraphQLHttpClient.Create(gateway.CreateClient());
var request = new OperationRequest(
"""
query testQuery($skip1: Boolean!, $skip2: Boolean!) {
... @skip(if: $skip1) {
... @skip(if: $skip2) {
# We need another selection here or our rewriter
# would (correctly) pull the skip down on the node field.
__typename
# Discussion:1
node(id: "RGlzY3Vzc2lvbjox") {
__typename
}
}
}
}
""",
variables: new Dictionary<string, object?> { ["skip1"] = true, ["skip2"] = true });
using var result = await client.PostAsync(
request,
new Uri("http://localhost:5000/graphql"));
// assert
await MatchSnapshotAsync(gateway, request, result);
}
[Fact]
public async Task NodeField_Skip_On_Shared_Selection()
{
// arrange
using var server1 = CreateSourceSchema(
"A",
"""
type Query {
node(id: ID!): Node @lookup @shareable
}
| Node |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Rendering/Composition/Animations/ExpressionAnimation.cs | {
"start": 1017,
"end": 2506
} | public sealed class ____ : CompositionAnimation
{
private string? _expression;
private Expression? _parsedExpression;
internal ExpressionAnimation(Compositor compositor) : base(compositor)
{
}
/// <summary>
/// The mathematical equation specifying how the animated value is calculated each frame.
/// The Expression is the core of an <see cref="ExpressionAnimation"/> and represents the equation
/// the system will use to calculate the value of the animation property each frame.
/// The equation is set on this property in the form of a string.
/// Although expressions can be defined by simple mathematical equations such as "2+2",
/// the real power lies in creating mathematical relationships where the input values can change frame over frame.
/// </summary>
public string? Expression
{
get => _expression;
set
{
_expression = value;
_parsedExpression = null;
}
}
private Expression ParsedExpression => _parsedExpression ??= ExpressionParser.Parse(_expression.AsSpan());
internal override IAnimationInstance CreateInstance(
ServerObject targetObject, ExpressionVariant? finalValue)
=> new ExpressionAnimationInstance(ParsedExpression,
targetObject, finalValue, CreateSnapshot());
}
}
| ExpressionAnimation |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesOptions.cs | {
"start": 33,
"end": 579
} | public class ____
{
private readonly List<SitemapsRazorPagesContentTypeOption> _contentTypeOptions = [];
public SitemapsRazorPagesOptions ConfigureContentType(string contentType, Action<SitemapsRazorPagesContentTypeOption> action)
{
var option = new SitemapsRazorPagesContentTypeOption(contentType);
action(option);
_contentTypeOptions.Add(option);
return this;
}
public IReadOnlyList<SitemapsRazorPagesContentTypeOption> ContentTypeOptions => _contentTypeOptions;
}
| SitemapsRazorPagesOptions |
csharp | grandnode__grandnode2 | src/Core/Grand.Data/IAuditInfoProvider.cs | {
"start": 24,
"end": 127
} | public interface ____
{
string GetCurrentUser();
DateTime GetCurrentDateTime();
} | IAuditInfoProvider |
csharp | dotnet__maui | src/Controls/tests/BindingSourceGen.UnitTests/IntegrationTests.cs | {
"start": 63932,
"end": 65387
} | public class ____
{
private Button Button {get; set;} = new Button();
public void SetBinding()
{
var entry = new Entry();
entry.SetBinding(Entry.TextProperty, static (MySourceClass sc) => sc.Button.Text);
}
}
}
""";
var result = SourceGenHelpers.Run(source);
var id = Math.Abs(result.Binding!.SimpleLocation!.GetHashCode());
AssertExtensions.AssertNoDiagnostics(result);
AssertExtensions.CodeIsEqual(
$$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a .NET MAUI source generator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
namespace System.Runtime.CompilerServices
{
using System;
using System.Diagnostics;
{{BindingCodeWriter.GeneratedCodeAttribute}}
[Conditional("DEBUG")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file | MySourceClass |
csharp | PrismLibrary__Prism | tests/Avalonia/Prism.Avalonia.Tests/Modularity/ModuleInitializerFixture.cs | {
"start": 6187,
"end": 6711
} | public class ____ : ModuleInitializer
{
public bool HandleModuleInitializerrorCalled;
public CustomModuleInitializerService(IContainerExtension containerFacade)
: base(containerFacade)
{
}
public override void HandleModuleInitializationError(IModuleInfo moduleInfo, string assemblyName, Exception exception)
{
HandleModuleInitializerrorCalled = true;
}
}
| CustomModuleInitializerService |
csharp | MonoGame__MonoGame | Tests/Framework/Components/DrawFrameNumberComponent.cs | {
"start": 382,
"end": 1221
} | class ____ : DrawableGameComponent {
private SpriteBatch _batch;
private SpriteFont _font;
public DrawFrameNumberComponent (Game game)
: base (game)
{
}
protected override void LoadContent ()
{
_batch = new SpriteBatch (Game.GraphicsDevice);
_font = Game.Content.Load<SpriteFont> (Paths.Font ("Default"));
}
protected override void UnloadContent ()
{
_batch.Dispose ();
_batch = null;
_font = null;
}
public override void Draw (GameTime gameTime)
{
var frameInfoSource = Game.Services.RequireService<IFrameInfoSource> ();
var frameInfo = frameInfoSource.FrameInfo;
// TODO: Add support for different placements and colors.
_batch.Begin ();
_batch.DrawString (_font, frameInfo.DrawNumber.ToString(), Vector2.Zero, Color.White);
_batch.End ();
}
}
}
| DrawFrameNumberComponent |
csharp | FluentValidation__FluentValidation | src/FluentValidation.Tests/ComplexValidationTester.cs | {
"start": 8656,
"end": 8843
} | public class ____ : AbstractValidator<InfiniteLoop> {
public InfiniteLoopValidator() {
RuleFor(x => x.Property).SetValidator(new InfiniteLoop2Validator());
}
}
| InfiniteLoopValidator |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsTypeNameOnUnionsTest.Client.cs | {
"start": 55971,
"end": 57134
} | public partial class ____ : global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsTypeNameOnUnions.State.HumanEntity, SearchHero_Search_Human>
{
private readonly global::StrawberryShake.IEntityStore _entityStore;
public SearchHero_Search_HumanFromHumanEntityMapper(global::StrawberryShake.IEntityStore entityStore)
{
_entityStore = entityStore ?? throw new global::System.ArgumentNullException(nameof(entityStore));
}
public SearchHero_Search_Human Map(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsTypeNameOnUnions.State.HumanEntity entity, global::StrawberryShake.IEntityStoreSnapshot? snapshot = null)
{
if (snapshot is null)
{
snapshot = _entityStore.CurrentSnapshot;
}
return new SearchHero_Search_Human(entity.__typename);
}
}
// StrawberryShake.CodeGeneration.CSharp.Generators.ResultFromEntityTypeMapperGenerator
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
| SearchHero_Search_HumanFromHumanEntityMapper |
csharp | AutoFixture__AutoFixture | Src/AutoFixture/Kernel/Postprocessor.cs | {
"start": 7427,
"end": 13864
} | class ____ the
/// supplied parameters.
/// </summary>
/// <param name="builder">The <see cref="ISpecimenBuilder"/> to decorate.</param>
/// <param name="action">The action to perform on the created specimen.</param>
/// <param name="specification">
/// A specification which is used to determine whether postprocessing should be performed
/// for a request.
/// </param>
[Obsolete("Use Postprocessor(ISpecimenBuilder, ISpecimenCommand, IRequestSpecification) instead", true)]
public Postprocessor(ISpecimenBuilder builder, Action<T, ISpecimenContext> action, IRequestSpecification specification)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (specification == null)
{
throw new ArgumentNullException(nameof(specification));
}
this.Builder = builder;
this.action = action;
this.Command = new ActionSpecimenCommand<T>(this.action);
this.Specification = specification;
}
/// <summary>
/// Initializes a new instance of the <see cref="Postprocessor{T}" />
/// class.
/// </summary>
/// <param name="builder">
/// The <see cref="ISpecimenBuilder"/> to decorate.
/// </param>
/// <param name="command">
/// The command to apply to the created specimen.
/// </param>
/// <param name="specification">
/// A specification which is used to determine whether postprocessing
/// should be performed for a request.
/// </param>
/// <exception cref="ArgumentNullException">
/// builder, command, or specification is null.
/// </exception>
public Postprocessor(
ISpecimenBuilder builder,
ISpecimenCommand command,
IRequestSpecification specification)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (command == null)
throw new ArgumentNullException(nameof(command));
if (specification == null)
throw new ArgumentNullException(nameof(specification));
this.Builder = builder;
this.Command = command;
this.Specification = specification;
this.action = (s, c) => this.Command.Execute(s, c);
}
/// <summary>
/// Gets the action to perform on created specimens.
/// </summary>
[Obsolete("Use the Command property instead.", true)]
public Action<T, ISpecimenContext> Action
{
get => this.action;
internal set => this.action = value;
}
/// <summary>
/// Gets the command, which is applied during postprocessing.
/// </summary>
/// <value>The command supplied via one of the constructors.</value>
public ISpecimenCommand Command { get; }
/// <summary>
/// Gets the decorated builder.
/// </summary>
public ISpecimenBuilder Builder { get; }
/// <summary>
/// Gets the filter that determines whether <see cref="Command"/> should be executed.
/// </summary>
public IRequestSpecification Specification { get; }
/// <summary>
/// Creates a new specimen based on a request and performs an action on the created
/// specimen.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">A context that can be used to create other specimens.</param>
/// <returns>
/// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
/// </returns>
/// <remarks>
/// <para>
/// The <paramref name="request"/> can be any object, but will often be a
/// <see cref="Type"/> or other <see cref="System.Reflection.MemberInfo"/> instances.
/// </para>
/// </remarks>
public object Create(object request, ISpecimenContext context)
{
var specimen = this.Builder.Create(request, context);
if (specimen == null)
return specimen;
var ns = specimen as NoSpecimen;
if (ns != null)
return ns;
if (!this.Specification.IsSatisfiedBy(request))
return specimen;
if (!(specimen is T))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
"The specimen returned by the decorated ISpecimenBuilder is not compatible with {0}.", typeof(T)));
}
this.Command.Execute(specimen, context);
return specimen;
}
/// <summary>Composes the supplied builders.</summary>
/// <param name="builders">The builders to compose.</param>
/// <returns>
/// A new <see cref="ISpecimenBuilderNode" /> instance containing
/// <paramref name="builders" /> as child nodes.
/// </returns>
public virtual ISpecimenBuilderNode Compose(IEnumerable<ISpecimenBuilder> builders)
{
if (builders == null) throw new ArgumentNullException(nameof(builders));
var composedBuilder = CompositeSpecimenBuilder.ComposeIfMultiple(builders);
var pp = new Postprocessor<T>(composedBuilder, this.Command, this.Specification);
pp.action = this.action;
return pp;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{ISpecimenBuilder}" /> that can be used to
/// iterate through the collection.
/// </returns>
public IEnumerator<ISpecimenBuilder> GetEnumerator()
{
yield return this.Builder;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
#pragma warning restore SA1402 // File may only contain a single type
}
| with |
csharp | CommunityToolkit__Maui | src/CommunityToolkit.Maui.UnitTests/Behaviors/ValidationBehaviorTests.cs | {
"start": 169,
"end": 5714
} | public class ____(ITestOutputHelper testOutputHelper) : BaseBehaviorTest<ValidationBehavior, VisualElement>(new MockValidationBehavior(), new View())
{
[Fact]
public void ValidateOnValueChanged()
{
// Arrange
var entry = new Entry
{
Text = "123"
};
var behavior = new MockValidationBehavior()
{
ExpectedValue = "321",
Flags = ValidationFlags.ValidateOnValueChanged
};
entry.Behaviors.Add(behavior);
// Act
entry.Text = "321";
// Assert
Assert.True(behavior.IsValid);
}
[Fact(Timeout = (int)TestDuration.Medium)]
public async Task ValidValue_ValidStyle()
{
// Arrange
var entry = new Entry
{
Text = "123"
};
var validStyle = new Style(entry.GetType());
validStyle.Setters.Add(new Setter() { Property = VisualElement.BackgroundColorProperty, Value = Colors.Green });
var invalidStyle = new Style(entry.GetType());
invalidStyle.Setters.Add(new Setter() { Property = VisualElement.BackgroundColorProperty, Value = Colors.Red });
var behavior = new MockValidationBehavior()
{
ExpectedValue = "321",
ValidStyle = validStyle,
InvalidStyle = invalidStyle
};
entry.Behaviors.Add(behavior);
// Act
entry.Text = "321";
await behavior.ForceValidate(TestContext.Current.CancellationToken);
// Assert
Assert.Equal(entry.Style, validStyle);
}
[Fact(Timeout = (int)TestDuration.Short)]
public async Task InvalidValue_InvalidStyle()
{
// Arrange
var entry = new Entry
{
Text = "123"
};
var validStyle = new Style(entry.GetType());
validStyle.Setters.Add(new Setter() { Property = VisualElement.BackgroundColorProperty, Value = Colors.Green });
var invalidStyle = new Style(entry.GetType());
invalidStyle.Setters.Add(new Setter() { Property = VisualElement.BackgroundColorProperty, Value = Colors.Red });
var behavior = new MockValidationBehavior()
{
ExpectedValue = "21",
ValidStyle = validStyle,
InvalidStyle = invalidStyle
};
entry.Behaviors.Add(behavior);
// Act
entry.Text = "321";
await behavior.ForceValidate(TestContext.Current.CancellationToken);
// Assert
Assert.Equal(entry.Style, invalidStyle, (style1, style2) =>
{
if (style1 == null || style2 == null)
{
return style1 == style2;
}
testOutputHelper.WriteLine($"Style1: {style1.Setters.Count} - Style2: {style2.Setters.Count}");
testOutputHelper.WriteLine($"Style1: {style1.TargetType.FullName} - Style2: {style2.TargetType.FullName}");
return style1.Setters.Count == style2.Setters.Count
&& style1.TargetType.FullName == style2.TargetType.FullName
&& style1.Setters.All(x => style2.Setters.Contains(x, new StyleSetterComparer(testOutputHelper)));
});
}
[Fact(Timeout = (int)TestDuration.Short)]
public async Task IsRunning()
{
// Arrange
var entry = new Entry
{
Text = "123"
};
var behavior = new MockValidationBehavior()
{
ExpectedValue = "321",
SimulateValidationDelay = true
};
entry.Behaviors.Add(behavior);
// Act
entry.Text = "321";
// Assert
Assert.False(behavior.IsRunning);
// Act
var forceValidateTask = behavior.ForceValidate(TestContext.Current.CancellationToken);
// Assert
Assert.True(behavior.IsRunning);
// Act
await forceValidateTask;
}
[Fact]
public void ForceValidateCommand()
{
// Arrange
var entry = new Entry
{
Text = "123"
};
var behavior = new MockValidationBehavior()
{
ExpectedValue = "321",
ForceValidateCommand = new Command<CancellationToken>(_ =>
{
entry.Text = "321";
})
};
entry.Behaviors.Add(behavior);
// Act
behavior.ForceValidateCommand.Execute(null);
// Assert
Assert.True(behavior.IsValid);
}
[Fact(Timeout = (int)TestDuration.Short)]
public async Task CancellationTokenExpired()
{
// Arrange
var behavior = new MockValidationBehavior();
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1));
var entry = new Entry
{
Text = "Hello"
};
entry.Behaviors.Add(behavior);
// Act
// Ensure CancellationToken expires
await Task.Delay(100, TestContext.Current.CancellationToken);
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () => await behavior.ForceValidate(cts.Token));
}
[Fact(Timeout = (int)TestDuration.Short)]
public async Task CancellationTokenCanceled()
{
// Arrange
var behavior = new MockValidationBehavior();
var cts = new CancellationTokenSource();
var entry = new Entry
{
Text = "Hello"
};
entry.Behaviors.Add(behavior);
// Act
// Ensure CancellationToken expires
await Task.Delay(100, TestContext.Current.CancellationToken);
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await cts.CancelAsync();
await behavior.ForceValidate(cts.Token);
});
}
[Fact]
public void TestRemoveValidationBindingWithBindingContext()
{
var behavior = new MockValidationBehavior();
var view = new View
{
BindingContext = new MockPageViewModel()
};
view.Behaviors.Add(behavior);
Assert.IsType<MockValidationBehavior>(Assert.Single(view.Behaviors), exactMatch: false);
view.Behaviors.Remove(behavior);
Assert.Empty(view.Behaviors);
}
[Fact]
public void TestRemoveValidationBindingWithoutBindingContext()
{
var behavior = new MockValidationBehavior();
var view = new View();
view.Behaviors.Add(behavior);
Assert.IsType<MockValidationBehavior>(Assert.Single(view.Behaviors), exactMatch: false);
view.Behaviors.Remove(behavior);
Assert.Empty(view.Behaviors);
}
}
| ValidationBehaviorTests |
csharp | louthy__language-ext | Samples/TestBed/TestCodeGen.cs | {
"start": 4438,
"end": 4711
} | public partial class ____ : Record<TestWith>
{
public readonly string Name;
public readonly string Surname;
public TestWith(string name, string surname)
{
Name = name;
Surname = surname;
}
}
| TestWith |
csharp | jellyfin__jellyfin | src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/IEntityFrameworkCoreLockingBehavior.cs | {
"start": 229,
"end": 1369
} | public interface ____
{
/// <summary>
/// Provides access to the builder to setup any connection related locking behavior.
/// </summary>
/// <param name="optionsBuilder">The options builder.</param>
void Initialise(DbContextOptionsBuilder optionsBuilder);
/// <summary>
/// Will be invoked when changes should be saved in the current locking behavior.
/// </summary>
/// <param name="context">The database context invoking the action.</param>
/// <param name="saveChanges">Callback for performing the actual save changes.</param>
void OnSaveChanges(JellyfinDbContext context, Action saveChanges);
/// <summary>
/// Will be invoked when changes should be saved in the current locking behavior.
/// </summary>
/// <param name="context">The database context invoking the action.</param>
/// <param name="saveChanges">Callback for performing the actual save changes.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges);
}
| IEntityFrameworkCoreLockingBehavior |
csharp | protobuf-net__protobuf-net | src/protobuf-net.Test/Meta/FieldOffset.cs | {
"start": 59,
"end": 2532
} | public class ____
{
[Fact]
public void ZeroOffsetIsFineEvenWhenCompiled()
{
var model = RuntimeTypeModel.Create();
var mt = model.Add(typeof(Foo), true);
model.CompileInPlace();
mt.ApplyFieldOffset(0); // fine because no-op
var proto = model.GetSchema(typeof(Foo), ProtoSyntax.Proto3);
Assert.Equal(@"syntax = ""proto3"";
package ProtoBuf.Meta;
message Bar {
int32 X = 1;
string Y = 2;
}
message Foo {
int32 A = 5;
string B = 6;
oneof subtype {
Bar Bar = 42;
}
}
", proto, ignoreLineEndingDifferences: true);
}
[Fact]
public void NonZeroOffsetFailsWhenCompiled()
{
var model = RuntimeTypeModel.Create();
var mt = model.Add(typeof(Foo), true);
model.CompileInPlace();
Assert.Throws<InvalidOperationException>(() => mt.ApplyFieldOffset(1));
}
[Fact]
public void NegativeOffsetFailsIfMakesInvalid()
{
var model = RuntimeTypeModel.Create();
var mt = model.Add(typeof(Foo), true);
Assert.Throws<ArgumentOutOfRangeException>(() => mt.ApplyFieldOffset(-10));
}
[Fact]
public void NegativeOffsetIsFineWhenLeavesValid()
{
var model = RuntimeTypeModel.Create();
var mt = model.Add(typeof(Foo), true);
mt.ApplyFieldOffset(-4); // leaves everything +ve
var proto = model.GetSchema(typeof(Foo), ProtoSyntax.Proto3);
Assert.Equal(@"syntax = ""proto3"";
package ProtoBuf.Meta;
message Bar {
int32 X = 1;
string Y = 2;
}
message Foo {
int32 A = 1;
string B = 2;
oneof subtype {
Bar Bar = 38;
}
}
", proto, ignoreLineEndingDifferences: true);
}
[Fact]
public void PositiveOffsetIsFineWhenLeavesValid()
{
var model = RuntimeTypeModel.Create();
var mt = model.Add(typeof(Foo), true);
mt.ApplyFieldOffset(4);
var proto = model.GetSchema(typeof(Foo), ProtoSyntax.Proto3);
Assert.Equal(@"syntax = ""proto3"";
package ProtoBuf.Meta;
message Bar {
int32 X = 1;
string Y = 2;
}
message Foo {
int32 A = 9;
string B = 10;
oneof subtype {
Bar Bar = 46;
}
}
", proto, ignoreLineEndingDifferences: true);
}
}
[ProtoContract]
[ProtoInclude(42, typeof(Bar))]
| FieldOffset |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/CursorEnumerable.cs | {
"start": 483,
"end": 2179
} | internal abstract class ____<T> : IEnumerable<T>, IScanningCursor, IAsyncEnumerable<T>
{
private readonly RedisBase redis;
private readonly ServerEndPoint? server;
private protected readonly int db;
private protected readonly CommandFlags flags;
private protected readonly int pageSize, initialOffset;
private protected readonly RedisValue initialCursor;
private volatile IScanningCursor? activeCursor;
private protected CursorEnumerable(RedisBase redis, ServerEndPoint? server, int db, int pageSize, in RedisValue cursor, int pageOffset, CommandFlags flags)
{
if (pageOffset < 0) throw new ArgumentOutOfRangeException(nameof(pageOffset));
this.redis = redis;
this.server = server;
this.db = db;
this.pageSize = pageSize;
this.flags = flags;
initialCursor = cursor;
initialOffset = pageOffset;
}
/// <summary>
/// Gets an enumerator for the sequence.
/// </summary>
public Enumerator GetEnumerator() => new Enumerator(this, default);
/// <summary>
/// Gets an enumerator for the sequence.
/// </summary>
public Enumerator GetAsyncEnumerator(CancellationToken cancellationToken) => new Enumerator(this, cancellationToken);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken cancellationToken) => GetAsyncEnumerator(cancellationToken);
internal readonly | CursorEnumerable |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/ViewModels/UserTaskEventViewModel.cs | {
"start": 55,
"end": 186
} | public class ____
{
public string Actions { get; set; }
public IList<string> Roles { get; set; } = [];
}
| UserTaskEventViewModel |
csharp | unoplatform__uno | src/SourceGenerators/Uno.UI.SourceGenerators.Tests/_Dotnet.cs | {
"start": 115,
"end": 625
} | internal record ____ _Dotnet(string Moniker, ReferenceAssemblies ReferenceAssemblies)
{
public ReferenceAssemblies WithUnoPackage(string version = "5.0.118")
=> ReferenceAssemblies.AddPackages([new PackageIdentity("Uno.WinUI", version)]);
public static _Dotnet Previous = new("net9.0", ReferenceAssemblies.Net.Net80);
public static _Dotnet Current = new("net10.0", ReferenceAssemblies.Net.Net90);
public static _Dotnet CurrentAndroid = new("net10.0-android", ReferenceAssemblies.Net.Net90Android);
}
| class |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs | {
"start": 344,
"end": 2655
} | public class ____(ITestOutputHelper output) : BaseTest(output)
{
/// <summary>
/// Demonstrates the usage of the HttpClientFactory with a custom resilience policy.
/// </summary>
[Fact]
public async Task RunAsync()
{
// Create a Kernel with the HttpClient
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
builder.Services.ConfigureHttpClientDefaults(c =>
{
// Use a standard resiliency policy, augmented to retry on 401 Unauthorized for this example
c.AddStandardResilienceHandler().Configure(o =>
{
o.Retry.ShouldHandle = args => ValueTask.FromResult(args.Outcome.Result?.StatusCode is HttpStatusCode.Unauthorized);
});
});
builder.Services.AddOpenAIChatCompletion("gpt-4", "BAD_KEY"); // OpenAI settings - you can set the OpenAI.ApiKey to an invalid value to see the retry policy in play
Kernel kernel = builder.Build();
var logger = kernel.LoggerFactory.CreateLogger(typeof(HttpClient_Resiliency));
const string Question = "How do I add a standard resilience handler in IHttpClientBuilder??";
logger.LogInformation("Question: {Question}", Question);
// The call to OpenAI will fail and be retried a few times before eventually failing.
// Retrying can overcome transient problems and thus improves resiliency.
try
{
// The InvokePromptAsync call will issue a request to OpenAI with an invalid API key.
// That will cause the request to fail with an HTTP status code 401. As the resilience
// handler is configured to retry on 401s, it'll reissue the request, and will do so
// multiple times until it hits the default retry limit, at which point this operation
// will throw an exception in response to the failure. All of the retries will be visible
// in the logging out to the console.
logger.LogInformation("Answer: {Result}", await kernel.InvokePromptAsync(Question));
}
catch (Exception ex)
{
logger.LogInformation("Error: {Message}", ex.Message);
}
}
}
| HttpClient_Resiliency |
csharp | MonoGame__MonoGame | MonoGame.Framework/Graphics/DeviceNotResetException.cs | {
"start": 656,
"end": 1558
} | class ____ a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public DeviceNotResetException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DeviceNotResetException"/> with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="inner">
/// The exception that is the cause of the current exception,
/// or a null reference if no inner exception is specified.
/// </param>
public DeviceNotResetException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| with |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Descriptors/NameDescriptors/UnionTypeNameDependencyDescriptor.cs | {
"start": 119,
"end": 1281
} | internal sealed class ____
: IUnionTypeNameDependencyDescriptor
{
private readonly IUnionTypeDescriptor _descriptor;
private readonly Func<ITypeDefinition, string> _createName;
public UnionTypeNameDependencyDescriptor(
IUnionTypeDescriptor descriptor,
Func<ITypeDefinition, string> createName)
{
_descriptor = descriptor
?? throw new ArgumentNullException(nameof(descriptor));
_createName = createName
?? throw new ArgumentNullException(nameof(createName));
}
public IUnionTypeDescriptor DependsOn<TDependency>()
where TDependency : IType
{
TypeNameHelper.AddNameFunction(_descriptor, _createName, typeof(TDependency));
return _descriptor;
}
public IUnionTypeDescriptor DependsOn(Type schemaType)
{
TypeNameHelper.AddNameFunction(_descriptor, _createName, schemaType);
return _descriptor;
}
public IUnionTypeDescriptor DependsOn(TypeReference typeReference)
{
TypeNameHelper.AddNameFunction(_descriptor, _createName, typeReference);
return _descriptor;
}
}
| UnionTypeNameDependencyDescriptor |
csharp | ServiceStack__ServiceStack.OrmLite | tests/ServiceStack.OrmLite.Tests/Issues/LoadReferencesNullReferenceIssue.cs | {
"start": 544,
"end": 1376
} | public class ____ : OrmLiteProvidersTestBase
{
public LoadReferencesNullReferenceIssue(DialectContext context) : base(context) {}
[Test]
public void Does_not_load_references_when_RefId_is_null()
{
using (var db = OpenDbConnection())
{
//db.DropAndCreateTable<UserAuth>(); //This test shouldn't query this table
db.DropAndCreateTable<UserAuth>();
db.DropAndCreateTable<DepartmentEntity>();
db.Insert(new DepartmentEntity { Name = "Dept A", Email = "asif@depta.com" });
var result = db.LoadSingleById<DepartmentEntity>("Dept A");
db.DropTable<DepartmentEntity>();
Assert.That(result, Is.Not.Null);
}
}
}
} | LoadReferencesNullReferenceIssue |
csharp | Xabaril__AspNetCore.Diagnostics.HealthChecks | src/HealthChecks.AzureApplicationInsights/DependencyInjection/AzureApplicationInsightsHealthCheckBuilderExtensions.cs | {
"start": 267,
"end": 2112
} | public static class ____
{
internal const string AZUREAPPLICATIONINSIGHTS_NAME = "azureappinsights";
/// <summary>
/// Add a health check for specified Azure Application Insights.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="instrumentationKey">The azure app insights instrumentation key.</param>
/// <param name="name">The health check name. Optional. If <c>null</c> the type name 'azureappinsights' will be used for the name.</param>
/// <param name="failureStatus">
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
/// </param>
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
/// <param name="timeout">An optional System.TimeSpan representing the timeout of the check.</param>
/// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
public static IHealthChecksBuilder AddAzureApplicationInsights(
this IHealthChecksBuilder builder,
string instrumentationKey,
string? name = default,
HealthStatus? failureStatus = default,
IEnumerable<string>? tags = default,
TimeSpan? timeout = default)
{
var registrationName = name ?? AZUREAPPLICATIONINSIGHTS_NAME;
builder.Services.AddHttpClient(registrationName);
return builder.Add(new HealthCheckRegistration(
registrationName,
sp => new AzureApplicationInsightsHealthCheck(instrumentationKey, sp.GetRequiredService<IHttpClientFactory>()),
failureStatus,
tags,
timeout));
}
}
| AzureApplicationInsightsHealthCheckBuilderExtensions |
csharp | microsoft__FASTER | cs/test/RecoveryTestTypes.cs | {
"start": 979,
"end": 2476
} | public class ____ : FunctionsBase<AdId, NumClicks, AdInput, Output, Empty>
{
// Read functions
public override bool SingleReader(ref AdId key, ref AdInput input, ref NumClicks value, ref Output dst, ref ReadInfo readInfo)
{
dst.value = value;
return true;
}
public override bool ConcurrentReader(ref AdId key, ref AdInput input, ref NumClicks value, ref Output dst, ref ReadInfo readInfo)
{
dst.value = value;
return true;
}
// RMW functions
public override bool InitialUpdater(ref AdId key, ref AdInput input, ref NumClicks value, ref Output output, ref RMWInfo rmwInfo)
{
value = input.numClicks;
return true;
}
public override bool InPlaceUpdater(ref AdId key, ref AdInput input, ref NumClicks value, ref Output output, ref RMWInfo rmwInfo)
{
Interlocked.Add(ref value.numClicks, input.numClicks.numClicks);
return true;
}
public override bool NeedCopyUpdate(ref AdId key, ref AdInput input, ref NumClicks oldValue, ref Output output, ref RMWInfo rmwInfo) => true;
public override bool CopyUpdater(ref AdId key, ref AdInput input, ref NumClicks oldValue, ref NumClicks newValue, ref Output output, ref RMWInfo rmwInfo)
{
newValue.numClicks += oldValue.numClicks + input.numClicks.numClicks;
return true;
}
}
}
| Functions |
csharp | dotnet__orleans | src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs | {
"start": 39690,
"end": 40543
} | public partial class ____ : TransactionTestRunnerBase
{
public TransactionRecoveryTestsRunner(TestingHost.TestCluster testCluster, System.Action<string> testOutput) : base(default!, default!) { }
protected void Log(string message) { }
protected virtual System.Threading.Tasks.Task TransactionWillRecoverAfterRandomSiloFailure(string transactionTestGrainClassName, int concurrent, bool gracefulShutdown) { throw null; }
public virtual System.Threading.Tasks.Task TransactionWillRecoverAfterRandomSiloGracefulShutdown(string transactionTestGrainClassName, int concurrent) { throw null; }
public virtual System.Threading.Tasks.Task TransactionWillRecoverAfterRandomSiloUnGracefulShutdown(string transactionTestGrainClassName, int concurrent) { throw null; }
}
public static | TransactionRecoveryTestsRunner |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/UseCases/JwtAuthProviderTests.cs | {
"start": 24891,
"end": 28092
} | class ____ : AppSelfHostBase
{
public AppHost()
: base(nameof(JwtAuthProviderIntegrationTests), typeof(JwtServices).Assembly) { }
public override void Configure(Container container)
{
// just for testing, create a privateKeyXml on every instance
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
[
new BasicAuthProvider(),
new CredentialsAuthProvider(),
new JwtAuthProvider
{
AuthKey = AuthKey,
RequireSecureConnection = false,
AllowInQueryString = true,
AllowInFormData = true,
}
]));
Plugins.Add(new RegistrationFeature());
container.Register<IAuthRepository>(c => new InMemoryAuthRepository());
var authRepo = GetAuthRepository();
authRepo.CreateUserAuth(new UserAuth
{
Id = 1,
UserName = Username,
FirstName = "First",
LastName = "Last",
DisplayName = "Display",
}, Password);
Plugins.Add(new RequestLogsFeature {
EnableSessionTracking = true,
ExcludeRequestDtoTypes = { typeof(Authenticate) },
});
}
}
protected virtual IJsonServiceClient GetClient() => new JsonServiceClient(Config.ListeningOn) {
UserName = Username,
Password = Password,
};
protected virtual IJsonServiceClient GetJwtClient()
{
var authClient = GetClient();
var authResponse = authClient.Post(new Authenticate());
return new JsonServiceClient(Config.ListeningOn) {
BearerToken = authClient.GetTokenCookie()
};
}
[Test]
public void Does_track_JWT_Sessions_calling_Authenticate_Services()
{
var client = GetJwtClient();
var request = new Secured { Name = "test" };
var response = client.Send(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var reqLogger = HostContext.TryResolve<IRequestLogger>();
var lastEntrySession = reqLogger.GetLatestLogs(1)[0]?.Session as AuthUserSession;
Assert.That(lastEntrySession, Is.Not.Null);
Assert.That(lastEntrySession.AuthProvider, Is.EqualTo("jwt"));
Assert.That(lastEntrySession.UserName, Is.EqualTo(Username));
}
[Test]
public void Does_track_JWT_Sessions_calling_non_Authenticate_Services()
{
var client = GetJwtClient();
var request = new Unsecure { Name = "test" };
var response = client.Send(request);
Assert.That(response.Name, Is.EqualTo(request.Name));
var reqLogger = HostContext.TryResolve<IRequestLogger>();
var lastEntrySession = reqLogger.GetLatestLogs(1)[0]?.Session as AuthUserSession;
Assert.That(lastEntrySession, Is.Not.Null);
Assert.That(lastEntrySession.AuthProvider, Is.EqualTo("jwt"));
Assert.That(lastEntrySession.UserName, Is.EqualTo(Username));
}
}
| AppHost |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.Core/Areas/Core/Controllers/EntityApiController.cs | {
"start": 321,
"end": 1378
} | public class ____ : Controller
{
private IRepository<Entity> _entityRepository;
public EntityApiController(IRepository<Entity> entityRepository)
{
_entityRepository = entityRepository;
}
[HttpGet]
public IActionResult Get(string entityTypeId, string name)
{
var query = _entityRepository.Query().Where(x => x.EntityType.IsMenuable);
if (!string.IsNullOrWhiteSpace(entityTypeId))
{
query = query.Where(x => x.EntityTypeId == entityTypeId);
}
if (!string.IsNullOrWhiteSpace(name))
{
query = query.Where(x => x.Name.Contains(name));
}
var entities = query.Select(x => new
{
Id = x.Id,
Name = x.Name,
Slug = x.Slug,
EntityTypeId = x.EntityTypeId,
EntityTypeName = x.EntityType.Name
});
return Ok(entities);
}
}
}
| EntityApiController |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/TypeCastRetry_Specs.cs | {
"start": 1061,
"end": 1320
} | class ____ :
Command
{
public CreateCommand()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public string Name { get; set; }
}
| CreateCommand |
csharp | Testably__Testably.Abstractions | Tests/Testably.Abstractions.Tests/FileSystem/FileInfo/AppendTextTests.cs | {
"start": 96,
"end": 999
} | public partial class ____
{
[Theory]
[AutoData]
public async Task AppendText_MissingFile_ShouldCreateFile(
string path, string appendText)
{
IFileInfo fileInfo = FileSystem.FileInfo.New(path);
using (StreamWriter stream = fileInfo.AppendText())
{
stream.Write(appendText);
}
await That(FileSystem.File.Exists(path)).IsTrue();
await That(FileSystem.File.ReadAllText(path)).IsEqualTo(appendText);
}
[Theory]
[AutoData]
public async Task AppendText_ShouldAddTextToExistingFile(
string path, string contents, string appendText)
{
FileSystem.File.WriteAllText(path, contents);
IFileInfo fileInfo = FileSystem.FileInfo.New(path);
using (StreamWriter stream = fileInfo.AppendText())
{
stream.Write(appendText);
}
await That(FileSystem.File.Exists(path)).IsTrue();
await That(FileSystem.File.ReadAllText(path)).IsEqualTo(contents + appendText);
}
}
| AppendTextTests |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/Mappings/ConstructorParameter/BooleanTrueValuesMapTests.cs | {
"start": 3123,
"end": 3347
} | private class ____ : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Boolean);
Parameter("id");
Parameter("boolean").TypeConverterOption.BooleanValues(true, true, "Bar");
}
}
}
}
| FooMap |
csharp | RicoSuter__NSwag | src/NSwag.CodeGeneration/Models/PropertyModel.cs | {
"start": 177,
"end": 1276
} | public class ____
{
/// <summary>
/// The key under which the <see cref="JsonProperty"/> is located in the parent JSON object
/// </summary>
public string Key { get; }
/// <summary>
/// The <see cref="JsonProperty"/> represented by this <see cref="PropertyModel"/>
/// </summary>
public JsonSchemaProperty JsonProperty { get; }
/// <summary>
/// The generated property name suitable for use in the target language
/// </summary>
public string Name { get; }
/// <summary>
/// Indicates whether the property is a collection
/// </summary>
public bool IsCollection => JsonProperty.Type == JsonObjectType.Array;
/// <inheritdoc />
public PropertyModel(string key, JsonSchemaProperty jsonProperty, string name)
{
Key = key;
JsonProperty = jsonProperty;
Name = name;
}
/// <inheritdoc />
public override string ToString()
{
return Name;
}
}
}
| PropertyModel |
csharp | abpframework__abp | modules/feature-management/src/Volo.Abp.FeatureManagement.Blazor/AbpFeatureManagementComponentBase.cs | {
"start": 133,
"end": 343
} | public abstract class ____ : AbpComponentBase
{
protected AbpFeatureManagementComponentBase()
{
LocalizationResource = typeof(AbpFeatureManagementResource);
}
}
| AbpFeatureManagementComponentBase |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue4720.cs | {
"start": 382,
"end": 2526
} | public class ____ : ContentPage
{
static int s_count;
Microsoft.Maui.Controls.WebView _webView;
public Issue4720WebPage()
{
Interlocked.Increment(ref s_count);
Debug.WriteLine($"++++++++ Issue4720WebPage : Constructor, count is {s_count}");
var label = new Microsoft.Maui.Controls.Label { Text = "Test case for GitHub issue #4720." };
var button = new Button { Text = "Close Page", AutomationId = "ClosePage" };
button.Clicked += ClosePageClicked;
var btnChangeExecutionMode = new Button { Text = "Change Execution Mode" };
btnChangeExecutionMode.Clicked += ChangeExecutionModeClicked;
#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning disable CS0618 // Type or member is obsolete
_webView = new Microsoft.Maui.Controls.WebView()
{
Source = new UrlWebViewSource { Url = "https://www.microsoft.com/" },
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Colors.Red
};
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore CS0618 // Type or member is obsolete
_webView.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().SetExecutionMode(WebViewExecutionMode.SeparateProcess);
var stackLayout = new StackLayout
{
label,
button,
btnChangeExecutionMode,
_webView
};
Content = stackLayout;
}
async void ClosePageClicked(object sender, EventArgs e)
{
await Navigation.PopAsync();
}
void ChangeExecutionModeClicked(object sender, EventArgs e)
{
if (_webView.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().GetExecutionMode() == WebViewExecutionMode.SameThread)
_webView.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().SetExecutionMode(WebViewExecutionMode.SeparateProcess);
else
_webView.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().SetExecutionMode(WebViewExecutionMode.SameThread);
}
~Issue4720WebPage()
{
Interlocked.Decrement(ref s_count);
Debug.WriteLine($"-------- Issue4720WebPage: Destructor, count is {s_count}");
}
}
| Issue4720WebPage |
csharp | dotnetcore__WTM | demo/WalkingTec.Mvvm.ConsoleDemo/ViewModels/StudentVMs/StudentListVM.cs | {
"start": 342,
"end": 3931
} | public partial class ____ : BasePagedListVM<Student_View, StudentSearcher>
{
protected override List<GridAction> InitGridAction()
{
return new List<GridAction>
{
this.MakeStandardAction("Student", GridActionStandardTypesEnum.Create, Localizer["Sys.Create"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.Edit, Localizer["Sys.Edit"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.Delete, Localizer["Sys.Delete"], "",dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.Details, Localizer["Sys.Details"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.BatchEdit, Localizer["Sys.BatchEdit"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.BatchDelete, Localizer["Sys.BatchDelete"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.Import, Localizer["Sys.Import"],"", dialogWidth: 800),
this.MakeStandardAction("Student", GridActionStandardTypesEnum.ExportExcel, Localizer["Sys.Export"],""),
};
}
protected override IEnumerable<IGridColumn<Student_View>> InitGridHeader()
{
return new List<GridColumn<Student_View>>{
this.MakeGridHeader(x => x.ID),
this.MakeGridHeader(x => x.Password),
this.MakeGridHeader(x => x.Email),
this.MakeGridHeader(x => x.Name),
this.MakeGridHeader(x => x.Sex),
this.MakeGridHeader(x => x.CellPhone),
this.MakeGridHeader(x => x.Address),
this.MakeGridHeader(x => x.ZipCode),
this.MakeGridHeader(x => x.PhotoId).SetFormat(PhotoIdFormat),
this.MakeGridHeader(x => x.IsValid),
this.MakeGridHeader(x => x.EnRollDate),
this.MakeGridHeader(x => x.MajorName_view),
this.MakeGridHeaderAction(width: 200)
};
}
private List<ColumnFormatInfo> PhotoIdFormat(Student_View entity, object val)
{
return new List<ColumnFormatInfo>
{
ColumnFormatInfo.MakeDownloadButton(ButtonTypesEnum.Button,entity.PhotoId),
ColumnFormatInfo.MakeViewButton(ButtonTypesEnum.Button,entity.PhotoId,640,480),
};
}
public override IOrderedQueryable<Student_View> GetSearchQuery()
{
var query = DC.Set<Student>()
.CheckContain(Searcher.Name, x => x.Name)
.CheckEqual(Searcher.IsValid, x => x.IsValid)
//.DPWhere(WtmContext, x => x.StudentMajor[0].MajorId)
.Select(x => new Student_View
{
ID = x.ID,
Password = x.Password,
Email = x.Email,
Name = x.Name,
Sex = x.Sex,
CellPhone = x.CellPhone,
Address = x.Address,
ZipCode = x.ZipCode,
PhotoId = x.PhotoId,
IsValid = x.IsValid,
EnRollDate = x.EnRollDate,
MajorName_view = x.StudentMajor.Select(y=>y.Major.MajorName).ToSepratedString(null,","),
})
.OrderBy(x => x.ID);
return query;
}
}
| StudentListVM |
csharp | bitwarden__server | src/Api/Dirt/Models/Response/OrganizationReportResponseModel.cs | {
"start": 73,
"end": 1446
} | public class ____
{
public Guid Id { get; set; }
public Guid OrganizationId { get; set; }
public string? ReportData { get; set; }
public string? ContentEncryptionKey { get; set; }
public string? SummaryData { get; set; }
public string? ApplicationData { get; set; }
public int? PasswordCount { get; set; }
public int? PasswordAtRiskCount { get; set; }
public int? MemberCount { get; set; }
public DateTime? CreationDate { get; set; } = null;
public DateTime? RevisionDate { get; set; } = null;
public OrganizationReportResponseModel(OrganizationReport organizationReport)
{
if (organizationReport == null)
{
return;
}
Id = organizationReport.Id;
OrganizationId = organizationReport.OrganizationId;
ReportData = organizationReport.ReportData;
ContentEncryptionKey = organizationReport.ContentEncryptionKey;
SummaryData = organizationReport.SummaryData;
ApplicationData = organizationReport.ApplicationData;
PasswordCount = organizationReport.PasswordCount;
PasswordAtRiskCount = organizationReport.PasswordAtRiskCount;
MemberCount = organizationReport.MemberCount;
CreationDate = organizationReport.CreationDate;
RevisionDate = organizationReport.RevisionDate;
}
}
| OrganizationReportResponseModel |
csharp | dotnet__orleans | test/DefaultCluster.Tests/GrainReferenceCastTests.cs | {
"start": 3180,
"end": 3939
} | interface ____ while maintaining state consistency.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public async Task CastMultifacetRWReference()
{
int newValue = 3;
IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(1);
// No Wait in this test case
IMultifacetReader reader = writer.AsReference<IMultifacetReader>();
await writer.SetValue(newValue);
Task<int> readAsync = reader.GetValue();
int result = await readAsync;
Assert.Equal(newValue, result);
}
/// <summary>
/// Tests casting between interfaces with explicit grain resolution.
/// Validates | views |
csharp | domaindrivendev__Swashbuckle.AspNetCore | test/Swashbuckle.AspNetCore.Annotations.Test/AnnotationsSchemaFilterTests.cs | {
"start": 181,
"end": 4459
} | public class ____
{
[Theory]
[InlineData(typeof(SwaggerAnnotatedType))]
[InlineData(typeof(SwaggerAnnotatedStruct))]
public void Apply_EnrichesSchemaMetadata_IfTypeDecoratedWithSwaggerSchemaAttribute(Type type)
{
var schema = new OpenApiSchema();
var context = new SchemaFilterContext(type: type, schemaGenerator: null, schemaRepository: null);
Subject().Apply(schema, context);
Assert.Equal($"Description for {type.Name}", schema.Description);
Assert.Equal(["StringWithSwaggerSchemaAttribute"], schema.Required);
Assert.Equal($"Title for {type.Name}", schema.Title);
}
[Fact]
public void Apply_EnrichesSchemaMetadata_IfParameterDecoratedWithSwaggerSchemaAttribute()
{
var schema = new OpenApiSchema();
var parameterInfo = typeof(FakeControllerWithSwaggerAnnotations)
.GetMethod(nameof(FakeControllerWithSwaggerAnnotations.ActionWithSwaggerSchemaAttribute))
.GetParameters()[0];
var context = new SchemaFilterContext(
type: parameterInfo.ParameterType,
schemaGenerator: null,
schemaRepository: null,
parameterInfo: parameterInfo);
Subject().Apply(schema, context);
Assert.Equal($"Description for param", schema.Description);
Assert.Equal("date", schema.Format);
}
[Theory]
[InlineData(typeof(SwaggerAnnotatedType), nameof(SwaggerAnnotatedType.StringWithSwaggerSchemaAttribute), true, true, false)]
[InlineData(typeof(SwaggerAnnotatedStruct), nameof(SwaggerAnnotatedStruct.StringWithSwaggerSchemaAttribute), true, true, false)]
public void Apply_EnrichesSchemaMetadata_IfPropertyDecoratedWithSwaggerSchemaAttribute(
Type declaringType,
string propertyName,
bool expectedReadOnly,
bool expectedWriteOnly,
bool expectedNullable)
{
var schema = new OpenApiSchema { Type = JsonSchemaType.Null };
var propertyInfo = declaringType
.GetProperty(propertyName);
var context = new SchemaFilterContext(
type: propertyInfo.PropertyType,
schemaGenerator: null,
schemaRepository: null,
memberInfo: propertyInfo);
Subject().Apply(schema, context);
Assert.Equal($"Description for {propertyName}", schema.Description);
Assert.Equal("date", schema.Format);
Assert.Equal(expectedReadOnly, schema.ReadOnly);
Assert.Equal(expectedWriteOnly, schema.WriteOnly);
Assert.Equal(expectedNullable, schema.Type.Value.HasFlag(JsonSchemaType.Null));
}
[Fact]
public void Apply_DoesNotModifyFlags_IfNotSpecifiedWithSwaggerSchemaAttribute()
{
var schema = new OpenApiSchema { ReadOnly = true, WriteOnly = true, Type = JsonSchemaType.Null };
var propertyInfo = typeof(SwaggerAnnotatedType)
.GetProperty(nameof(SwaggerAnnotatedType.StringWithSwaggerSchemaAttributeDescriptionOnly));
var context = new SchemaFilterContext(
type: propertyInfo.PropertyType,
schemaGenerator: null,
schemaRepository: null,
memberInfo: propertyInfo);
Subject().Apply(schema, context);
Assert.True(schema.ReadOnly);
Assert.True(schema.WriteOnly);
Assert.True(schema.Type.Value.HasFlag(JsonSchemaType.Null));
}
[Theory]
[InlineData(typeof(SwaggerAnnotatedType))]
[InlineData(typeof(SwaggerAnnotatedStruct))]
public void Apply_DelegatesToSpecifiedFilter_IfTypeDecoratedWithFilterAttribute(Type type)
{
var schema = new OpenApiSchema();
var context = new SchemaFilterContext(type: type, schemaGenerator: null, schemaRepository: null);
Subject().Apply(schema, context);
Assert.NotEmpty(schema.Extensions);
}
private static AnnotationsSchemaFilter Subject()
{
// A service provider is required from .NET 8 onwards.
// See https://learn.microsoft.com/dotnet/core/compatibility/extensions/8.0/activatorutilities-createinstance-null-provider.
var serviceProvider = new ServiceCollection().BuildServiceProvider();
return new AnnotationsSchemaFilter(serviceProvider);
}
}
| AnnotationsSchemaFilterTests |
csharp | abpframework__abp | modules/permission-management/src/Volo.Abp.PermissionManagement.EntityFrameworkCore/Volo/Abp/PermissionManagement/EntityFrameworkCore/PermissionManagementDbContext.cs | {
"start": 239,
"end": 885
} | public class ____ : AbpDbContext<PermissionManagementDbContext>, IPermissionManagementDbContext
{
public DbSet<PermissionGroupDefinitionRecord> PermissionGroups { get; set; }
public DbSet<PermissionDefinitionRecord> Permissions { get; set; }
public DbSet<PermissionGrant> PermissionGrants { get; set; }
public PermissionManagementDbContext(DbContextOptions<PermissionManagementDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ConfigurePermissionManagement();
}
}
| PermissionManagementDbContext |
csharp | duplicati__duplicati | Duplicati/UnitTest/Issue5196.cs | {
"start": 1375,
"end": 4005
} | public class ____ : BasicSetupHelper
{
[Test]
[Category("Targeted")]
public void RunCommands()
{
var testopts = TestOptions;
testopts["upload-unchanged-backups"] = "true";
testopts["blocksize"] = "50kb";
var data = new byte[1024 * 1024 * 10];
File.WriteAllBytes(Path.Combine(DATAFOLDER, "a"), data);
using (var c = new Library.Main.Controller("file://" + TARGETFOLDER, testopts, null))
{
var r = c.Backup(new string[] { DATAFOLDER });
Assert.AreEqual(0, r.Errors.Count());
Assert.AreEqual(0, r.Warnings.Count());
Assert.AreEqual(1, r.AddedFiles);
var pr = (Library.Interface.IParsedBackendStatistics)r.BackendStatistics;
if (pr.KnownFileSize == 0 || pr.KnownFileCount != 3 || pr.BackupListCount != 1)
throw new Exception(string.Format("Failed to get stats from remote backend: {0}, {1}, {2}", pr.KnownFileSize, pr.KnownFileCount, pr.BackupListCount));
System.Threading.Thread.Sleep(3000);
r = c.Backup(new string[] { DATAFOLDER });
Assert.AreEqual(0, r.Errors.Count());
Assert.AreEqual(0, r.Warnings.Count());
pr = (Library.Interface.IParsedBackendStatistics)r.BackendStatistics;
if (pr.KnownFileSize == 0 || pr.KnownFileCount != 4 || pr.BackupListCount != 2)
throw new Exception(string.Format("Failed to get stats from remote backend: {0}, {1}, {2}", pr.KnownFileSize, pr.KnownFileCount, pr.BackupListCount));
var versions = c.List().Filesets.ToList();
using (var tempDbPath = new Library.Utility.TempFile())
{
testopts["dbpath"] = tempDbPath;
testopts["repair-only-paths"] = "true";
testopts.Remove("blocksize");
testopts["time"] = Library.Utility.Utility.SerializeDateTime(versions[0].Time);
var rcr1 = c.UpdateDatabaseWithVersions();
testopts["time"] = Library.Utility.Utility.SerializeDateTime(versions[1].Time);
var rcr2 = c.UpdateDatabaseWithVersions();
File.Delete(tempDbPath);
testopts["repair-only-paths"] = "true";
testopts["blocksize"] = "25kb";
try
{
c.UpdateDatabaseWithVersions();
throw new Exception("Expected an exception when changing blocksize");
}
catch (InvalidManifestException)
{
}
}
}
}
}
| Issue5196 |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Authentication.Web.Provider/WebAccountProviderRequestTokenOperation.cs | {
"start": 319,
"end": 6661
} | public partial class ____ : global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderTokenOperation, global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderOperation, global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderUIReportOperation, global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderBaseReportOperation
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal WebAccountProviderRequestTokenOperation()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Security.Authentication.Web.Provider.WebAccountProviderOperationKind Kind
{
get
{
throw new global::System.NotImplementedException("The member WebAccountProviderOperationKind WebAccountProviderRequestTokenOperation.Kind is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=WebAccountProviderOperationKind%20WebAccountProviderRequestTokenOperation.Kind");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.DateTimeOffset CacheExpirationTime
{
get
{
throw new global::System.NotImplementedException("The member DateTimeOffset WebAccountProviderRequestTokenOperation.CacheExpirationTime is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DateTimeOffset%20WebAccountProviderRequestTokenOperation.CacheExpirationTime");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation", "DateTimeOffset WebAccountProviderRequestTokenOperation.CacheExpirationTime");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Security.Authentication.Web.Provider.WebProviderTokenRequest ProviderRequest
{
get
{
throw new global::System.NotImplementedException("The member WebProviderTokenRequest WebAccountProviderRequestTokenOperation.ProviderRequest is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=WebProviderTokenRequest%20WebAccountProviderRequestTokenOperation.ProviderRequest");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Collections.Generic.IList<global::Windows.Security.Authentication.Web.Provider.WebProviderTokenResponse> ProviderResponses
{
get
{
throw new global::System.NotImplementedException("The member IList<WebProviderTokenResponse> WebAccountProviderRequestTokenOperation.ProviderResponses is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IList%3CWebProviderTokenResponse%3E%20WebAccountProviderRequestTokenOperation.ProviderResponses");
}
}
#endif
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation.ProviderRequest.get
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation.ProviderResponses.get
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation.CacheExpirationTime.set
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation.CacheExpirationTime.get
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation.Kind.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void ReportUserCanceled()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation", "void WebAccountProviderRequestTokenOperation.ReportUserCanceled()");
}
#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 void ReportCompleted()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation", "void WebAccountProviderRequestTokenOperation.ReportCompleted()");
}
#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 void ReportError(global::Windows.Security.Authentication.Web.Core.WebProviderError value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderRequestTokenOperation", "void WebAccountProviderRequestTokenOperation.ReportError(WebProviderError value)");
}
#endif
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderTokenOperation
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderOperation
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderUIReportOperation
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderBaseReportOperation
}
}
| WebAccountProviderRequestTokenOperation |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/Core/Servers/ServerDescriptionTests.cs | {
"start": 22812,
"end": 23095
} | internal static class ____
{
public static bool Equals(this ServerDescription serverDescription, Exception x, Exception y)
{
return (bool)Reflector.InvokeStatic(typeof(ServerDescription), nameof(Equals), x, y);
}
}
}
| ServerDescriptionReflector |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Cast.cs | {
"start": 138,
"end": 444
} | partial class ____
{
public static IUniTaskAsyncEnumerable<TResult> Cast<TResult>(this IUniTaskAsyncEnumerable<Object> source)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new Cast<TResult>(source);
}
}
| UniTaskAsyncEnumerable |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Bugs/Issue3370.cs | {
"start": 2037,
"end": 2229
} | public class ____ : InputObjectGraphType<TestInput>
{
public TestInputType()
{
Field<NonNullGraphType<StringGraphType>>("prop1");
}
}
| TestInputType |
csharp | grandnode__grandnode2 | src/Modules/Grand.Module.Api/Infrastructure/Mapper/Profiles/ProductAttributeMappingProfile.cs | {
"start": 180,
"end": 630
} | public class ____ : Profile, IAutoMapperProfile
{
public ProductAttributeMappingProfile()
{
CreateMap<ProductAttributeMappingDto, ProductAttributeMapping>();
CreateMap<ProductAttributeMapping, ProductAttributeMappingDto>();
CreateMap<ProductAttributeValueDto, ProductAttributeValue>();
CreateMap<ProductAttributeValue, ProductAttributeValueDto>();
}
public int Order => 1;
} | ProductAttributeMappingProfile |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/src/devices/AzureStorageDevice/AzureCheckpointNamingScheme.cs | {
"start": 341,
"end": 2892
} | public class ____ : ICheckpointNamingScheme
{
/// <inheritdoc />
public string BaseName { get; }
/// <summary>
/// Create instance of default naming scheme
/// </summary>
/// <param name="baseName">Overall location specifier (e.g., local path or cloud container name)</param>
public AzureCheckpointNamingScheme(string baseName = "")
{
BaseName = baseName;
}
/// <inheritdoc />
public FileDescriptor LogCheckpointBase(Guid token) => new(string.Join('/', LogCheckpointBasePath, token.ToString()), null);
/// <inheritdoc />
public FileDescriptor LogCheckpointMetadata(Guid token) => new(string.Join('/', LogCheckpointBasePath, token.ToString()), "info.dat");
/// <inheritdoc />
public FileDescriptor LogSnapshot(Guid token) => new(string.Join('/', LogCheckpointBasePath, token.ToString()), "snapshot.dat");
/// <inheritdoc />
public FileDescriptor ObjectLogSnapshot(Guid token) => new(string.Join('/', LogCheckpointBasePath, token.ToString()), "snapshot.obj.dat");
/// <inheritdoc />
public FileDescriptor DeltaLog(Guid token) => new(string.Join('/', LogCheckpointBasePath, token.ToString()), "delta.dat");
/// <inheritdoc />
public FileDescriptor IndexCheckpointBase(Guid token) => new(string.Join('/', IndexCheckpointBasePath, token.ToString()), null);
/// <inheritdoc />
public FileDescriptor IndexCheckpointMetadata(Guid token) => new(string.Join('/', IndexCheckpointBasePath, token.ToString()), "info.dat");
/// <inheritdoc />
public FileDescriptor HashTable(Guid token) => new(string.Join('/', IndexCheckpointBasePath, token.ToString()), "ht.dat");
/// <inheritdoc />
public FileDescriptor TsavoriteLogCommitMetadata(long commitNumber) => new(TsavoriteLogCommitBasePath, $"commit.{commitNumber}");
/// <inheritdoc />
public Guid Token(FileDescriptor fileDescriptor) => Guid.Parse(new DirectoryInfo(fileDescriptor.directoryName).Name);
/// <inheritdoc />
public long CommitNumber(FileDescriptor fileDescriptor) => long.Parse(fileDescriptor.fileName.Split('.')[^2]);
/// <inheritdoc />
public string IndexCheckpointBasePath => "index-checkpoints";
/// <inheritdoc />
public string LogCheckpointBasePath => "cpr-checkpoints";
/// <inheritdoc />
public string TsavoriteLogCommitBasePath => "log-commits";
}
} | AzureCheckpointNamingScheme |
csharp | dotnet__maui | src/Controls/tests/ManualTests/Performance/CollectionViewPool/Converters/BoolToGridLengthConverter.cs | {
"start": 75,
"end": 842
} | public class ____ : IValueConverter
{
public BoolToGridLengthConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Boolean && !(bool)value)
return new GridLength(0);
if (parameter?.ToString()?.Equals("auto", StringComparison.OrdinalIgnoreCase) ?? false)
return GridLength.Auto;
double numParam = -1;
if (parameter != null && double.TryParse(parameter.ToString(), out numParam))
return new GridLength(numParam, GridUnitType.Absolute);
return new GridLength(1, GridUnitType.Star);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| BoolToGridLengthConverter |
csharp | dotnetcore__Util | src/Util.Ui.NgZorro/Components/Anchors/Builders/AnchorBuilder.cs | {
"start": 192,
"end": 3121
} | public class ____ : AngularTagBuilder {
/// <summary>
/// 配置
/// </summary>
private readonly Config _config;
/// <summary>
/// 初始化锚点标签生成器
/// </summary>
public AnchorBuilder( Config config ) : base( config,"nz-anchor" ) {
_config = config;
}
/// <summary>
/// 配置是否固定模式
/// </summary>
public AnchorBuilder Affix() {
AttributeIfNotEmpty( "[nzAffix]", _config.GetValue( UiConst.Affix ) );
return this;
}
/// <summary>
/// 配置区域边界
/// </summary>
public AnchorBuilder Bounds() {
AttributeIfNotEmpty( "[nzBounds]", _config.GetValue( UiConst.Bounds ) );
return this;
}
/// <summary>
/// 配置顶部偏移量
/// </summary>
public AnchorBuilder OffsetTop() {
AttributeIfNotEmpty( "[nzOffsetTop]", _config.GetValue( UiConst.OffsetTop ) );
return this;
}
/// <summary>
/// 配置固定模式是否显示小圆点
/// </summary>
public AnchorBuilder ShowInkInFixed() {
AttributeIfNotEmpty( "[nzShowInkInFixed]", _config.GetValue( UiConst.ShowInkInFixed ) );
return this;
}
/// <summary>
/// 配置容器
/// </summary>
public AnchorBuilder Container() {
AttributeIfNotEmpty( "nzContainer", _config.GetValue( UiConst.Container ) );
AttributeIfNotEmpty( "[nzContainer]", _config.GetValue( AngularConst.BindContainer ) );
return this;
}
/// <summary>
/// 配置自定义高亮的锚点
/// </summary>
public AnchorBuilder CurrentAnchor() {
AttributeIfNotEmpty( "nzCurrentAnchor", _config.GetValue( UiConst.CurrentAnchor ) );
AttributeIfNotEmpty( "[nzCurrentAnchor]", _config.GetValue( AngularConst.BindCurrentAnchor ) );
return this;
}
/// <summary>
/// 配置锚点滚动偏移量
/// </summary>
public AnchorBuilder TargetOffset() {
AttributeIfNotEmpty( "[nzTargetOffset]", _config.GetValue( UiConst.TargetOffset ) );
return this;
}
/// <summary>
/// 配置方向
/// </summary>
public AnchorBuilder Direction() {
AttributeIfNotEmpty( "nzDirection", _config.GetValue<AnchorDirection?>( UiConst.Direction )?.Description() );
AttributeIfNotEmpty( "[nzDirection]", _config.GetValue( AngularConst.BindDirection ) );
return this;
}
/// <summary>
/// 配置事件
/// </summary>
public AnchorBuilder Events() {
AttributeIfNotEmpty( "(nzClick)", _config.GetValue( UiConst.OnClick ) );
AttributeIfNotEmpty( "(nzChange)", _config.GetValue( UiConst.OnChange ) );
AttributeIfNotEmpty( "(nzScroll)", _config.GetValue( UiConst.OnScroll ) );
return this;
}
/// <summary>
/// 配置
/// </summary>
public override void Config() {
base.Config();
Affix().Bounds().OffsetTop().ShowInkInFixed()
.Container().CurrentAnchor().TargetOffset()
.Direction()
.Events();
}
} | AnchorBuilder |
csharp | dotnet__efcore | test/EFCore.Relational.Specification.Tests/Query/Associations/ComplexTableSplitting/ComplexTableSplittingMiscellaneousRelationalTestBase.cs | {
"start": 296,
"end": 905
} | public abstract class ____<TFixture> : ComplexPropertiesMiscellaneousTestBase<TFixture>
where TFixture : ComplexTableSplittingRelationalFixtureBase, new()
{
public ComplexTableSplittingMiscellaneousRelationalTestBase(TFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
fixture.TestSqlLoggerFactory.Clear();
fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
protected void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
}
| ComplexTableSplittingMiscellaneousRelationalTestBase |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Serialization/Attribute_Specs.cs | {
"start": 941,
"end": 1387
} | public class ____
{
[Test]
public void Should_copy_the_property_to_the_interface()
{
var messageSerializer = new SystemTextJsonMessageSerializer();
var value = messageSerializer.DeserializeObject<SillyMessage>("{\"Value\": 10}");
Assert.That(value?.Value, Is.EqualTo(-1));
}
}
| Serializing_an_interface_with_a_property_attribute |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.Excluding.cs | {
"start": 22525,
"end": 37719
} | private interface ____
{
string NormalProperty { get; set; }
int DefaultProperty => NormalProperty.Length;
}
#endif
[Fact]
public void An_anonymous_object_with_multiple_fields_excludes_correctly()
{
// Arrange
var subject = new
{
FirstName = "John",
MiddleName = "X",
LastName = "Doe",
Age = 34
};
var expectation = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
Age = 29
};
// Act / Assert
subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.MiddleName, p.LastName, p.Age }));
}
[Fact]
public void An_empty_anonymous_object_excludes_nothing()
{
// Arrange
var subject = new
{
FirstName = "John",
MiddleName = "X",
LastName = "Doe",
Age = 34
};
var expectation = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
Age = 29
};
// Act
Action act = () => subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { }));
// Assert
act.Should().Throw<XunitException>();
}
[Fact]
public void An_anonymous_object_can_exclude_collections()
{
// Arrange
var subject = new
{
Names = new[]
{
"John",
"X.",
"Doe"
},
Age = 34
};
var expectation = new
{
Names = new[]
{
"John",
"W.",
"Smith"
},
Age = 34
};
// Act / Assert
subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.Names }));
}
[Fact]
public void An_anonymous_object_can_exclude_nested_objects()
{
// Arrange
var subject = new
{
Names = new
{
FirstName = "John",
MiddleName = "X",
LastName = "Doe",
},
Age = 34
};
var expectation = new
{
Names = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
},
Age = 34
};
// Act / Assert
subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.Names.MiddleName, p.Names.LastName }));
}
[Fact]
public void An_anonymous_object_can_exclude_nested_objects_inside_collections()
{
// Arrange
var subject = new
{
Names = new
{
FirstName = "John",
MiddleName = "X",
LastName = "Doe",
},
Pets = new[]
{
new
{
Name = "Dog",
Age = 1,
Color = "Black"
},
new
{
Name = "Cat",
Age = 1,
Color = "Black"
},
new
{
Name = "Bird",
Age = 1,
Color = "Black"
},
}
};
var expectation = new
{
Names = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
},
Pets = new[]
{
new
{
Name = "Dog",
Age = 1,
Color = "Black"
},
new
{
Name = "Dog",
Age = 2,
Color = "Gray"
},
new
{
Name = "Bird",
Age = 3,
Color = "Black"
},
}
};
// Act
Action act = () => subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.Names.MiddleName, p.Names.LastName })
.For(p => p.Pets)
.Exclude(p => new { p.Age, p.Name }));
// Assert
act.Should().Throw<XunitException>().Which.Message.Should()
.NotMatch("*Pets[1].Age*").And
.NotMatch("*Pets[1].Name*").And
.Match("*Pets[1].Color*");
}
[Fact]
public void An_anonymous_object_can_exclude_nested_objects_inside_nested_collections()
{
// Arrange
var subject = new
{
Names = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
},
Pets = new[]
{
new
{
Name = "Dog",
Fleas = new[]
{
new
{
Name = "Flea 1",
Age = 1,
},
new
{
Name = "Flea 2",
Age = 2,
},
},
},
new
{
Name = "Dog",
Fleas = new[]
{
new
{
Name = "Flea 10",
Age = 1,
},
new
{
Name = "Flea 21",
Age = 3,
},
},
},
new
{
Name = "Dog",
Fleas = new[]
{
new
{
Name = "Flea 1",
Age = 1,
},
new
{
Name = "Flea 2",
Age = 2,
},
},
},
},
};
var expectation = new
{
Names = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
},
Pets = new[]
{
new
{
Name = "Dog",
Fleas = new[]
{
new
{
Name = "Flea 1",
Age = 1,
},
new
{
Name = "Flea 2",
Age = 2,
},
},
},
new
{
Name = "Dog",
Fleas = new[]
{
new
{
Name = "Flea 1",
Age = 1,
},
new
{
Name = "Flea 2",
Age = 1,
},
},
},
new
{
Name = "Bird",
Fleas = new[]
{
new
{
Name = "Flea 1",
Age = 1,
},
new
{
Name = "Flea 2",
Age = 2,
},
},
},
},
};
// Act
Action act = () => subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.Names.MiddleName, p.Names.LastName })
.For(person => person.Pets)
.For(pet => pet.Fleas)
.Exclude(flea => new { flea.Name, flea.Age }));
// Assert
act.Should().Throw<XunitException>().Which.Message.Should()
.NotMatch("*Pets[*].Fleas[*].Age*").And
.NotMatch("*Pets[*].Fleas[*].Name*").And
.Match("*- Exclude*Pets[]Fleas[]Age*").And
.Match("*- Exclude*Pets[]Fleas[]Name*");
}
[Fact]
public void An_empty_anonymous_object_excludes_nothing_inside_collections()
{
// Arrange
var subject = new
{
Names = new
{
FirstName = "John",
MiddleName = "X",
LastName = "Doe",
},
Pets = new[]
{
new
{
Name = "Dog",
Age = 1
},
new
{
Name = "Cat",
Age = 1
},
new
{
Name = "Bird",
Age = 1
},
}
};
var expectation = new
{
Names = new
{
FirstName = "John",
MiddleName = "W.",
LastName = "Smith",
},
Pets = new[]
{
new
{
Name = "Dog",
Age = 1
},
new
{
Name = "Dog",
Age = 2
},
new
{
Name = "Bird",
Age = 1
},
}
};
// Act
Action act = () => subject.Should().BeEquivalentTo(expectation, opts => opts
.Excluding(p => new { p.Names.MiddleName, p.Names.LastName })
.For(p => p.Pets)
.Exclude(p => new { }));
// Assert
act.Should().Throw<XunitException>().WithMessage("*Pets[1].Name*Pets[1].Age*");
}
[Fact]
public void Can_exclude_root_properties_by_name()
{
// Arrange
var subject = new
{
FirstName = "John",
LastName = "Doe",
Age = 30
};
var expectation = new
{
FirstName = "John",
LastName = "Smith",
Age = 35
};
// Act / Assert
subject.Should().BeEquivalentTo(expectation, options => options
.ExcludingMembersNamed("LastName", "Age"));
}
[Fact]
public void Can_exclude_properties_deeper_in_the_graph_by_name()
{
// Arrange
var subject = new
{
Person = new
{
FirstName = "John",
LastName = "Doe",
Age = 30
},
Address = new
{
Street = "123 Main St",
City = "Anytown",
ZipCode = "12345"
}
};
var expectation = new
{
Person = new
{
FirstName = "John",
LastName = "Smith",
Age = 35
},
Address = new
{
Street = "123 Main St",
City = "Othertown",
ZipCode = "54321"
}
};
// Act / Assert
subject.Should().BeEquivalentTo(expectation, options => options
.ExcludingMembersNamed("LastName", "Age", "City", "ZipCode"));
}
[Fact]
public void Must_provide_property_names_when_excluding_by_name()
{
// Arrange
var subject = new
{
FirstName = "John",
LastName = "Doe"
};
// Act
Action act = () => subject.Should().BeEquivalentTo(subject, options => options
.ExcludingMembersNamed());
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("*least one*name*");
}
[Fact]
public void Cannot_provide_null_as_a_property_name()
{
// Arrange
var subject = new
{
FirstName = "John",
LastName = "Doe"
};
// Act
Action act = () => subject.Should().BeEquivalentTo(subject, options => options
.ExcludingMembersNamed(null));
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Member names cannot be null*");
}
}
}
| IHaveDefaultProperty |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/src/Data/Projections/Extensions/SingleOrDefaultObjectFieldDescriptorExtensions.cs | {
"start": 152,
"end": 3486
} | public static class ____
{
private static readonly Type s_firstMiddleware = typeof(FirstOrDefaultMiddleware<>);
private static readonly Type s_singleMiddleware = typeof(SingleOrDefaultMiddleware<>);
public static IObjectFieldDescriptor UseFirstOrDefault(
this IObjectFieldDescriptor descriptor) =>
ApplyMiddleware(descriptor, SelectionFlags.FirstOrDefault, s_firstMiddleware);
public static IObjectFieldDescriptor UseSingleOrDefault(
this IObjectFieldDescriptor descriptor) =>
ApplyMiddleware(descriptor, SelectionFlags.SingleOrDefault, s_singleMiddleware);
private static IObjectFieldDescriptor ApplyMiddleware(
this IObjectFieldDescriptor descriptor,
SelectionFlags selectionFlags,
Type middlewareDefinition)
{
ArgumentNullException.ThrowIfNull(descriptor);
FieldMiddlewareConfiguration placeholder =
new(_ => _ => default, key: WellKnownMiddleware.SingleOrDefault);
descriptor.Extend().Configuration.MiddlewareConfigurations.Add(placeholder);
descriptor
.Extend()
.OnBeforeCreate(
(context, definition) =>
{
definition.AddSelectionFlags(selectionFlags | SelectionFlags.MemberIsList);
if (definition.ResultType is null
|| !context.TypeInspector.TryCreateTypeInfo(
definition.ResultType,
out var typeInfo))
{
var resultType = definition.ResolverType ?? typeof(object);
throw new ArgumentException(
$"Cannot handle the specified type `{resultType.FullName}`.",
nameof(descriptor));
}
var selectionType = typeInfo.NamedType;
definition.ResultType = selectionType;
definition.Type =
context.TypeInspector.GetTypeRef(selectionType, TypeContext.Output);
definition.Tasks.Add(
new OnCompleteTypeSystemConfigurationTask<ObjectFieldConfiguration>(
(_, d) =>
{
CompileMiddleware(
selectionType,
d,
placeholder,
middlewareDefinition);
},
definition,
ApplyConfigurationOn.BeforeCompletion));
});
return descriptor;
}
private static void CompileMiddleware(
Type type,
ObjectFieldConfiguration definition,
FieldMiddlewareConfiguration placeholder,
Type middlewareDefinition)
{
var middlewareType = middlewareDefinition.MakeGenericType(type);
var middleware = FieldClassMiddlewareFactory.Create(middlewareType);
var index = definition.MiddlewareConfigurations.IndexOf(placeholder);
definition.MiddlewareConfigurations[index] =
new(middleware, key: WellKnownMiddleware.SingleOrDefault);
}
}
| SingleOrDefaultObjectFieldDescriptorExtensions |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json/Bson/BsonToken.cs | {
"start": 3042,
"end": 3395
} | internal class ____ : BsonToken
{
private readonly object _value;
private readonly BsonType _type;
public BsonValue(object value, BsonType type)
{
_value = value;
_type = type;
}
public object Value => _value;
public override BsonType Type => _type;
}
| BsonValue |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs | {
"start": 6470,
"end": 6745
} | private class ____ : Base3595
{
public int Id { get; set; }
public int QuestionId { get; set; }
public Question3595 Question { get; set; }
public int ExamId { get; set; }
public Exam3595 Exam { get; set; }
}
| ExamQuestion3595 |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/CommandsFeature.cs | {
"start": 23389,
"end": 23680
} | public class ____
{
public List<CommandSummary> CommandTotals { get; set; }
public List<CommandResult> LatestCommands { get; set; }
public List<CommandResult> LatestFailed { get; set; }
public ResponseStatus? ResponseStatus { get; set; }
}
[ExcludeMetadata]
| ViewCommandsResponse |
csharp | npgsql__efcore.pg | test/EFCore.PG.FunctionalTests/NpgsqlDatabaseCreatorTest.cs | {
"start": 20190,
"end": 21085
} | public class ____
{
protected static IDisposable CreateTransactionScope(bool useTransaction)
=> TestStore.CreateTransactionScope(useTransaction);
protected static TestDatabaseCreator GetDatabaseCreator(NpgsqlTestStore testStore)
=> GetDatabaseCreator(testStore.ConnectionString);
protected static TestDatabaseCreator GetDatabaseCreator(string connectionString)
=> GetDatabaseCreator(new BloggingContext(connectionString));
protected static TestDatabaseCreator GetDatabaseCreator(BloggingContext context)
=> (TestDatabaseCreator)context.GetService<IRelationalDatabaseCreator>();
protected static IExecutionStrategy GetExecutionStrategy(NpgsqlTestStore testStore)
=> new BloggingContext(testStore).GetService<IExecutionStrategyFactory>().Create();
// ReSharper disable once ClassNeverInstantiated.Local
| NpgsqlDatabaseCreatorTest |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/Mappings/Attribute/HeaderPrefixTests.cs | {
"start": 616,
"end": 4340
} | public class ____
{
[Fact]
public void WriteHeader_PrefixCustom_WritesCustomPrefixesOwnLevelOnly()
{
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<ACustom>();
csv.Flush();
Assert.Equal("AId,b_BId,c_CId", writer.ToString());
}
}
[Fact]
public void WriteHeader_PrefixInherit_WritesPrefixesForEachLevel()
{
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<AInherit>();
csv.Flush();
Assert.Equal("AId,B.BId,B.C.CId", writer.ToString());
}
}
[Fact]
public void WriteHeader_PrefixNoInherit_WritesPrefixesOwnLevelOnly()
{
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<ANoInherit>();
csv.Flush();
Assert.Equal("AId,B.BId,C.CId", writer.ToString());
}
}
[Fact]
public void WriteHeader_PrefixDefaultInherit_WritesPrefixesOwnLevelOnly()
{
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<ADefaultInherit>();
csv.Flush();
Assert.Equal("AId,B.BId,C.CId", writer.ToString());
}
}
[Fact]
public void GetRecords_PrefixCustom_ReadsCustomHeader()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
var s = new TestStringBuilder(config.NewLine);
s.AppendLine("AId,b_BId,c_CId");
s.AppendLine("aid,bid,cid");
using (var reader = new StringReader(s))
using (var csv = new CsvReader(reader, config))
{
var records = csv.GetRecords<ACustom>().ToList();
Assert.Single(records);
Assert.Equal("aid", records?[0]?.AId);
Assert.Equal("bid", records?[0]?.B?.BId);
Assert.Equal("cid", records?[0]?.B?.C?.CId);
}
}
[Fact]
public void GetRecords_PrefixInherit_ReadsInheritedHeader()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
var s = new TestStringBuilder(config.NewLine);
s.AppendLine("AId,B.BId,B.C.CId");
s.AppendLine("aid,bid,cid");
using (var reader = new StringReader(s))
using (var csv = new CsvReader(reader, config))
{
var records = csv.GetRecords<AInherit>().ToList();
Assert.Single(records);
Assert.Equal("aid", records?[0].AId);
Assert.Equal("bid", records?[0].B?.BId);
Assert.Equal("cid", records?[0].B?.C?.CId);
}
}
[Fact]
public void GetRecords_PrefixNoInherit_ReadsNonInheritedHeader()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
var s = new TestStringBuilder(config.NewLine);
s.AppendLine("AId,B.BId,C.CId");
s.AppendLine("aid,bid,cid");
using (var reader = new StringReader(s))
using (var csv = new CsvReader(reader, config))
{
var records = csv.GetRecords<ANoInherit>().ToList();
Assert.Single(records);
Assert.Equal("bid", records?[0].B?.BId);
Assert.Equal("aid", records?[0].AId);
Assert.Equal("cid", records?[0].B?.C?.CId);
}
}
[Fact]
public void GetRecords_PrefixDefaultInherit_ReadsNonInheritedHeader()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
var s = new TestStringBuilder(config.NewLine);
s.AppendLine("AId,B.BId,C.CId");
s.AppendLine("aid,bid,cid");
using (var reader = new StringReader(s))
using (var csv = new CsvReader(reader, config))
{
var records = csv.GetRecords<ADefaultInherit>().ToList();
Assert.Single(records);
Assert.Equal("aid", records?[0].AId);
Assert.Equal("bid", records?[0].B?.BId);
Assert.Equal("cid", records?[0].B?.C?.CId);
}
}
| HeaderPrefixTests |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Types/MethodInfoSelectorAssertionSpecs.cs | {
"start": 13827,
"end": 15294
} | public class ____
{
[Fact]
public void When_asserting_methods_are_async_and_they_are_then_it_succeeds()
{
// Arrange
var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsAsync));
// Act
Action act = () => methodSelector.Should().BeAsync();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_asserting_methods_are_async_but_non_async_methods_are_found_it_should_throw_with_descriptive_message()
{
// Arrange
var methodSelector = new MethodInfoSelector(typeof(ClassWithNonAsyncMethods));
// Act
Action act = () => methodSelector.Should().BeAsync("we want to test the error {0}", "message");
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected all selected methods" +
" to be async because we want to test the error message," +
" but the following methods are not:" + Environment.NewLine +
"Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.PublicDoNothing" + Environment.NewLine +
"Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.InternalDoNothing" + Environment.NewLine +
"Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.ProtectedDoNothing");
}
}
| BeAsync |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs | {
"start": 31610,
"end": 32329
} | public partial class ____ : INotifyPropertyChanged
{
[ObservableProperty]
public int {|MVVMTK0019:number|};
public event PropertyChangedEventHandler PropertyChanged;
}
}
""";
await VerifyAnalyzerDiagnosticsAndSuccessfulGeneration<InvalidTargetObservablePropertyAttributeAnalyzer>(source, LanguageVersion.CSharp8);
}
[TestMethod]
public async Task InvalidContainingTypeForObservableProperty_OnField_InValidType_DoesNotWarn()
{
string source = """
using CommunityToolkit.Mvvm.ComponentModel;
namespace MyApp
{
| MyViewModel |
csharp | dotnetcore__Util | src/Util.Microservices/IStateManager.cs | {
"start": 1224,
"end": 2347
} | public interface ____<T> : IStateManagerBase<IStateManager<T>> {
/// <summary>
/// 设置升序排序属性
/// </summary>
/// <param name="expression">属性表达式</param>
IStateManager<T> OrderBy( Expression<Func<T, object>> expression );
/// <summary>
/// 设置降序排序属性
/// </summary>
/// <param name="expression">属性表达式</param>
IStateManager<T> OrderByDescending( Expression<Func<T, object>> expression );
/// <summary>
/// 设置相等条件
/// </summary>
/// <param name="expression">属性名表达式</param>
/// <param name="value">属性值</param>
IStateManager<T> Equal( Expression<Func<T, object>> expression, object value );
/// <summary>
/// 设置In条件
/// </summary>
/// <param name="expression">属性名表达式</param>
/// <param name="values">属性值</param>
IStateManager<T> In( Expression<Func<T, object>> expression, IEnumerable<object> values );
/// <summary>
/// 设置In条件
/// </summary>
/// <param name="expression">属性名表达式</param>
/// <param name="values">属性值</param>
IStateManager<T> In( Expression<Func<T, object>> expression, params object[] values );
} | IStateManager |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/RenderingPerformance.xaml.cs | {
"start": 5748,
"end": 5902
} | public class ____
{
public string Header { get; set; }
public string Content { get; set; }
public bool IsMeasured { get; set; }
}
} | NestedViewModelStub |
csharp | bitwarden__server | test/Core.Test/OrganizationFeatures/OrganizationCollections/BulkAddCollectionAccessCommandTests.cs | {
"start": 545,
"end": 14414
} | public class ____
{
[Theory, BitAutoData, CollectionCustomization]
public async Task AddAccessAsync_Success(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
Organization org,
ICollection<Collection> collections,
ICollection<OrganizationUser> organizationUsers,
ICollection<Group> groups,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
)
.Returns(organizationUsers);
sutProvider.GetDependency<IGroupRepository>()
.GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionGroups.Select(u => u.GroupId)))
)
.Returns(groups);
var userAccessSelections = ToAccessSelection(collectionUsers);
var groupAccessSelections = ToAccessSelection(collectionGroups);
await sutProvider.Sut.AddAccessAsync(collections,
userAccessSelections,
groupAccessSelections
);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received().GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(userAccessSelections.Select(u => u.Id)))
);
await sutProvider.GetDependency<IGroupRepository>().Received().GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(groupAccessSelections.Select(g => g.Id)))
);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateOrUpdateAccessForManyAsync(
org.Id,
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collections.Select(c => c.Id))),
userAccessSelections,
groupAccessSelections);
await sutProvider.GetDependency<IEventService>().Received().LogCollectionEventsAsync(
Arg.Is<IEnumerable<(Collection, EventType, DateTime?)>>(
events => events.All(e =>
collections.Contains(e.Item1) &&
e.Item2 == EventType.Collection_Updated &&
e.Item3.HasValue
)
)
);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_NoCollectionsProvided_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider)
{
var exception =
await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.AddAccessAsync(null, null, null));
Assert.Contains("No collections were provided.", exception.Message);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIdsAsync(default);
await sutProvider.GetDependency<IOrganizationUserRepository>().DidNotReceiveWithAnyArgs().GetManyAsync(default);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_NoCollection_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(Enumerable.Empty<Collection>().ToList(),
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("No collections were provided.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().DidNotReceiveWithAnyArgs().GetManyAsync(default);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_DifferentOrgs_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
ICollection<Collection> collections,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
collections.First().OrganizationId = Guid.NewGuid();
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("All collections must belong to the same organization.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().DidNotReceiveWithAnyArgs().GetManyAsync(default);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_MissingUser_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IList<Collection> collections,
IList<OrganizationUser> organizationUsers,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
organizationUsers.RemoveAt(0);
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
)
.Returns(organizationUsers);
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("One or more users do not exist.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received().GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_UserWrongOrg_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IList<Collection> collections,
IList<OrganizationUser> organizationUsers,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
organizationUsers.First().OrganizationId = Guid.NewGuid();
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
)
.Returns(organizationUsers);
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("One or more users do not belong to the same organization as the collection being assigned.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received().GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_MissingGroup_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IList<Collection> collections,
IList<OrganizationUser> organizationUsers,
IList<Group> groups,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
groups.RemoveAt(0);
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
)
.Returns(organizationUsers);
sutProvider.GetDependency<IGroupRepository>()
.GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionGroups.Select(u => u.GroupId)))
)
.Returns(groups);
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("One or more groups do not exist.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received().GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
);
await sutProvider.GetDependency<IGroupRepository>().Received().GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionGroups.Select(u => u.GroupId)))
);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task ValidateRequestAsync_GroupWrongOrg_Failure(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IList<Collection> collections,
IList<OrganizationUser> organizationUsers,
IList<Group> groups,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
SetCollectionsToSharedType(collections);
groups.First().OrganizationId = Guid.NewGuid();
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
)
.Returns(organizationUsers);
sutProvider.GetDependency<IGroupRepository>()
.GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionGroups.Select(u => u.GroupId)))
)
.Returns(groups);
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("One or more groups do not belong to the same organization as the collection being assigned.", exception.Message);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received().GetManyAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionUsers.Select(u => u.OrganizationUserId)))
);
await sutProvider.GetDependency<IGroupRepository>().Received().GetManyByManyIds(
Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionGroups.Select(u => u.GroupId)))
);
}
[Theory, BitAutoData, CollectionCustomization]
public async Task AddAccessAsync_WithDefaultUserCollectionType_ThrowsBadRequest(SutProvider<BulkAddCollectionAccessCommand> sutProvider,
IList<Collection> collections,
IEnumerable<CollectionUser> collectionUsers,
IEnumerable<CollectionGroup> collectionGroups)
{
// Arrange
collections.First().Type = CollectionType.DefaultUserCollection;
// Act & Assert
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.AddAccessAsync(collections,
ToAccessSelection(collectionUsers),
ToAccessSelection(collectionGroups)
));
Assert.Contains("You cannot add access to collections with the type as DefaultUserCollection.", exception.Message);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateOrUpdateAccessForManyAsync(default, default, default, default);
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs().LogCollectionEventsAsync(default);
await sutProvider.GetDependency<IOrganizationUserRepository>().DidNotReceiveWithAnyArgs().GetManyAsync(default);
await sutProvider.GetDependency<IGroupRepository>().DidNotReceiveWithAnyArgs().GetManyByManyIds(default);
}
private static void SetCollectionsToSharedType(IEnumerable<Collection> collections)
{
foreach (var collection in collections)
{
collection.Type = CollectionType.SharedCollection;
}
}
private static ICollection<CollectionAccessSelection> ToAccessSelection(IEnumerable<CollectionUser> collectionUsers)
{
return collectionUsers.Select(cu => new CollectionAccessSelection
{
Id = cu.OrganizationUserId,
Manage = cu.Manage,
HidePasswords = cu.HidePasswords,
ReadOnly = cu.ReadOnly
}).ToList();
}
private static ICollection<CollectionAccessSelection> ToAccessSelection(IEnumerable<CollectionGroup> collectionGroups)
{
return collectionGroups.Select(cg => new CollectionAccessSelection
{
Id = cg.GroupId,
Manage = cg.Manage,
HidePasswords = cg.HidePasswords,
ReadOnly = cg.ReadOnly
}).ToList();
}
}
| BulkAddCollectionAccessCommandTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.