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
src/MongoDB.Driver/DeleteResult.cs
{ "start": 1832, "end": 2686 }
public class ____ : DeleteResult { private readonly long _deletedCount; /// <summary> /// Initializes a new instance of the <see cref="Acknowledged"/> class. /// </summary> /// <param name="deletedCount">The deleted count.</param> public Acknowledged(long deletedCount) { _deletedCount = deletedCount; } /// <inheritdoc/> public override long DeletedCount { get { return _deletedCount; } } /// <inheritdoc/> public override bool IsAcknowledged { get { return true; } } } /// <summary> /// The result of an unacknowledged delete operation. /// </summary>
Acknowledged
csharp
abpframework__abp
framework/src/Volo.Abp.Authorization/Microsoft/AspNetCore/Authorization/AuthorizationOptionsExtensions.cs
{ "start": 157, "end": 1007 }
public static class ____ { private static readonly PropertyInfo PolicyMapProperty = typeof(AuthorizationOptions) .GetProperty("PolicyMap", BindingFlags.Instance | BindingFlags.NonPublic)!; /// <summary> /// Gets all policies. /// /// IMPORTANT NOTE: Use this method carefully. /// It relies on reflection to get all policies from a private field of the <paramref name="options"/>. /// This method may be removed in the future if internals of <see cref="AuthorizationOptions"/> changes. /// </summary> /// <param name="options"></param> /// <returns></returns> public static List<string> GetPoliciesNames(this AuthorizationOptions options) { return ((IDictionary<string, Task<AuthorizationPolicy>>)PolicyMapProperty.GetValue(options)!).Keys.ToList(); } }
AuthorizationOptionsExtensions
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Prediction/Calibrator.cs
{ "start": 21029, "end": 21284 }
internal sealed class ____<TSubModel, TCalibrator> : ValueMapperCalibratedModelParametersBase<TSubModel, TCalibrator>, IPredictorWithFeatureWeights<float>, ICanSaveModel where TSubModel :
FeatureWeightsCalibratedModelParameters
csharp
dotnet__maui
src/Controls/src/Core/Shell/ShellSection.cs
{ "start": 37189, "end": 38204 }
private sealed class ____ : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => false; public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cultureInfo, object value, Type destinationType) => throw new NotSupportedException(); public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(ShellContent) || sourceType == typeof(TemplatedPage); public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) => value switch { ShellContent shellContent => (ShellSection)shellContent, TemplatedPage page => (ShellSection)page, _ => throw new NotSupportedException(), }; } /// <summary> /// Provides a debug view for the <see cref="ShellSection"/> class. /// </summary> /// <param name="section">The <see cref="ShellSection"/> instance to debug.</param>
ShellSectionTypeConverter
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp4763Tests.cs
{ "start": 851, "end": 21602 }
public class ____ : LinqIntegrationTest<CSharp4763Tests.ClassFixture> { public CSharp4763Tests(ClassFixture fixture) : base(fixture) { } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Find_with_client_side_projection_ToList_should_work( bool useFindOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var findOptions = GetFindOptions(useFindOptions, useTranslationOptions, enableClientSideProjections); var find = collection .Find("{}", findOptions) .Project(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var projection = TranslateFindProjection(collection, find, out var projectionSerializer); if (findOptions.TranslationOptions.CompatibilityLevel == ServerVersion.Server42) { projection.Should().BeNull(); } else { projection.Should().Be("{ _snippets : ['$X'], _id : 0 }"); } projectionSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var results = find.ToList(); results.Should().Equal(2); } else { var exception = Record.Exception(() => TranslateFindProjection(collection, find)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Find_with_client_side_projection_First_should_work( bool useFindOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var findOptions = GetFindOptions(useFindOptions, useFindOptions, enableClientSideProjections); var find = collection .Find("{}", findOptions) .Project(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var projection = TranslateFindProjection(collection, find, out var projectionSerializer); if (findOptions.TranslationOptions.CompatibilityLevel == ServerVersion.Server42) { projection.Should().BeNull(); } else { projection.Should().Be("{ _snippets : ['$X'], _id : 0 }"); } projectionSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var result = find.First(); result.Should().Be(2); } else { var exception = Record.Exception(() => TranslateFindProjection(collection, find)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Find_with_client_side_projection_Single_should_work( bool useFindOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var findOptions = GetFindOptions(useFindOptions, useFindOptions, enableClientSideProjections); var find = collection .Find("{}", findOptions) .Project(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var projection = TranslateFindProjection(collection, find, out var projectionSerializer); if (findOptions.TranslationOptions.CompatibilityLevel == ServerVersion.Server42) { projection.Should().BeNull(); } else { projection.Should().Be("{ _snippets : ['$X'], _id : 0 }"); } projectionSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var result = find.Single(); result.Should().Be(2); } else { var exception = Record.Exception(() => TranslateFindProjection(collection, find)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Aggregate_Project_with_client_side_projection_ToList_should_work( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var aggregate = collection.Aggregate(aggregateOptions) .Project(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var stages = Translate(collection, aggregate, out var outputSerializer); AssertStages(stages, "{ $project : { _snippets : ['$X'], _id : 0 } }"); outputSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var results = aggregate.ToList(); results.Should().Equal(2); } else { var exception = Record.Exception(() => Translate(collection, aggregate)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Aggregate_Project_with_client_side_projection_First_should_work( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var aggregate = collection.Aggregate(aggregateOptions) .Project(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var stages = Translate(collection, aggregate, out var serializer); AssertStages(stages, "{ $project : { _snippets : ['$X'], _id : 0 } }"); serializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var result = aggregate.First(); result.Should().Be(2); } else { var exception = Record.Exception(() => Translate(collection, aggregate)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Aggregate_Project_with_client_side_projection_Match_should_throw( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var aggregate = collection.Aggregate(aggregateOptions) .Project(x => MyFunction(x.X)) .Match(x => x == 2); var exception = Record.Exception(() => Translate(collection, aggregate)); if (enableClientSideProjections ?? false) { exception.Should().BeOfType<NotSupportedException>(); exception.Message.Should().Contain("A $match stage cannot follow a client side projection"); } else { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_ToList_should_work( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var stages = Translate(collection, queryable, out var outputSerializer); AssertStages(stages, "{ $project : { _snippets : ['$X'], _id : 0 } }"); outputSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var results = queryable.ToList(); results.Should().Equal(2); } else { var exception = Record.Exception(() => Translate(collection, queryable)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_First_should_work( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var stages = Translate(collection, queryable, out var outputSerializer); AssertStages(stages, "{ $project : { _snippets : ['$X'], _id : 0 } }"); outputSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var result = queryable.First(); result.Should().Be(2); } else { var exception = Record.Exception(() => Translate(collection, queryable)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_First_with_predicate_should_throw( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)); var exception = Record.Exception(() => queryable.First(x => x == 2)); if (enableClientSideProjections ?? false) { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("because First with a predicate cannot follow a client side projection"); } else { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_Single_should_work( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)); if (enableClientSideProjections ?? false) { var stages = Translate(collection, queryable, out var outputSerializer); AssertStages(stages, "{ $project : { _snippets : ['$X'], _id : 0 } }"); outputSerializer.Should().BeAssignableTo<IClientSideProjectionDeserializer>(); var result = queryable.Single(); result.Should().Be(2); } else { var exception = Record.Exception(() => Translate(collection, queryable)); exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_Single_with_predicate_should_throw( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)); var exception = Record.Exception(() => queryable.Single(x => x == 2)); if (enableClientSideProjections ?? false) { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("because Single with a predicate cannot follow a client side projection"); } else { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_Where_should_throw( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)) .Where(x => x == 2); var exception = Record.Exception(() => queryable.ToList()); if (enableClientSideProjections ?? false) { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("because Where cannot follow a client side projection"); } else { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } [Theory] [InlineData(false, false, null)] [InlineData(true, false, null)] [InlineData(true, true, null)] [InlineData(true, true, false)] [InlineData(true, true, true)] public void Queryable_Select_with_client_side_projection_Select_should_throw( bool useAggregateOptions, bool useTranslationOptions, bool? enableClientSideProjections) { var collection = Fixture.Collection; var aggregateOptions = GetAggregateOptions(useAggregateOptions, useTranslationOptions, enableClientSideProjections); var queryable = collection.AsQueryable(aggregateOptions) .Select(x => MyFunction(x.X)) .Select(x => x + 1); var exception = Record.Exception(() => queryable.ToList()); if (enableClientSideProjections ?? false) { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("because Select cannot follow a client side projection"); } else { exception.Should().BeOfType<ExpressionNotSupportedException>(); exception.Message.Should().Contain("MyFunction"); } } private AggregateOptions GetAggregateOptions(bool useFindOptions, bool useTranslationOptions, bool? enableClientSideProjections) => (useFindOptions, useTranslationOptions) switch { (false, _) => null, (true, false) => new AggregateOptions { TranslationOptions = null }, (true, true) => new AggregateOptions { TranslationOptions = GetTranslationOptions(enableClientSideProjections) }, }; private FindOptions GetFindOptions(bool useFindOptions, bool useTranslationOptions, bool? enableClientSideProjections) { return (useFindOptions, useTranslationOptions) switch { (false, _) => null, (true, false) => new FindOptions { TranslationOptions = null }, (true, true) => new FindOptions { TranslationOptions = GetTranslationOptions(enableClientSideProjections) } }; } private ExpressionTranslationOptions GetTranslationOptions(bool? enableClientSideProjections) { var wireVersion = CoreTestConfiguration.MaxWireVersion; var compatibilityLevel = Feature.FindProjectionExpressions.IsSupported(wireVersion) ? (ServerVersion?)null : ServerVersion.Server42; return new ExpressionTranslationOptions { EnableClientSideProjections = enableClientSideProjections, CompatibilityLevel = compatibilityLevel }; } private int MyFunction(int x) => 2 * x;
CSharp4763Tests
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Input/IAccessKeyHandler.cs
{ "start": 174, "end": 1225 }
internal interface ____ { /// <summary> /// Gets or sets the window's main menu. /// </summary> IMainMenu? MainMenu { get; set; } /// <summary> /// Sets the owner of the access key handler. /// </summary> /// <param name="owner">The owner.</param> /// <remarks> /// This method can only be called once, typically by the owner itself on creation. /// </remarks> void SetOwner(IInputRoot owner); /// <summary> /// Registers an input element to be associated with an access key. /// </summary> /// <param name="accessKey">The access key.</param> /// <param name="element">The input element.</param> void Register(char accessKey, IInputElement element); /// <summary> /// Unregisters the access keys associated with the input element. /// </summary> /// <param name="element">The input element.</param> void Unregister(IInputElement element); } }
IAccessKeyHandler
csharp
abpframework__abp
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateRazorPage.cs
{ "start": 4758, "end": 5121 }
private class ____ : RazorEngineFeatureBase, IConfigureRazorCodeGenerationOptionsFeature { public int Order { get; set; } public void Configure(RazorCodeGenerationOptionsBuilder options) { Check.NotNull(options, nameof(options)); options.SuppressChecksum = true; } }
SuppressChecksumOptionsFeature
csharp
grandnode__grandnode2
src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs
{ "start": 217, "end": 1722 }
public class ____ : ITypeConverter { public void Register() { TypeDescriptor.AddAttributes(typeof(bool), new TypeConverterAttribute(typeof(BoolTypeConverter))); //dictionaries TypeDescriptor.AddAttributes(typeof(Dictionary<int, int>), new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<int, int>))); TypeDescriptor.AddAttributes(typeof(Dictionary<string, bool>), new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<string, bool>))); //shipping option TypeDescriptor.AddAttributes(typeof(ShippingOption), new TypeConverterAttribute(typeof(ShippingOptionTypeConverter))); TypeDescriptor.AddAttributes(typeof(List<ShippingOption>), new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter))); TypeDescriptor.AddAttributes(typeof(IList<ShippingOption>), new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter))); //custom attributes TypeDescriptor.AddAttributes(typeof(List<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter))); TypeDescriptor.AddAttributes(typeof(IList<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter))); TypeDescriptor.AddAttributes(typeof(RefreshToken), new TypeConverterAttribute(typeof(RefreshTokenTypeConverter))); } public int Order => 0; }
WebTypeConverter
csharp
dotnet__BenchmarkDotNet
samples/BenchmarkDotNet.Samples/IntroParamsSource.cs
{ "start": 848, "end": 971 }
public static class ____ { public static IEnumerable<int> ValuesForC() => new[] { 1000, 2000 }; } }
ParamsValues
csharp
getsentry__sentry-dotnet
src/Sentry/Platforms/Android/Callbacks/TracesSamplerCallback.cs
{ "start": 71, "end": 579 }
internal class ____ : JavaObject, JavaSdk.SentryOptions.ITracesSamplerCallback { private readonly Func<TransactionSamplingContext, double?> _tracesSampler; public TracesSamplerCallback(Func<TransactionSamplingContext, double?> tracesSampler) { _tracesSampler = tracesSampler; } public JavaDouble? Sample(JavaSdk.SamplingContext c) { var context = c.ToTransactionSamplingContext(); return (JavaDouble?)_tracesSampler.Invoke(context); } }
TracesSamplerCallback
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Email.Core/Services/EmailProviderOptions.cs
{ "start": 78, "end": 2147 }
public class ____ { private Dictionary<string, EmailProviderTypeOptions> _providers { get; } = []; private FrozenDictionary<string, EmailProviderTypeOptions> _readonlyProviders; /// <summary> /// This read-only collections contains all registered email providers. /// The 'Key' is the technical name of the provider. /// The 'Value' is the type of the email provider. The type will always be an implementation of <see cref="IEmailProvider"></see> interface. /// </summary> public IReadOnlyDictionary<string, EmailProviderTypeOptions> Providers => _readonlyProviders ??= _providers.ToFrozenDictionary(x => x.Key, x => x.Value); /// <summary> /// Adds a provider if one does not exist. /// </summary> /// <param name="name">The technical name of the provider.</param> /// <param name="options">The type options of the provider.</param> public EmailProviderOptions TryAddProvider(string name, EmailProviderTypeOptions options) { ArgumentException.ThrowIfNullOrEmpty(name); if (_providers.ContainsKey(name)) { return this; } _providers.Add(name, options); _readonlyProviders = null; return this; } /// <summary> /// Removes a provider if one exist. /// </summary> /// <param name="name">The technical name of the provider.</param> public EmailProviderOptions RemoveProvider(string name) { ArgumentException.ThrowIfNullOrEmpty(name); if (_providers.Remove(name)) { _readonlyProviders = null; } return this; } /// <summary> /// Replaces existing or adds a new provider. /// </summary> /// <param name="name">The technical name of the provider.</param> /// <param name="options">The type-options of the provider.</param> public EmailProviderOptions ReplaceProvider(string name, EmailProviderTypeOptions options) { _providers.Remove(name); return TryAddProvider(name, options); } }
EmailProviderOptions
csharp
ServiceStack__ServiceStack
ServiceStack.Text/tests/ServiceStack.Text.Tests/Utils/DateTimeSerializerTests.cs
{ "start": 14397, "end": 23769 }
public class ____ { public DateTime Date { get; set; } } [OneTimeSetUp] public void TestFixtureSetUp() { JsConfig.DateHandler = DateHandler.ISO8601; } [OneTimeTearDown] public void TestFixtureTearDown() { JsConfig.Reset(); } [Test] public void DateTime_Is_Serialized_As_Utc_and_Deserialized_as_local() { var testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc) }; Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); //Can change default behavior with config using (JsConfig.With(new Config { AlwaysUseUtc = true })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); //Can change default behavior with config using (JsConfig.With(new Config { AlwaysUseUtc = true })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } } [Test] public void SkipDateTimeConversion_IgnoresTimezoneOffsets() { JsConfig.DateHandler = DateHandler.ISO8601; JsConfig.SkipDateTimeConversion = true; string serilizedResult; DateTime deserilizedResult; var targetDateLocal = new DateTime(2016, 01, 10, 12, 12, 12, DateTimeKind.Local).AddMilliseconds(2); var targetDateUtc = new DateTime(2016, 01, 10, 12, 12, 12, DateTimeKind.Utc).AddMilliseconds(2); var targetDateUnspecificed = new DateTime(2016, 01, 10, 12, 12, 12, DateTimeKind.Unspecified).AddMilliseconds(2); serilizedResult = "2016-01-10T12:12:12.002-15:00"; deserilizedResult = TypeSerializer.DeserializeFromString<DateTime>(serilizedResult); Assert.AreEqual(deserilizedResult, targetDateLocal); serilizedResult = "2016-01-10T12:12:12.002+05:00"; deserilizedResult = TypeSerializer.DeserializeFromString<DateTime>(serilizedResult); Assert.AreEqual(deserilizedResult, targetDateLocal); serilizedResult = "2016-01-10T12:12:12.002Z"; deserilizedResult = TypeSerializer.DeserializeFromString<DateTime>(serilizedResult); Assert.AreEqual(deserilizedResult, targetDateUtc); serilizedResult = "2016-01-10T12:12:12.002"; deserilizedResult = TypeSerializer.DeserializeFromString<DateTime>(serilizedResult); Assert.AreEqual(deserilizedResult, targetDateUnspecificed); } [Test] public void DateTimeKind_Does_Not_Change_With_SkipDateTimeConversion_true() { JsConfig.DateHandler = DateHandler.ISO8601; JsConfig.SkipDateTimeConversion = true; string serilizedResult; TestObject deserilizedResult; var testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc) }; serilizedResult = TypeSerializer.SerializeToString<TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString<TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind); using (JsConfig.With(new Config { SkipDateTimeConversion = false })) { Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; serilizedResult = TypeSerializer.SerializeToString<TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString<TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind); using (JsConfig.With(new Config { SkipDateTimeConversion = false })) { Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } using (JsConfig.With(new Config { AlwaysUseUtc = true, SkipDateTimeConversion = false })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } //make sure it still keeps local local testObject = new TestObject { Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Local) }; serilizedResult = TypeSerializer.SerializeToString<TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString<TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind); using (JsConfig.With(new Config { AlwaysUseUtc = true })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } using (JsConfig.With(new Config { AlwaysUseUtc = true, SkipDateTimeConversion = false })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } testObject = new TestObject { Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Unspecified) }; serilizedResult = TypeSerializer.SerializeToString<TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString<TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Unspecified, deserilizedResult.Date.Kind); using (JsConfig.With(new Config { AlwaysUseUtc = true })) { Assert.AreEqual(DateTimeKind.Unspecified, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } using (JsConfig.With(new Config { AlwaysUseUtc = true, SkipDateTimeConversion = false })) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString<TestObject>(TypeSerializer.SerializeToString<TestObject>(testObject)).Date.Kind); } using (JsConfig.With(new Config { SkipDateTimeConversion = false })) { serilizedResult = TypeSerializer.SerializeToString<TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString<TestObject>(serilizedResult); Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind); } } [Test] public void Does_parse_as_UTC() { JsConfig.AssumeUtc = true; var dateStr = "2014-08-27 14:30:23"; var dateTime = dateStr.FromJson<DateTime>(); Assert.That(dateTime.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(dateTime.Hour, Is.EqualTo(14)); Assert.That(dateTime.Minute, Is.EqualTo(30)); Assert.That(dateTime.Second, Is.EqualTo(23)); JsConfig.Reset(); } [Test] public void Can_serialize_nullable_DateTime() { JsConfig.IncludeNullValues = true; JsConfig.AssumeUtc = true; var date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc); var dto = new DateModel { DateTime = date, NullableDateTime = date }; dto.ToJson().Print(); Assert.That(dto.ToJson(), Is.EqualTo("{\"DateTime\":\"2013-01-01T00:00:01.0000000Z\",\"NullableDateTime\":\"2013-01-01T00:00:01.0000000Z\"}")); JsConfig.Reset(); } [Test] public void Can_deserialize_LocalTime_using_ISO8601() { var date = DateTime.Now; var dateStr = date.ToJson(); var fromDate = dateStr.FromJson<DateTime>(); Assert.AreEqual(date.ToLocalTime().RoundToSecond(), fromDate.ToLocalTime().RoundToSecond()); } } [TestFixture]
TestObject
csharp
npgsql__efcore.pg
test/EFCore.PG.FunctionalTests/DataAnnotationNpgsqlTest.cs
{ "start": 43, "end": 985 }
public class ____(DataAnnotationNpgsqlTest.DataAnnotationNpgsqlFixture fixture) : DataAnnotationRelationalTestBase<DataAnnotationNpgsqlTest.DataAnnotationNpgsqlFixture>(fixture) { protected override void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction) => facade.UseTransaction(transaction.GetDbTransaction()); protected override TestHelpers TestHelpers => NpgsqlTestHelpers.Instance; public override Task StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() => Task.CompletedTask; // Npgsql does not support length public override Task TimestampAttribute_throws_if_value_in_database_changed() => Task.CompletedTask; // Npgsql does not support length public override Task MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() => Task.CompletedTask; // Npgsql does not support length
DataAnnotationNpgsqlTest
csharp
dotnet__efcore
test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs
{ "start": 16668, "end": 17155 }
private class ____ : DbContext { public TestContext() => throw new Exception("This isn't the constructor you're looking for."); public TestContext(DbContextOptions<TestContext> options) : base(options) { Assert.Equal("Development", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")); Assert.Equal("Development", Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")); } }
TestContext
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/ElectionsService/ElectionsServiceTests.cs
{ "start": 11119, "end": 13285 }
public class ____ : ElectionsFixture { public when_view_change_proof_is_triggered_and_the_first_election_has_completed() : base(NodeFactory(3), NodeFactory(2), NodeFactory(1)) { _sut.Handle(new GossipMessage.GossipUpdated(new ClusterInfo( MemberInfoFromVNode(_node, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0), MemberInfoFromVNode(_nodeTwo, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0), MemberInfoFromVNode(_nodeThree, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0)))); } [Test] public void should_send_view_change_proof_to_other_members() { _sut.Handle(new ElectionMessage.StartElections()); _sut.Handle(new ElectionMessage.ViewChange(_nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, 0)); _sut.Handle(new ElectionMessage.PrepareOk(0, _nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, 0, 0, _epochId, Guid.Empty, 0, 0, 0, 0, new ClusterInfo())); var proposalHttpMessage = _publisher.Messages.OfType<GrpcMessage.SendOverGrpc>() .FirstOrDefault(x => x.Message is ElectionMessage.Proposal); var proposalMessage = (ElectionMessage.Proposal)proposalHttpMessage.Message; _publisher.Messages.Clear(); _sut.Handle(new ElectionMessage.Accept(_nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, proposalMessage.LeaderId, proposalMessage.LeaderHttpEndPoint, 0)); _publisher.Messages.Clear(); _sut.Handle(new ElectionMessage.SendViewChangeProof()); var expected = new Message[] { new GrpcMessage.SendOverGrpc(_nodeTwo.HttpEndPoint, new ElectionMessage.ViewChangeProof(_node.InstanceId, _node.HttpEndPoint, 0), _timeProvider.LocalTime.Add(LeaderElectionProgressTimeout)), new GrpcMessage.SendOverGrpc(_nodeThree.HttpEndPoint, new ElectionMessage.ViewChangeProof(_node.InstanceId, _node.HttpEndPoint, 0), _timeProvider.LocalTime.Add(LeaderElectionProgressTimeout)), TimerMessage.Schedule.Create( KurrentDB.Core.Services.ElectionsService.SendViewChangeProofInterval, _publisher, new ElectionMessage.SendViewChangeProof()), }; _publisher.Messages.Should().BeEquivalentTo(expected); } }
when_view_change_proof_is_triggered_and_the_first_election_has_completed
csharp
smartstore__Smartstore
src/Smartstore.Core/Checkout/Cart/Domain/ShoppingCartLineItem.cs
{ "start": 219, "end": 998 }
public partial class ____ { public ShoppingCartLineItem(OrganizedShoppingCartItem item) { Item = Guard.NotNull(item); } /// <summary> /// The shopping cart item. /// </summary> public OrganizedShoppingCartItem Item { get; private set; } /// <summary> /// The calculated unit price in the primary currency. /// </summary> public CalculatedPrice UnitPrice { get; init; } /// <summary> /// The calculated subtotal of the line item in the primary currency. /// It is the <see cref="UnitPrice"/> multiplied by <see cref="ShoppingCartItem.Quantity"/>. /// </summary> public CalculatedPrice Subtotal { get; init; } } }
ShoppingCartLineItem
csharp
bitwarden__server
src/Core/Platform/Installations/Queries/GetInstallationQuery/IGetInstallationQuery.cs
{ "start": 86, "end": 210 }
interface ____ for fetching an installation from /// `InstallationRepository`. /// </summary> /// <remarks> /// This
responsible
csharp
icsharpcode__SharpZipLib
src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs
{ "start": 129040, "end": 129846 }
public class ____ : IDynamicDataSource { #region IDataSource Members /// <summary> /// Get a <see cref="Stream"/> providing data for an entry. /// </summary> /// <param name="entry">The entry to provide data for.</param> /// <param name="name">The file name for data if known.</param> /// <returns>Returns a stream providing data; or null if not available</returns> public Stream GetSource(ZipEntry entry, string name) { Stream result = null; if (name != null) { result = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); } return result; } #endregion IDataSource Members } #endregion DataSources #region Archive Storage /// <summary> /// Defines facilities for data storage when updating Zip Archives. /// </summary>
DynamicDiskDataSource
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Misc.Omnisend/DTO/Events/TrackingItem.cs
{ "start": 73, "end": 374 }
public class ____ { [JsonProperty("code")] public string Code { get; set; } [JsonProperty("courierTitle")] public string CourierTitle { get; set; } [JsonProperty("courierURL")] public string CourierURL { get; set; } [JsonProperty("status")] public string Status { get; set; } }
TrackingItem
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Cms/IWidgetPlugin.cs
{ "start": 88, "end": 135 }
interface ____ creating widgets /// </summary>
for
csharp
dotnet__orleans
test/Orleans.Serialization.UnitTests/NumericsWideningAndNarrowingTests.cs
{ "start": 17138, "end": 17724 }
public sealed class ____ : INumber<ushort> { public ushort MinValue => ushort.MinValue; public ushort MaxValue => ushort.MaxValue; public ushort MultiplicativeIdentity => 1; public int Sign(ushort value) => 1; public ushort Add(ushort x, ushort y) => (ushort)(x + y); public ushort Subtract(ushort x, ushort y) => (ushort)(x - y); public ushort Divide(ushort x, ushort y) => (ushort)(x / y); public ushort CreateTruncating<TFrom>(TFrom from) => (ushort)Convert.ChangeType(from, typeof(ushort)); }
UShortNumber
csharp
NEventStore__NEventStore
src/NEventStore.Tests/PipelineHooksAwarePersistanceDecoratorTests.Async.cs
{ "start": 473, "end": 873 }
public class ____ : using_underlying_persistence { protected override void Because() { Decorator.Dispose(); } [Fact] public void should_dispose_the_underlying_persistence() { A.CallTo(() => persistence.Dispose()).MustHaveHappenedOnceExactly(); } } #if MSTEST [TestClass] #endif
when_disposing_the_decorator
csharp
dotnet__maui
src/Controls/tests/ManualTests/Tests/Editor/D9.xaml.cs
{ "start": 181, "end": 267 }
public partial class ____ : ContentPage { public D9() { InitializeComponent(); } }
D9
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Interactivity/EventRoute.cs
{ "start": 6068, "end": 6857 }
struct ____ { public RouteItem( Interactive target, Delegate? handler, Action<Delegate, object, RoutedEventArgs>? adapter, RoutingStrategies routes, bool handledEventsToo) { Target = target; Handler = handler; Adapter = adapter; Routes = routes; HandledEventsToo = handledEventsToo; } public Interactive Target { get; } public Delegate? Handler { get; } public Action<Delegate, object, RoutedEventArgs>? Adapter { get; } public RoutingStrategies Routes { get; } public bool HandledEventsToo { get; } } } }
RouteItem
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Execution/SerialExecutionStrategyTests.cs
{ "start": 103, "end": 3212 }
public class ____ { [Fact] public async Task VerifyCorrectExecutionOrder() { var sb = new StringBuilder(); Func<IResolveFieldContext, object> resolver = context => { sb.AppendLine(string.Join(".", context.ResponsePath)); return "test"; }; var leaderGraphType = new ObjectGraphType() { Name = "LoaderType" }; leaderGraphType.Field<StringGraphType>("lastName").Resolve(resolver); leaderGraphType.Field<StringGraphType>("name").Resolve(resolver); var familiesGraphType = new ObjectGraphType() { Name = "FamiliesType" }; familiesGraphType.Field("leader", leaderGraphType).Resolve(resolver); familiesGraphType.Field("leader_dataLoader", leaderGraphType).Resolve(context => { resolver(context); return new SimpleDataLoader<object>(ctx => { sb.AppendLine(string.Join(".", context.ResponsePath) + "-completed"); return Task.FromResult<object>("test"); }); }); var queryGraphType = new ObjectGraphType(); queryGraphType.Field("families", new ListGraphType(familiesGraphType)).Resolve(context => { resolver(context); return new object[] { "a", "a", "a" }; }); var mutationGraphType = new ObjectGraphType { Name = "Mutation" }; mutationGraphType.Field("families", new ListGraphType(familiesGraphType)).Resolve(context => { resolver(context); return new object[] { "a", "a", "a" }; }); var schema = new Schema { Query = queryGraphType, Mutation = mutationGraphType, }; var documentExecuter = new DocumentExecuter(); var executionOptions = new ExecutionOptions() { Schema = schema, Query = "mutation { families { leader_dataLoader { lastName name } leader { lastName name } } }", }; await documentExecuter.ExecuteAsync(executionOptions); sb.ToString().ShouldBeCrossPlat(""" families families.0.leader_dataLoader families.0.leader families.0.leader.lastName families.0.leader.name families.1.leader_dataLoader families.1.leader families.1.leader.lastName families.1.leader.name families.2.leader_dataLoader families.2.leader families.2.leader.lastName families.2.leader.name families.0.leader_dataLoader-completed families.1.leader_dataLoader-completed families.2.leader_dataLoader-completed families.0.leader_dataLoader.lastName families.0.leader_dataLoader.name families.1.leader_dataLoader.lastName families.1.leader_dataLoader.name families.2.leader_dataLoader.lastName families.2.leader_dataLoader.name """); } }
SerialExecutionStrategyTests
csharp
AutoFixture__AutoFixture
Src/AutoFixtureUnitTest/Kernel/SeedRequestSpecificationTest.cs
{ "start": 124, "end": 2611 }
public class ____ { [Fact] public void SutIsRequestSpecification() { // Arrange var dummyType = typeof(object); // Act var sut = new SeedRequestSpecification(dummyType); // Assert Assert.IsAssignableFrom<IRequestSpecification>(sut); } [Fact] public void InitializeWithNullTypeThrows() { // Arrange // Act & assert Assert.Throws<ArgumentNullException>(() => new SeedRequestSpecification(null)); } [Fact] public void TargetTypeIsCorrect() { // Arrange var expectedType = typeof(DayOfWeek); var sut = new SeedRequestSpecification(expectedType); // Act Type result = sut.TargetType; // Assert Assert.Equal(expectedType, result); } [Fact] public void IsSatisfiedByNullThrows() { // Arrange var dummyType = typeof(object); var sut = new SeedRequestSpecification(dummyType); // Act & assert Assert.Throws<ArgumentNullException>(() => sut.IsSatisfiedBy(null)); } [Fact] public void IsSatisfiedByNonSeedReturnsCorrectResult() { // Arrange var dummyType = typeof(object); var sut = new SeedRequestSpecification(dummyType); var nonSeedRequest = new object(); // Act var result = sut.IsSatisfiedBy(nonSeedRequest); // Assert Assert.False(result); } [Theory] [InlineData(typeof(object), typeof(object), true)] [InlineData(typeof(string), typeof(string), true)] [InlineData(typeof(string), typeof(int), false)] [InlineData(typeof(PropertyHolder<string>), typeof(FieldHolder<string>), false)] public void IsSatisfiedByReturnsCorrectResult(Type specType, Type seedRequestType, bool expectedResult) { // Arrange var sut = new SeedRequestSpecification(specType); var dummySeed = new object(); var seededRequest = new SeededRequest(seedRequestType, dummySeed); // Act var result = sut.IsSatisfiedBy(seededRequest); // Assert Assert.Equal(expectedResult, result); } } }
SeedRequestSpecificationTest
csharp
dotnet__orleans
test/Orleans.Serialization.UnitTests/Models.cs
{ "start": 17997, "end": 18118 }
public enum ____ { None, One, Two, Three } [GenerateSerializer]
MyCustomEnum
csharp
NLog__NLog
examples/targets/Configuration API/Trace/Simple/Example.cs
{ "start": 93, "end": 564 }
class ____ { static void Main(string[] args) { Trace.Listeners.Add(new ConsoleTraceListener()); TraceTarget target = new TraceTarget(); target.Layout = "${message}"; LoggingConfiguration nlogConfig = new LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(target); LogManager.Configuration = nlogConfig; Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } }
Example
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/ContentPickerFieldIndexHandler.cs
{ "start": 153, "end": 996 }
public class ____ : ContentFieldIndexHandler<ContentPickerField> { public override Task BuildIndexAsync(ContentPickerField field, BuildFieldIndexContext context) { var options = DocumentIndexOptions.Keyword | DocumentIndexOptions.Store; if (field.ContentItemIds.Length > 0) { foreach (var contentItemId in field.ContentItemIds) { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, contentItemId, options); } } } else { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, ContentIndexingConstants.NullValue, options); } } return Task.CompletedTask; } }
ContentPickerFieldIndexHandler
csharp
ServiceStack__ServiceStack.Redis
src/ServiceStack.Redis/Commands.cs
{ "start": 75, "end": 15403 }
public static class ____ { public readonly static byte[] Quit = "QUIT".ToUtf8Bytes(); public readonly static byte[] Auth = "AUTH".ToUtf8Bytes(); public readonly static byte[] Exists = "EXISTS".ToUtf8Bytes(); public readonly static byte[] Del = "DEL".ToUtf8Bytes(); public readonly static byte[] Type = "TYPE".ToUtf8Bytes(); public readonly static byte[] Keys = "KEYS".ToUtf8Bytes(); public readonly static byte[] RandomKey = "RANDOMKEY".ToUtf8Bytes(); public readonly static byte[] Rename = "RENAME".ToUtf8Bytes(); public readonly static byte[] RenameNx = "RENAMENX".ToUtf8Bytes(); public readonly static byte[] PExpire = "PEXPIRE".ToUtf8Bytes(); public readonly static byte[] PExpireAt = "PEXPIREAT".ToUtf8Bytes(); public readonly static byte[] DbSize = "DBSIZE".ToUtf8Bytes(); public readonly static byte[] Expire = "EXPIRE".ToUtf8Bytes(); public readonly static byte[] ExpireAt = "EXPIREAT".ToUtf8Bytes(); public readonly static byte[] Ttl = "TTL".ToUtf8Bytes(); public readonly static byte[] PTtl = "PTTL".ToUtf8Bytes(); public readonly static byte[] Select = "SELECT".ToUtf8Bytes(); public readonly static byte[] FlushDb = "FLUSHDB".ToUtf8Bytes(); public readonly static byte[] FlushAll = "FLUSHALL".ToUtf8Bytes(); public readonly static byte[] Ping = "PING".ToUtf8Bytes(); public readonly static byte[] Echo = "ECHO".ToUtf8Bytes(); public readonly static byte[] Save = "SAVE".ToUtf8Bytes(); public readonly static byte[] BgSave = "BGSAVE".ToUtf8Bytes(); public readonly static byte[] LastSave = "LASTSAVE".ToUtf8Bytes(); public readonly static byte[] Shutdown = "SHUTDOWN".ToUtf8Bytes(); public readonly static byte[] NoSave = "NOSAVE".ToUtf8Bytes(); public readonly static byte[] BgRewriteAof = "BGREWRITEAOF".ToUtf8Bytes(); public readonly static byte[] Info = "INFO".ToUtf8Bytes(); public readonly static byte[] SlaveOf = "SLAVEOF".ToUtf8Bytes(); public readonly static byte[] No = "NO".ToUtf8Bytes(); public readonly static byte[] One = "ONE".ToUtf8Bytes(); public readonly static byte[] ResetStat = "RESETSTAT".ToUtf8Bytes(); public readonly static byte[] Rewrite = "REWRITE".ToUtf8Bytes(); public readonly static byte[] Time = "TIME".ToUtf8Bytes(); public readonly static byte[] Segfault = "SEGFAULT".ToUtf8Bytes(); public readonly static byte[] Sleep = "SLEEP".ToUtf8Bytes(); public readonly static byte[] Dump = "DUMP".ToUtf8Bytes(); public readonly static byte[] Restore = "RESTORE".ToUtf8Bytes(); public readonly static byte[] Migrate = "MIGRATE".ToUtf8Bytes(); public readonly static byte[] Move = "MOVE".ToUtf8Bytes(); public readonly static byte[] Object = "OBJECT".ToUtf8Bytes(); public readonly static byte[] IdleTime = "IDLETIME".ToUtf8Bytes(); public readonly static byte[] Monitor = "MONITOR".ToUtf8Bytes(); //missing public readonly static byte[] Debug = "DEBUG".ToUtf8Bytes(); //missing public readonly static byte[] Config = "CONFIG".ToUtf8Bytes(); //missing public readonly static byte[] Client = "CLIENT".ToUtf8Bytes(); public readonly static byte[] List = "LIST".ToUtf8Bytes(); public readonly static byte[] Kill = "KILL".ToUtf8Bytes(); public readonly static byte[] Addr = "ADDR".ToUtf8Bytes(); public readonly static byte[] Id = "ID".ToUtf8Bytes(); public readonly static byte[] SkipMe = "SKIPME".ToUtf8Bytes(); public readonly static byte[] SetName = "SETNAME".ToUtf8Bytes(); public readonly static byte[] GetName = "GETNAME".ToUtf8Bytes(); public readonly static byte[] Pause = "PAUSE".ToUtf8Bytes(); public readonly static byte[] Role = "ROLE".ToUtf8Bytes(); //public readonly static byte[] Get = "GET".ToUtf8Bytes(); //public readonly static byte[] Set = "SET".ToUtf8Bytes(); public readonly static byte[] StrLen = "STRLEN".ToUtf8Bytes(); public readonly static byte[] Set = "SET".ToUtf8Bytes(); public readonly static byte[] Get = "GET".ToUtf8Bytes(); public readonly static byte[] GetSet = "GETSET".ToUtf8Bytes(); public readonly static byte[] MGet = "MGET".ToUtf8Bytes(); public readonly static byte[] SetNx = "SETNX".ToUtf8Bytes(); public readonly static byte[] SetEx = "SETEX".ToUtf8Bytes(); public readonly static byte[] Persist = "PERSIST".ToUtf8Bytes(); public readonly static byte[] PSetEx = "PSETEX".ToUtf8Bytes(); public readonly static byte[] MSet = "MSET".ToUtf8Bytes(); public readonly static byte[] MSetNx = "MSETNX".ToUtf8Bytes(); public readonly static byte[] Incr = "INCR".ToUtf8Bytes(); public readonly static byte[] IncrBy = "INCRBY".ToUtf8Bytes(); public readonly static byte[] IncrByFloat = "INCRBYFLOAT".ToUtf8Bytes(); public readonly static byte[] Decr = "DECR".ToUtf8Bytes(); public readonly static byte[] DecrBy = "DECRBY".ToUtf8Bytes(); public readonly static byte[] Append = "APPEND".ToUtf8Bytes(); public readonly static byte[] GetRange = "GETRANGE".ToUtf8Bytes(); public readonly static byte[] SetRange = "SETRANGE".ToUtf8Bytes(); public readonly static byte[] GetBit = "GETBIT".ToUtf8Bytes(); public readonly static byte[] SetBit = "SETBIT".ToUtf8Bytes(); public readonly static byte[] BitCount = "BITCOUNT".ToUtf8Bytes(); public readonly static byte[] Scan = "SCAN".ToUtf8Bytes(); public readonly static byte[] SScan = "SSCAN".ToUtf8Bytes(); public readonly static byte[] HScan = "HSCAN".ToUtf8Bytes(); public readonly static byte[] ZScan = "ZSCAN".ToUtf8Bytes(); public readonly static byte[] Match = "MATCH".ToUtf8Bytes(); public readonly static byte[] Count = "COUNT".ToUtf8Bytes(); public readonly static byte[] PfAdd = "PFADD".ToUtf8Bytes(); public readonly static byte[] PfCount = "PFCOUNT".ToUtf8Bytes(); public readonly static byte[] PfMerge = "PFMERGE".ToUtf8Bytes(); public readonly static byte[] RPush = "RPUSH".ToUtf8Bytes(); public readonly static byte[] LPush = "LPUSH".ToUtf8Bytes(); public readonly static byte[] RPushX = "RPUSHX".ToUtf8Bytes(); public readonly static byte[] LPushX = "LPUSHX".ToUtf8Bytes(); public readonly static byte[] LLen = "LLEN".ToUtf8Bytes(); public readonly static byte[] LRange = "LRANGE".ToUtf8Bytes(); public readonly static byte[] LTrim = "LTRIM".ToUtf8Bytes(); public readonly static byte[] LIndex = "LINDEX".ToUtf8Bytes(); public readonly static byte[] LInsert = "LINSERT".ToUtf8Bytes(); public readonly static byte[] Before = "BEFORE".ToUtf8Bytes(); public readonly static byte[] After = "AFTER".ToUtf8Bytes(); public readonly static byte[] LSet = "LSET".ToUtf8Bytes(); public readonly static byte[] LRem = "LREM".ToUtf8Bytes(); public readonly static byte[] LPop = "LPOP".ToUtf8Bytes(); public readonly static byte[] RPop = "RPOP".ToUtf8Bytes(); public readonly static byte[] BLPop = "BLPOP".ToUtf8Bytes(); public readonly static byte[] BRPop = "BRPOP".ToUtf8Bytes(); public readonly static byte[] RPopLPush = "RPOPLPUSH".ToUtf8Bytes(); public readonly static byte[] BRPopLPush = "BRPOPLPUSH".ToUtf8Bytes(); public readonly static byte[] SAdd = "SADD".ToUtf8Bytes(); public readonly static byte[] SRem = "SREM".ToUtf8Bytes(); public readonly static byte[] SPop = "SPOP".ToUtf8Bytes(); public readonly static byte[] SMove = "SMOVE".ToUtf8Bytes(); public readonly static byte[] SCard = "SCARD".ToUtf8Bytes(); public readonly static byte[] SIsMember = "SISMEMBER".ToUtf8Bytes(); public readonly static byte[] SInter = "SINTER".ToUtf8Bytes(); public readonly static byte[] SInterStore = "SINTERSTORE".ToUtf8Bytes(); public readonly static byte[] SUnion = "SUNION".ToUtf8Bytes(); public readonly static byte[] SUnionStore = "SUNIONSTORE".ToUtf8Bytes(); public readonly static byte[] SDiff = "SDIFF".ToUtf8Bytes(); public readonly static byte[] SDiffStore = "SDIFFSTORE".ToUtf8Bytes(); public readonly static byte[] SMembers = "SMEMBERS".ToUtf8Bytes(); public readonly static byte[] SRandMember = "SRANDMEMBER".ToUtf8Bytes(); public readonly static byte[] ZAdd = "ZADD".ToUtf8Bytes(); public readonly static byte[] ZRem = "ZREM".ToUtf8Bytes(); public readonly static byte[] ZIncrBy = "ZINCRBY".ToUtf8Bytes(); public readonly static byte[] ZRank = "ZRANK".ToUtf8Bytes(); public readonly static byte[] ZRevRank = "ZREVRANK".ToUtf8Bytes(); public readonly static byte[] ZRange = "ZRANGE".ToUtf8Bytes(); public readonly static byte[] ZRevRange = "ZREVRANGE".ToUtf8Bytes(); public readonly static byte[] ZRangeByScore = "ZRANGEBYSCORE".ToUtf8Bytes(); public readonly static byte[] ZRevRangeByScore = "ZREVRANGEBYSCORE".ToUtf8Bytes(); public readonly static byte[] ZCard = "ZCARD".ToUtf8Bytes(); public readonly static byte[] ZScore = "ZSCORE".ToUtf8Bytes(); public readonly static byte[] ZCount = "ZCOUNT".ToUtf8Bytes(); public readonly static byte[] ZRemRangeByRank = "ZREMRANGEBYRANK".ToUtf8Bytes(); public readonly static byte[] ZRemRangeByScore = "ZREMRANGEBYSCORE".ToUtf8Bytes(); public readonly static byte[] ZUnionStore = "ZUNIONSTORE".ToUtf8Bytes(); public readonly static byte[] ZInterStore = "ZINTERSTORE".ToUtf8Bytes(); public static readonly byte[] ZRangeByLex = "ZRANGEBYLEX".ToUtf8Bytes(); public static readonly byte[] ZLexCount = "ZLEXCOUNT".ToUtf8Bytes(); public static readonly byte[] ZRemRangeByLex = "ZREMRANGEBYLEX".ToUtf8Bytes(); public readonly static byte[] HSet = "HSET".ToUtf8Bytes(); public readonly static byte[] HSetNx = "HSETNX".ToUtf8Bytes(); public readonly static byte[] HGet = "HGET".ToUtf8Bytes(); public readonly static byte[] HMSet = "HMSET".ToUtf8Bytes(); public readonly static byte[] HMGet = "HMGET".ToUtf8Bytes(); public readonly static byte[] HIncrBy = "HINCRBY".ToUtf8Bytes(); public readonly static byte[] HIncrByFloat = "HINCRBYFLOAT".ToUtf8Bytes(); public readonly static byte[] HExists = "HEXISTS".ToUtf8Bytes(); public readonly static byte[] HDel = "HDEL".ToUtf8Bytes(); public readonly static byte[] HLen = "HLEN".ToUtf8Bytes(); public readonly static byte[] HKeys = "HKEYS".ToUtf8Bytes(); public readonly static byte[] HVals = "HVALS".ToUtf8Bytes(); public readonly static byte[] HGetAll = "HGETALL".ToUtf8Bytes(); public readonly static byte[] Sort = "SORT".ToUtf8Bytes(); public readonly static byte[] Watch = "WATCH".ToUtf8Bytes(); public readonly static byte[] UnWatch = "UNWATCH".ToUtf8Bytes(); public readonly static byte[] Multi = "MULTI".ToUtf8Bytes(); public readonly static byte[] Exec = "EXEC".ToUtf8Bytes(); public readonly static byte[] Discard = "DISCARD".ToUtf8Bytes(); public readonly static byte[] Subscribe = "SUBSCRIBE".ToUtf8Bytes(); public readonly static byte[] UnSubscribe = "UNSUBSCRIBE".ToUtf8Bytes(); public readonly static byte[] PSubscribe = "PSUBSCRIBE".ToUtf8Bytes(); public readonly static byte[] PUnSubscribe = "PUNSUBSCRIBE".ToUtf8Bytes(); public readonly static byte[] Publish = "PUBLISH".ToUtf8Bytes(); public readonly static byte[] WithScores = "WITHSCORES".ToUtf8Bytes(); public readonly static byte[] Limit = "LIMIT".ToUtf8Bytes(); public readonly static byte[] By = "BY".ToUtf8Bytes(); public readonly static byte[] Asc = "ASC".ToUtf8Bytes(); public readonly static byte[] Desc = "DESC".ToUtf8Bytes(); public readonly static byte[] Alpha = "ALPHA".ToUtf8Bytes(); public readonly static byte[] Store = "STORE".ToUtf8Bytes(); public readonly static byte[] Eval = "EVAL".ToUtf8Bytes(); public readonly static byte[] EvalSha = "EVALSHA".ToUtf8Bytes(); public readonly static byte[] Script = "SCRIPT".ToUtf8Bytes(); public readonly static byte[] Load = "LOAD".ToUtf8Bytes(); //public readonly static byte[] Exists = "EXISTS".ToUtf8Bytes(); public readonly static byte[] Flush = "FLUSH".ToUtf8Bytes(); public readonly static byte[] Slowlog = "SLOWLOG".ToUtf8Bytes(); public readonly static byte[] Ex = "EX".ToUtf8Bytes(); public readonly static byte[] Px = "PX".ToUtf8Bytes(); public readonly static byte[] Nx = "NX".ToUtf8Bytes(); public readonly static byte[] Xx = "XX".ToUtf8Bytes(); // Sentinel commands public readonly static byte[] Sentinel = "SENTINEL".ToUtf8Bytes(); public readonly static byte[] Masters = "masters".ToUtf8Bytes(); public readonly static byte[] Sentinels = "sentinels".ToUtf8Bytes(); public readonly static byte[] Master = "master".ToUtf8Bytes(); public readonly static byte[] Slaves = "slaves".ToUtf8Bytes(); public readonly static byte[] Failover = "failover".ToUtf8Bytes(); public readonly static byte[] GetMasterAddrByName = "get-master-addr-by-name".ToUtf8Bytes(); //Geo commands public readonly static byte[] GeoAdd = "GEOADD".ToUtf8Bytes(); public readonly static byte[] GeoDist = "GEODIST".ToUtf8Bytes(); public readonly static byte[] GeoHash = "GEOHASH".ToUtf8Bytes(); public readonly static byte[] GeoPos = "GEOPOS".ToUtf8Bytes(); public readonly static byte[] GeoRadius = "GEORADIUS".ToUtf8Bytes(); public readonly static byte[] GeoRadiusByMember = "GEORADIUSBYMEMBER".ToUtf8Bytes(); public readonly static byte[] WithCoord = "WITHCOORD".ToUtf8Bytes(); public readonly static byte[] WithDist = "WITHDIST".ToUtf8Bytes(); public readonly static byte[] WithHash = "WITHHASH".ToUtf8Bytes(); public readonly static byte[] Meters = RedisGeoUnit.Meters.ToUtf8Bytes(); public readonly static byte[] Kilometers = RedisGeoUnit.Kilometers.ToUtf8Bytes(); public readonly static byte[] Miles = RedisGeoUnit.Miles.ToUtf8Bytes(); public readonly static byte[] Feet = RedisGeoUnit.Feet.ToUtf8Bytes(); public static byte[] GetUnit(string unit) { if (unit == null) throw new ArgumentNullException("unit"); switch (unit) { case RedisGeoUnit.Meters: return Meters; case RedisGeoUnit.Kilometers: return Kilometers; case RedisGeoUnit.Miles: return Miles; case RedisGeoUnit.Feet: return Feet; default: throw new NotSupportedException("Unit '{0}' is not a valid unit".Fmt(unit)); } } } }
Commands
csharp
dotnet__aspnetcore
src/Features/JsonPatch.SystemTextJson/src/Adapters/ObjectAdapter.cs
{ "start": 471, "end": 10934 }
internal class ____ : IObjectAdapterWithTest { /// <summary> /// Initializes a new instance of <see cref="ObjectAdapter"/>. /// </summary> /// <param name="serializerOptions">The <see cref="JsonSerializerOptions"/>.</param> /// <param name="logErrorAction">The <see cref="Action"/> for logging <see cref="JsonPatchError"/>.</param> public ObjectAdapter( JsonSerializerOptions serializerOptions, Action<JsonPatchError> logErrorAction) : this(serializerOptions, logErrorAction, Adapters.AdapterFactory.Default) { } /// <summary> /// Initializes a new instance of <see cref="ObjectAdapter"/>. /// </summary> /// <param name="serializerOptions">The <see cref="JsonSerializerOptions"/>.</param> /// <param name="logErrorAction">The <see cref="Action"/> for logging <see cref="JsonPatchError"/>.</param> /// <param name="adapterFactory">The <see cref="IAdapterFactory"/> to use when creating adaptors.</param> public ObjectAdapter( JsonSerializerOptions serializerOptions, Action<JsonPatchError> logErrorAction, IAdapterFactory adapterFactory) { SerializerOptions = serializerOptions ?? throw new ArgumentNullException(nameof(serializerOptions)); LogErrorAction = logErrorAction; AdapterFactory = adapterFactory ?? throw new ArgumentNullException(nameof(adapterFactory)); } /// <summary> /// Gets or sets the <see cref="IJsonTypeInfoResolver"/>. /// </summary> public JsonSerializerOptions SerializerOptions { get; } /// <summary> /// Gets or sets the <see cref="IAdapterFactory"/> /// </summary> public IAdapterFactory AdapterFactory { get; } /// <summary> /// Action for logging <see cref="JsonPatchError"/>. /// </summary> public Action<JsonPatchError> LogErrorAction { get; } public void Add(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); Add(operation.path, operation.value, objectToApplyTo, operation); } /// <summary> /// Add is used by various operations (eg: add, copy, ...), yet through different operations; /// This method allows code reuse yet reporting the correct operation on error /// </summary> private void Add( string path, object value, object objectToApplyTo, Operation operation) { ArgumentNullThrowHelper.ThrowIfNull(path); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); ArgumentNullThrowHelper.ThrowIfNull(operation); var parsedPath = new ParsedPath(path); var visitor = new ObjectVisitor(parsedPath, SerializerOptions, AdapterFactory); var target = objectToApplyTo; // Find the target object and the appropriate adapter if (!visitor.TryVisit(ref target, out var adapter, out var errorMessage)) { var error = CreatePathNotFoundError(objectToApplyTo, path, operation, errorMessage); ErrorReporter(error); return; } if (!adapter.TryAdd(target, parsedPath.LastSegment, SerializerOptions, value, out errorMessage)) { var error = CreateOperationFailedError(objectToApplyTo, path, operation, errorMessage); ErrorReporter(error); return; } } public void Move(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); // Get value at 'from' location and add that value to the 'path' location if (TryGetValue(operation.from, objectToApplyTo, operation, out var propertyValue)) { // remove that value Remove(operation.from, objectToApplyTo, operation); // add that value to the path location Add(operation.path, propertyValue, objectToApplyTo, operation); } } public void Remove(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); Remove(operation.path, objectToApplyTo, operation); } /// <summary> /// Remove is used by various operations (eg: remove, move, ...), yet through different operations; /// This method allows code reuse yet reporting the correct operation on error. The return value /// contains the type of the item that has been removed (and a bool possibly signifying an error) /// This can be used by other methods, like replace, to ensure that we can pass in the correctly /// typed value to whatever method follows. /// </summary> private void Remove(string path, object objectToApplyTo, Operation operationToReport) { var parsedPath = new ParsedPath(path); var visitor = new ObjectVisitor(parsedPath, SerializerOptions, AdapterFactory); var target = objectToApplyTo; if (!visitor.TryVisit(ref target, out var adapter, out var errorMessage)) { var error = CreatePathNotFoundError(objectToApplyTo, path, operationToReport, errorMessage); ErrorReporter(error); return; } if (!adapter.TryRemove(target, parsedPath.LastSegment, SerializerOptions, out errorMessage)) { var error = CreateOperationFailedError(objectToApplyTo, path, operationToReport, errorMessage); ErrorReporter(error); return; } } public void Replace(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); var parsedPath = new ParsedPath(operation.path); var visitor = new ObjectVisitor(parsedPath, SerializerOptions, AdapterFactory); var target = objectToApplyTo; if (!visitor.TryVisit(ref target, out var adapter, out var errorMessage)) { var error = CreatePathNotFoundError(objectToApplyTo, operation.path, operation, errorMessage); ErrorReporter(error); return; } if (!adapter.TryReplace(target, parsedPath.LastSegment, SerializerOptions, operation.value, out errorMessage)) { var error = CreateOperationFailedError(objectToApplyTo, operation.path, operation, errorMessage); ErrorReporter(error); return; } } public void Copy(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); // Get value at 'from' location and add that value to the 'path' location if (TryGetValue(operation.from, objectToApplyTo, operation, out var propertyValue)) { // Create deep copy var copyResult = ConversionResultProvider.CopyTo(propertyValue, propertyValue?.GetType(), SerializerOptions); if (copyResult.CanBeConverted) { Add(operation.path, copyResult.ConvertedInstance, objectToApplyTo, operation); } else { var error = CreateOperationFailedError(objectToApplyTo, operation.path, operation, Resources.FormatCannotCopyProperty(operation.from)); ErrorReporter(error); return; } } } public void Test(Operation operation, object objectToApplyTo) { ArgumentNullThrowHelper.ThrowIfNull(operation); ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); var parsedPath = new ParsedPath(operation.path); var visitor = new ObjectVisitor(parsedPath, SerializerOptions, AdapterFactory); var target = objectToApplyTo; if (!visitor.TryVisit(ref target, out var adapter, out var errorMessage)) { var error = CreatePathNotFoundError(objectToApplyTo, operation.path, operation, errorMessage); ErrorReporter(error); return; } if (!adapter.TryTest(target, parsedPath.LastSegment, SerializerOptions, operation.value, out errorMessage)) { var error = CreateOperationFailedError(objectToApplyTo, operation.path, operation, errorMessage); ErrorReporter(error); return; } } private bool TryGetValue( string fromLocation, object objectToGetValueFrom, Operation operation, out object propertyValue) { ArgumentNullThrowHelper.ThrowIfNull(fromLocation); ArgumentNullThrowHelper.ThrowIfNull(objectToGetValueFrom); ArgumentNullThrowHelper.ThrowIfNull(operation); propertyValue = null; var parsedPath = new ParsedPath(fromLocation); var visitor = new ObjectVisitor(parsedPath, SerializerOptions, AdapterFactory); var target = objectToGetValueFrom; if (!visitor.TryVisit(ref target, out var adapter, out var errorMessage)) { var error = CreatePathNotFoundError(objectToGetValueFrom, fromLocation, operation, errorMessage); ErrorReporter(error); return false; } if (!adapter.TryGet(target, parsedPath.LastSegment, SerializerOptions, out propertyValue, out errorMessage)) { var error = CreateOperationFailedError(objectToGetValueFrom, fromLocation, operation, errorMessage); ErrorReporter(error); return false; } return true; } private Action<JsonPatchError> ErrorReporter { get { return LogErrorAction ?? Internal.ErrorReporter.Default; } } private static JsonPatchError CreateOperationFailedError(object target, string path, Operation operation, string errorMessage) { return new JsonPatchError( target, operation, errorMessage ?? Resources.FormatCannotPerformOperation(operation.op, path)); } private static JsonPatchError CreatePathNotFoundError(object target, string path, Operation operation, string errorMessage) { return new JsonPatchError( target, operation, errorMessage ?? Resources.FormatTargetLocationNotFound(operation.op, path)); } }
ObjectAdapter
csharp
dotnet__aspnetcore
src/Shared/HttpSys/RequestProcessing/RequestUriBuilder.cs
{ "start": 662, "end": 10784 }
internal static class ____ { private static readonly Encoding UTF8 = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static string DecodeAndUnescapePath(Span<byte> rawUrlBytes) { Debug.Assert(rawUrlBytes.Length != 0, "Length of the URL cannot be zero."); var rawPath = RawUrlHelper.GetPath(rawUrlBytes); if (rawPath.Length == 0) { return "/"; } // OPTIONS * // RemoveDotSegments Asserts path always starts with a '/' if (rawPath.Length == 1 && rawPath[0] == (byte)'*') { return "*"; } var unescapedPath = Unescape(rawPath); var length = PathNormalizer.RemoveDotSegments(unescapedPath); return UTF8.GetString(unescapedPath.Slice(0, length)); } /// <summary> /// Unescape a given path string in place. The given path string may contain escaped char. /// </summary> /// <param name="rawPath">The raw path string to be unescaped</param> /// <returns>The unescaped path string</returns> private static Span<byte> Unescape(Span<byte> rawPath) { // the slot to read the input var reader = 0; // the slot to write the unescaped byte var writer = 0; // the end of the path var end = rawPath.Length; while (true) { if (reader == end) { break; } if (rawPath[reader] == '%') { var decodeReader = reader; // If decoding process succeeds, the writer iterator will be moved // to the next write-ready location. On the other hand if the scanned // percent-encodings cannot be interpreted as sequence of UTF-8 octets, // these bytes should be copied to output as is. // The decodeReader iterator is always moved to the first byte not yet // be scanned after the process. A failed decoding means the chars // between the reader and decodeReader can be copied to output untouched. if (!DecodeCore(ref decodeReader, ref writer, end, rawPath)) { Copy(reader, decodeReader, ref writer, rawPath); } reader = decodeReader; } else { rawPath[writer++] = rawPath[reader++]; } } return rawPath.Slice(0, writer); } /// <summary> /// Unescape the percent-encodings /// </summary> /// <param name="reader">The iterator point to the first % char</param> /// <param name="writer">The place to write to</param> /// <param name="end">The end of the buffer</param> /// <param name="buffer">The byte array</param> private static bool DecodeCore(ref int reader, ref int writer, int end, Span<byte> buffer) { // preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets, // bytes from this till the last scanned one will be copied to the memory pointed by writer. var byte1 = UnescapePercentEncoding(ref reader, end, buffer); if (!byte1.HasValue) { return false; } if (byte1 == 0) { throw new InvalidOperationException("The path contains null characters."); } if (byte1 <= 0x7F) { // first byte < U+007f, it is a single byte ASCII buffer[writer++] = (byte)byte1; return true; } int byte2 = 0, byte3 = 0, byte4 = 0; // anticipate more bytes int currentDecodeBits; int byteCount; int expectValueMin; if ((byte1 & 0xE0) == 0xC0) { // 110x xxxx, expect one more byte currentDecodeBits = byte1.Value & 0x1F; byteCount = 2; expectValueMin = 0x80; } else if ((byte1 & 0xF0) == 0xE0) { // 1110 xxxx, expect two more bytes currentDecodeBits = byte1.Value & 0x0F; byteCount = 3; expectValueMin = 0x800; } else if ((byte1 & 0xF8) == 0xF0) { // 1111 0xxx, expect three more bytes currentDecodeBits = byte1.Value & 0x07; byteCount = 4; expectValueMin = 0x10000; } else { // invalid first byte return false; } var remainingBytes = byteCount - 1; while (remainingBytes > 0) { // read following three chars if (reader == buffer.Length) { return false; } var nextItr = reader; var nextByte = UnescapePercentEncoding(ref nextItr, end, buffer); if (!nextByte.HasValue) { return false; } if ((nextByte & 0xC0) != 0x80) { // the follow up byte is not in form of 10xx xxxx return false; } currentDecodeBits = (currentDecodeBits << 6) | (nextByte.Value & 0x3F); remainingBytes--; if (remainingBytes == 1 && currentDecodeBits >= 0x360 && currentDecodeBits <= 0x37F) { // this is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that // are not allowed in UTF-8; return false; } if (remainingBytes == 2 && currentDecodeBits >= 0x110) { // this is going to be out of the upper Unicode bound 0x10FFFF. return false; } reader = nextItr; if (byteCount - remainingBytes == 2) { byte2 = nextByte.Value; } else if (byteCount - remainingBytes == 3) { byte3 = nextByte.Value; } else if (byteCount - remainingBytes == 4) { byte4 = nextByte.Value; } } if (currentDecodeBits < expectValueMin) { // overlong encoding (e.g. using 2 bytes to encode something that only needed 1). return false; } // all bytes are verified, write to the output if (byteCount > 0) { buffer[writer++] = (byte)byte1; } if (byteCount > 1) { buffer[writer++] = (byte)byte2; } if (byteCount > 2) { buffer[writer++] = (byte)byte3; } if (byteCount > 3) { buffer[writer++] = (byte)byte4; } return true; } private static void Copy(int begin, int end, ref int writer, Span<byte> buffer) { while (begin != end) { buffer[writer++] = buffer[begin++]; } } /// <summary> /// Read the percent-encoding and try unescape it. /// /// The operation first peek at the character the <paramref name="scan"/> /// iterator points at. If it is % the <paramref name="scan"/> is then /// moved on to scan the following to characters. If the two following /// characters are hexadecimal literals they will be unescaped and the /// value will be returned. /// /// If the first character is not % the <paramref name="scan"/> iterator /// will be removed beyond the location of % and -1 will be returned. /// /// If the following two characters can't be successfully unescaped the /// <paramref name="scan"/> iterator will be move behind the % and -1 /// will be returned. /// </summary> /// <param name="scan">The value to read</param> /// <param name="end">The end of the buffer</param> /// <param name="buffer">The byte array</param> /// <returns>The unescaped byte if success. Otherwise return -1.</returns> private static int? UnescapePercentEncoding(ref int scan, int end, ReadOnlySpan<byte> buffer) { if (buffer[scan++] != '%') { return -1; } var probe = scan; var value1 = ReadHex(ref probe, end, buffer); if (!value1.HasValue) { return null; } var value2 = ReadHex(ref probe, end, buffer); if (!value2.HasValue) { return null; } if (SkipUnescape(value1.Value, value2.Value)) { return null; } scan = probe; return (value1.Value << 4) + value2.Value; } /// <summary> /// Read the next char and convert it into hexadecimal value. /// /// The <paramref name="scan"/> iterator will be moved to the next /// byte no matter no matter whether the operation successes. /// </summary> /// <param name="scan">The value to read</param> /// <param name="end">The end of the buffer</param> /// <param name="buffer">The byte array</param> /// <returns>The hexadecimal value if successes, otherwise -1.</returns> private static int? ReadHex(ref int scan, int end, ReadOnlySpan<byte> buffer) { if (scan == end) { return null; } var value = buffer[scan++]; var isHead = (((value >= '0') && (value <= '9')) || ((value >= 'A') && (value <= 'F')) || ((value >= 'a') && (value <= 'f'))); if (!isHead) { return null; } if (value <= '9') { return value - '0'; } else if (value <= 'F') { return (value - 'A') + 10; } else // a - f { return (value - 'a') + 10; } } private static bool SkipUnescape(int value1, int value2) { // skip %2F - '/' if (value1 == 2 && value2 == 15) { return true; } return false; } }
RequestUriBuilder
csharp
MonoGame__MonoGame
MonoGame.Framework/Graphics/TextureCube.cs
{ "start": 1129, "end": 17175 }
public partial class ____ : Texture { internal int size; /// <summary> /// Gets the width and height of the cube map face in pixels. /// </summary> /// <value>The width and height of a cube map face in pixels.</value> public int Size { get { return size; } } /// <summary> /// Creates an uninitialized <b>TextureCube</b> resource of the specified dimensions /// </summary> /// <param name="graphicsDevice">The graphics device that will display the cube texture.</param> /// <param name="size">The width and height, in pixels, of the cube texture.</param> /// <param name="mipMap"><b>true</b> if mimapping is enabled for this cube texture; otherwise, <b>false</b>.</param> /// <param name="format">The surface format used by this cube texture.</param> /// <exception cref="ArgumentNullException"> The <paramref name="graphicsDevice"/> parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="size"/> parameter is less than or equal to zero.</exception> public TextureCube (GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat format) : this(graphicsDevice, size, mipMap, format, false) { } internal TextureCube(GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat format, bool renderTarget) { if (graphicsDevice == null) throw new ArgumentNullException("graphicsDevice", FrameworkResources.ResourceCreationWhenDeviceIsNull); if (size <= 0) throw new ArgumentOutOfRangeException("size","Cube size must be greater than zero"); this.GraphicsDevice = graphicsDevice; this.size = size; this._format = format; this._levelCount = mipMap ? CalculateMipLevels(size) : 1; PlatformConstruct(graphicsDevice, size, mipMap, format, renderTarget); } /// <summary> /// Copies the texture cube data into an array. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="cubeMapFace">The cube map face.</param> /// <param name="data">The array of data to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void GetData<T>(CubeMapFace cubeMapFace, T[] data) where T : struct { if (data == null) throw new ArgumentNullException("data"); GetData(cubeMapFace, 0, null, data, 0, data.Length); } /// <summary> /// Copies the texture cube data into an array. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="cubeMapFace">The cube map face.</param> /// <param name="data">The array of data to copy.</param> /// <param name="startIndex">The index of the element in the array at which to start copying.</param> /// <param name="elementCount">The number of elements to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="startIndex"/> parameter is less than zero or is greater than or equal to the /// length of the data array. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void GetData<T>(CubeMapFace cubeMapFace, T[] data, int startIndex, int elementCount) where T : struct { GetData(cubeMapFace, 0, null, data, startIndex, elementCount); } /// <summary> /// Copies the texture cube data into an array. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="cubeMapFace">The cube map face.</param> /// <param name="level">The mipmap level to copy from.</param> /// <param name="rect"> /// The section of the texture where the data will be placed. null indicates the data will be copied over the /// entire texture. /// </param> /// <param name="data">The array of data to copy.</param> /// <param name="startIndex">The index of the element in the array at which to start copying.</param> /// <param name="elementCount">The number of elements to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <paramref name="level"/> parameter is larger than the number of levels in this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="rect"/> is outside the bounds of the texture. /// </description> /// </item> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="startIndex"/> parameter is less than zero or is greater than or equal to the /// length of the data array. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void GetData<T>(CubeMapFace cubeMapFace, int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct { Rectangle checkedRect; ValidateParams(level, rect, data, startIndex, elementCount, out checkedRect); PlatformGetData(cubeMapFace, level, checkedRect, data, startIndex, elementCount); } /// <summary> /// Copies an array of data to the texture cube. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="face">The Cubemap face.</param> /// <param name="data">The array of data to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void SetData<T> (CubeMapFace face, T[] data) where T : struct { if (data == null) throw new ArgumentNullException("data"); SetData(face, 0, null, data, 0, data.Length); } /// <summary> /// Copies an array of data to the texture cube. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="face">The Cubemap face.</param> /// <param name="data">The array of data to copy.</param> /// <param name="startIndex">The index of the element in the array at which to start copying.</param> /// <param name="elementCount">The number of elements to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="startIndex"/> parameter is less than zero or is greater than or equal to the /// length of the data array. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void SetData<T>(CubeMapFace face, T[] data, int startIndex, int elementCount) where T : struct { SetData(face, 0, null, data, startIndex, elementCount); } /// <summary> /// Copies an array of data to the texture cube. /// </summary> /// <typeparam name="T">The type of the elements in the array.</typeparam> /// <param name="face">The Cubemap face.</param> /// <param name="level">The mipmap level where the data will be placed.</param> /// <param name="rect"> /// The section of the texture where the data will be placed. null indicates the data will be copied over the /// entire texture. /// </param> /// <param name="data">The array of data to copy.</param> /// <param name="startIndex">The index of the element in the array at which to start copying.</param> /// <param name="elementCount">The number of elements to copy.</param> /// <exception cref="ArgumentException"> /// One of the following conditions is true: /// <list type="bullet"> /// <item> /// <description> /// The <paramref name="level"/> parameter is larger than the number of levels in this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="rect"/> is outside the bounds of the texture. /// </description> /// </item> /// <item> /// <description> /// The <typeparamref name="T"/> type size is invalid for the format of this texture. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="startIndex"/> parameter is less than zero or is greater than or equal to the /// length of the data array. /// </description> /// </item> /// <item> /// <description> /// The <paramref name="data"/> array parameter is too small. /// </description> /// </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">The <paramref name="data"/> parameter is null.</exception> public void SetData<T>(CubeMapFace face, int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct { Rectangle checkedRect; ValidateParams(level, rect, data, startIndex, elementCount, out checkedRect); PlatformSetData(face, level, checkedRect, data, startIndex, elementCount); } private void ValidateParams<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount, out Rectangle checkedRect) where T : struct { var textureBounds = new Rectangle(0, 0, Math.Max(Size >> level, 1), Math.Max(Size >> level, 1)); checkedRect = rect ?? textureBounds; if (level < 0 || level >= LevelCount) throw new ArgumentException("level must be smaller than the number of levels in this texture."); if (!textureBounds.Contains(checkedRect) || checkedRect.Width <= 0 || checkedRect.Height <= 0) throw new ArgumentException("Rectangle must be inside the texture bounds", "rect"); if (data == null) throw new ArgumentNullException("data"); var tSize = ReflectionHelpers.FastSizeOf<T>(); var fSize = Format.GetSize(); if (tSize > fSize || fSize % tSize != 0) throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); if (startIndex < 0 || startIndex >= data.Length) throw new ArgumentException("startIndex must be at least zero and smaller than data.Length.", "startIndex"); if (data.Length < startIndex + elementCount) throw new ArgumentException("The data array is too small."); int dataByteSize; if (Format.IsCompressedFormat()) { // round x and y down to next multiple of four; width and height up to next multiple of four var roundedWidth = (checkedRect.Width + 3) & ~0x3; var roundedHeight = (checkedRect.Height + 3) & ~0x3; checkedRect = new Rectangle(checkedRect.X & ~0x3, checkedRect.Y & ~0x3, #if OPENGL // OpenGL only: The last two mip levels require the width and height to be // passed as 2x2 and 1x1, but there needs to be enough data passed to occupy // a 4x4 block. checkedRect.Width < 4 && textureBounds.Width < 4 ? textureBounds.Width : roundedWidth, checkedRect.Height < 4 && textureBounds.Height < 4 ? textureBounds.Height : roundedHeight); #else roundedWidth, roundedHeight); #endif dataByteSize = roundedWidth * roundedHeight * fSize / 16; } else { dataByteSize = checkedRect.Width * checkedRect.Height * fSize; } if (elementCount * tSize != dataByteSize) throw new ArgumentException(string.Format("elementCount is not the right size, " + "elementCount * sizeof(T) is {0}, but data size is {1}.", elementCount * tSize, dataByteSize), "elementCount"); } } }
TextureCube
csharp
npgsql__efcore.pg
test/EFCore.PG.FunctionalTests/Query/TPTGearsOfWarQueryNpgsqlTest.cs
{ "start": 113, "end": 3230 }
public class ____ : TPTGearsOfWarQueryRelationalTestBase<TPTGearsOfWarQueryNpgsqlFixture> { // ReSharper disable once UnusedParameter.Local public TPTGearsOfWarQueryNpgsqlTest(TPTGearsOfWarQueryNpgsqlFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } // TODO: #1232 // protected override bool CanExecuteQueryString => true; // Base implementation uses DateTimeOffset.Now, which we don't translate by design. Use DateTimeOffset.UtcNow instead. public override async Task Select_datetimeoffset_comparison_in_projection(bool async) { await AssertQueryScalar( async, ss => ss.Set<Mission>().Select(m => m.Timeline > DateTimeOffset.UtcNow)); AssertSql( """ SELECT m."Timeline" > now() FROM "Missions" AS m """); } public override async Task DateTimeOffset_Contains_Less_than_Greater_than(bool async) { var dto = new DateTimeOffset(599898024001234567, new TimeSpan(0)); var start = dto.AddDays(-1); var end = dto.AddDays(1); var dates = new[] { dto }; await AssertQuery( async, ss => ss.Set<Mission>().Where( m => start <= m.Timeline.Date && m.Timeline < end && dates.Contains(m.Timeline)), assertEmpty: true); // TODO: Check this out AssertSql( """ @start='1902-01-01T10:00:00.1234567+00:00' (DbType = DateTime) @end='1902-01-03T10:00:00.1234567+00:00' (DbType = DateTime) @dates={ '1902-01-02T10:00:00.1234567+00:00' } (DbType = Object) SELECT m."Id", m."CodeName", m."Date", m."Difficulty", m."Duration", m."Rating", m."Time", m."Timeline" FROM "Missions" AS m WHERE @start <= date_trunc('day', m."Timeline" AT TIME ZONE 'UTC')::timestamptz AND m."Timeline" < @end AND m."Timeline" = ANY (@dates) """); } public override async Task DateTimeOffset_Date_returns_datetime(bool async) { var dateTimeOffset = new DateTimeOffset(2, 3, 1, 8, 0, 0, new TimeSpan(-5, 0, 0)); await AssertQuery( async, ss => ss.Set<Mission>().Where(m => m.Timeline.Date.ToLocalTime() >= dateTimeOffset.Date)); AssertSql( """ @dateTimeOffset_Date='0002-03-01T00:00:00.0000000' SELECT m."Id", m."CodeName", m."Date", m."Difficulty", m."Duration", m."Rating", m."Time", m."Timeline" FROM "Missions" AS m WHERE date_trunc('day', m."Timeline" AT TIME ZONE 'UTC')::timestamp >= @dateTimeOffset_Date """); } // Not supported by design: we support getting a local DateTime via DateTime.Now (based on PG TimeZone), but there's no way to get a // non-UTC DateTimeOffset. public override Task DateTimeOffsetNow_minus_timespan(bool async) => Assert.ThrowsAsync<InvalidOperationException>(() => base.DateTimeOffsetNow_minus_timespan(async)); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); }
TPTGearsOfWarQueryNpgsqlTest
csharp
cake-build__cake
src/Cake.Common/Tools/Chocolatey/Pack/ChocolateyPackSettings.cs
{ "start": 427, "end": 5629 }
public sealed class ____ : ChocolateySettings { /// <summary> /// Gets or sets the package ID. /// </summary> /// <value>The package ID.</value> public string Id { get; set; } /// <summary> /// Gets or sets the package title. /// </summary> /// <value>The package title.</value> public string Title { get; set; } /// <summary> /// Gets or sets the package authors. /// </summary> /// <value>The package authors.</value> public ICollection<string> Authors { get; set; } = new List<string>(); /// <summary> /// Gets or sets the package owners. /// </summary> /// <value>The package owners.</value> public ICollection<string> Owners { get; set; } = new List<string>(); /// <summary> /// Gets or sets the package summary. /// </summary> /// <value>The package summary.</value> public string Summary { get; set; } /// <summary> /// Gets or sets the package description. /// </summary> /// <value>The package description.</value> /// <remarks>Markdown format is allowed for this property.</remarks> public string Description { get; set; } /// <summary> /// Gets or sets the package project URL. /// </summary> /// <value>The package project URL.</value> public Uri ProjectUrl { get; set; } /// <summary> /// Gets or sets the package Source URL. /// </summary> /// <value>The package Source URL.</value> /// <remarks>Requires at least Chocolatey 0.9.9.7.</remarks> public Uri PackageSourceUrl { get; set; } /// <summary> /// Gets or sets the package project Source URL. /// </summary> /// <value>The package project Source URL.</value> /// <remarks>Requires at least Chocolatey 0.9.9.7.</remarks> public Uri ProjectSourceUrl { get; set; } /// <summary> /// Gets or sets the package documentation URL. /// </summary> /// <value>The package documentation URL.</value> /// <remarks>Requires at least Chocolatey 0.9.9.7.</remarks> public Uri DocsUrl { get; set; } /// <summary> /// Gets or sets the package mailing list URL. /// </summary> /// <value>The package mailing list URL.</value> /// <remarks>Requires at least Chocolatey 0.9.9.7.</remarks> public Uri MailingListUrl { get; set; } /// <summary> /// Gets or sets the package bug tracker URL. /// </summary> /// <value>The package bug tracker URL.</value> /// <remarks>Requires at least Chocolatey 0.9.9.7.</remarks> public Uri BugTrackerUrl { get; set; } /// <summary> /// Gets or sets the package tags. /// </summary> /// <value>The package tags.</value> public ICollection<string> Tags { get; set; } = new List<string>(); /// <summary> /// Gets or sets the package copyright. /// </summary> /// <value>The package copyright.</value> public string Copyright { get; set; } /// <summary> /// Gets or sets the package license URL. /// </summary> /// <value>The package license URL.</value> public Uri LicenseUrl { get; set; } /// <summary> /// Gets or sets a value indicating whether users has to accept the package license. /// </summary> /// <value> /// <c>true</c> if users has to accept the package license; otherwise, <c>false</c>. /// </value> public bool RequireLicenseAcceptance { get; set; } /// <summary> /// Gets or sets the package icon URL. /// </summary> /// <value>The package icon URL.</value> public Uri IconUrl { get; set; } /// <summary> /// Gets or sets the package release notes. /// </summary> /// <value>The package release notes.</value> /// <remarks>Markdown format is allowed for this property.</remarks> public ICollection<string> ReleaseNotes { get; set; } = new List<string>(); /// <summary> /// Gets or sets the package files. /// </summary> /// <value>The package files.</value> public ICollection<ChocolateyNuSpecContent> Files { get; set; } = new List<ChocolateyNuSpecContent>(); /// <summary> /// Gets or sets the package dependencies. /// </summary> /// <value>The package files.</value> public ICollection<ChocolateyNuSpecDependency> Dependencies { get; set; } = new List<ChocolateyNuSpecDependency>(); /// <summary> /// Gets or sets the Nuspec version. /// </summary> /// <value>The Nuspec version.</value> public string Version { get; set; } /// <summary> /// Gets or sets a value indicating the Working Directory that should be used while running choco.exe. /// </summary> public DirectoryPath OutputDirectory { get; set; } } }
ChocolateyPackSettings
csharp
dotnet__orleans
test/Extensions/Tester.Cosmos/PersistenceProviderTests_Cosmos.cs
{ "start": 9190, "end": 10252 }
public class ____ { [JsonPropertyName("s")] public string String { get; set; } internal static GrainState<TestStoreGrainStateWithCustomJsonProperties> NewRandomState(int? aPropertyLength = null) { return new GrainState<TestStoreGrainStateWithCustomJsonProperties> { State = new TestStoreGrainStateWithCustomJsonProperties { String = aPropertyLength == null ? Random.Shared.Next().ToString(CultureInfo.InvariantCulture) : GenerateRandomDigitString(aPropertyLength.Value) } }; } private static string GenerateRandomDigitString(int stringLength) { var characters = new char[stringLength]; for (var i = 0; i < stringLength; ++i) { characters[i] = (char)Random.Shared.Next('0', '9' + 1); } return new string(characters); } } }
TestStoreGrainStateWithCustomJsonProperties
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationBaseTests.cs
{ "start": 829, "end": 23144 }
public class ____ : OperationTestBase { // fields private readonly BsonJavaScript _mapFunction = "map"; private readonly BsonJavaScript _reduceFunction = "reduce"; // test methods [Theory] [ParameterAttributeData] public void Collation_should_get_and_set_value( [Values(null, "en_US", "fr_CA")] string locale) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = locale == null ? null : new Collation(locale); subject.Collation = value; var result = subject.Collation; result.Should().BeSameAs(value); } [Theory] [ParameterAttributeData] public void CollectionNamespace_should_get_value( [Values("a", "b")] string collectionName) { var collectionNamespace = new CollectionNamespace(_collectionNamespace.DatabaseNamespace, collectionName); var subject = new FakeMapReduceOperation(collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var result = subject.CollectionNamespace; result.Should().BeSameAs(collectionNamespace); } [Fact] public void constructor_should_initialize_instance() { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); subject.CollectionNamespace.Should().BeSameAs(_collectionNamespace); subject.MapFunction.Should().BeSameAs(_mapFunction); subject.ReduceFunction.Should().BeSameAs(_reduceFunction); subject.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings); subject.Collation.Should().BeNull(); subject.Filter.Should().BeNull(); subject.FinalizeFunction.Should().BeNull(); #pragma warning disable 618 subject.JavaScriptMode.Should().NotHaveValue(); #pragma warning restore 618 subject.Limit.Should().NotHaveValue(); subject.MaxTime.Should().NotHaveValue(); subject.Scope.Should().BeNull(); subject.Sort.Should().BeNull(); subject.Verbose.Should().NotHaveValue(); } [Fact] public void constructor_should_throw_when_collectionNamespace_is_null() { var exception = Record.Exception(() => new FakeMapReduceOperation(null, _mapFunction, _reduceFunction, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("collectionNamespace"); } [Fact] public void constructor_should_throw_when_mapFunction_is_null() { var exception = Record.Exception(() => new FakeMapReduceOperation(_collectionNamespace, null, _reduceFunction, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("mapFunction"); } [Fact] public void constructor_should_throw_when_messageEncoderSettings_is_null() { var exception = Record.Exception(() => new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, null)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("messageEncoderSettings"); } [Fact] public void constructor_should_throw_when_reduceFunction_is_null() { var exception = Record.Exception(() => new FakeMapReduceOperation(_collectionNamespace, _mapFunction, null, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("reduceFunction"); } [Fact] public void CreateCommand_should_return_the_expected_result() { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Collation_is_provided( [Values(null, "en_US", "fr_CA")] string locale) { var collation = locale == null ? null : new Collation(locale); var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Collation = collation }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "collation", () => collation.ToBsonDocument(), collation != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Filter_is_provided( [Values(null, "{ x : 1 }", "{ x : 2 }")] string filterString) { var filter = filterString == null ? null : BsonDocument.Parse(filterString); var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Filter = filter }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "query", filter, filter != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_FinalizeFunction_is_provided( [Values(null, "a", "b")] string code) { var finalizeFunction = code == null ? null : new BsonJavaScript(code); var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { FinalizeFunction = finalizeFunction }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "finalize", finalizeFunction, finalizeFunction != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_JavaScriptMode_is_provided( [Values(null, false, true)] bool? javaScriptMode) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { #pragma warning disable 618 JavaScriptMode = javaScriptMode #pragma warning restore 618 }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "jsMode", () => javaScriptMode.Value, javaScriptMode.HasValue } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Limit_is_provided( [Values(null, 1L, 2L)] long? limit) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Limit = limit }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "limit", () => limit.Value, limit.HasValue } }; result.Should().Be(expectedResult); } [Theory] [InlineData(-10000, 0)] [InlineData(0, 0)] [InlineData(1, 1)] [InlineData(9999, 1)] [InlineData(10000, 1)] [InlineData(10001, 2)] public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long maxTimeTicks, int expectedMaxTimeMS) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "maxTimeMS", expectedMaxTimeMS } }; result.Should().Be(expectedResult); result["maxTimeMS"].BsonType.Should().Be(BsonType.Int32); } [Theory] [InlineData(42)] [InlineData(-1)] public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeoutMs) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { MaxTime = TimeSpan.FromTicks(10) }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); var result = subject.CreateCommand(operationContext, session, connectionDescription); result.Should().NotContain("maxTimeMS"); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Scope_is_provided( [Values(null, "{ x : 1 }", "{ x : 2 }")] string scopeString) { var scope = scopeString == null ? null : BsonDocument.Parse(scopeString); var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Scope = scope }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "scope", scope, scope != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Sort_is_provided( [Values(null, "{ x : 1 }", "{ x : -1 }")] string sortString) { var sort = sortString == null ? null : BsonDocument.Parse(sortString); var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Sort = sort }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "sort", sort, sort != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Verbose_is_provided( [Values(null, false, true)] bool? verbose) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings) { Verbose = verbose }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "mapReduce", _collectionNamespace.CollectionName }, { "map", _mapFunction }, { "reduce", _reduceFunction }, { "out", new BsonDocument("fake", 1) }, { "verbose", () => verbose.Value, verbose.HasValue } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void Filter_should_get_and_set_value( [Values(null, "{ x : 1 }", "{ x : 2 }")] string valueString) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = valueString == null ? null : BsonDocument.Parse(valueString); subject.Filter = value; var result = subject.Filter; result.Should().BeSameAs(value); } [Theory] [ParameterAttributeData] public void FinalizeFunction_should_get_and_set_value( [Values(null, "a", "b")] string code) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = code == null ? null : new BsonJavaScript(code); subject.FinalizeFunction = value; var result = subject.FinalizeFunction; result.Should().BeSameAs(value); } [Theory] [ParameterAttributeData] public void JavaScriptMode_should_get_and_set_value( [Values(null, false, true)] bool? value) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); #pragma warning disable 618 subject.JavaScriptMode = value; var result = subject.JavaScriptMode; #pragma warning restore 618 result.Should().Be(value); } [Theory] [ParameterAttributeData] public void Limit_should_get_and_set_value( [Values(null, 0L, 1L)] long? value) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); subject.Limit = value; var result = subject.Limit; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void MapFunction_should_get_value( [Values("a", "b")] string code) { var mapFunction = new BsonJavaScript(code); var subject = new FakeMapReduceOperation(_collectionNamespace, mapFunction, _reduceFunction, _messageEncoderSettings); var result = subject.MapFunction; result.Should().BeSameAs(mapFunction); } [Theory] [ParameterAttributeData] public void MaxTime_get_and_set_should_work( [Values(-10000, 0, 1, 10000, 99999)] long maxTimeTicks) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = TimeSpan.FromTicks(maxTimeTicks); subject.MaxTime = value; var result = subject.MaxTime; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_throw_when_value_is_invalid( [Values(-10001, -9999, -1)] long maxTimeTicks) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = TimeSpan.FromTicks(maxTimeTicks); var exception = Record.Exception(() => subject.MaxTime = value); var e = exception.Should().BeOfType<ArgumentOutOfRangeException>().Subject; e.ParamName.Should().Be("value"); } [Fact] public void MessageEncoderSettings_should_get_value() { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var result = subject.MessageEncoderSettings; result.Should().BeSameAs(_messageEncoderSettings); } [Fact] public void ReduceFunction_should_get_value() { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var result = subject.ReduceFunction; result.Should().BeSameAs(_reduceFunction); } [Theory] [ParameterAttributeData] public void Scope_should_get_and_set_value( [Values(null, "{ x : 1 }", "{ x : 2 }")] string valueString) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = valueString == null ? null : BsonDocument.Parse(valueString); subject.Scope = value; var result = subject.Scope; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void Sort_should_get_and_set_value( [Values(null, "{ x : 1 }", "{ x : -1 }")] string valueString) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var value = valueString == null ? null : BsonDocument.Parse(valueString); subject.Sort = value; var result = subject.Sort; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void Verbose_should_get_and_set_value( [Values(null, false, true)] bool? value) { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); subject.Verbose = value; var result = subject.Verbose; result.Should().Be(value); } // nested types #pragma warning disable CS0618 // Type or member is obsolete
MapReduceOperationBaseTests
csharp
MassTransit__MassTransit
tests/MassTransit.AmazonSqsTransport.Tests/MultiBus_Specs.cs
{ "start": 641, "end": 1114 }
public class ____ : IEntityNameFormatter { readonly string _prefix; public BusEnvironmentNameFormatter(string server) { _prefix = $"{server}-topic-"; } public string FormatEntityName<T>() { Console.WriteLine($"NameFormatter {_prefix}{typeof(T).Name}"); return _prefix + typeof(T).Name; } }
BusEnvironmentNameFormatter
csharp
dotnet__machinelearning
test/Microsoft.ML.TestFramework/Attributes/LightGBMTheoryAttribute.cs
{ "start": 457, "end": 852 }
public sealed class ____ : EnvironmentSpecificTheoryAttribute { public LightGBMTheoryAttribute() : base("LightGBM is 64-bit only") { } /// <inheritdoc /> protected override bool IsEnvironmentSupported() { return Environment.Is64BitProcess && NativeLibrary.NativeLibraryExists("lib_lightgbm"); } } }
LightGBMTheoryAttribute
csharp
dotnet__aspnetcore
src/SignalR/common/SignalR.Common/src/Protocol/CloseMessage.cs
{ "start": 1055, "end": 1423 }
class ____ an optional error message and <see cref="AllowReconnect"/> set to <see langword="false"/>. /// </summary> /// <param name="error">An optional error message.</param> public CloseMessage(string? error) : this(error, allowReconnect: false) { } /// <summary> /// Initializes a new instance of the <see cref="CloseMessage"/>
with
csharp
dotnetcore__Util
test/Util.TestShare/Dtos/ProductDto.cs
{ "start": 245, "end": 2121 }
public class ____ : DtoBase { /// <summary> /// 产品参数 /// </summary> public ProductDto() { TestProperty2 = new ProductItem(); TestProperties = new List<ProductItem2>(); } /// <summary> /// 产品编码 ///</summary> [Description( "产品编码" )] [MaxLength( 50 )] public string Code { get; set; } /// <summary> /// 产品名称 ///</summary> [Description( "产品名称" )] [MaxLength( 500 )] public string Name { get; set; } /// <summary> /// 价格 ///</summary> [Description( "价格" )] public decimal Price { get; set; } /// <summary> /// 描述 ///</summary> [Description( "描述" )] public string Description { get; set; } /// <summary> /// 启用 ///</summary> [Description( "启用" )] public bool Enabled { get; set; } /// <summary> /// 创建时间 ///</summary> [Description( "创建时间" )] public DateTime? CreationTime { get; set; } /// <summary> /// 创建人 ///</summary> [Description( "创建人" )] public Guid? CreatorId { get; set; } /// <summary> /// 最后修改时间 ///</summary> [Description( "最后修改时间" )] public DateTime? LastModificationTime { get; set; } /// <summary> /// 最后修改人 ///</summary> [Description( "最后修改人" )] public Guid? LastModifierId { get; set; } /// <summary> /// 是否删除 ///</summary> [Description( "是否删除" )] public bool IsDeleted { get; set; } /// <summary> /// 版本号 ///</summary> [Description( "版本号" )] public byte[] Version { get; set; } /// <summary> /// 简单扩展属性 /// </summary> public string TestProperty1 { get; set; } /// <summary> /// 对象扩展属性 /// </summary> public ProductItem TestProperty2 { get; set; } /// <summary> /// 对象集合扩展属性 /// </summary> public List<ProductItem2> TestProperties { get; set; } }
ProductDto
csharp
duplicati__duplicati
ReleaseBuilder/Build/Command.cs
{ "start": 18574, "end": 20416 }
record ____( PackageTarget[] Targets, DirectoryInfo BuildPath, FileInfo SolutionFile, bool GitStashPush, ReleaseChannel Channel, string? Version, string? Date, bool KeepBuilds, bool CompileOnly, bool DisableAuthenticode, bool DisableSignCode, string Password, string SignkeyPin, bool DisableDockerPush, string MacOSAppName, string DockerRepo, FileInfo ChangelogNewsFile, bool DisableNotarizeSigning, bool DisableGpgSigning, bool DisableS3Upload, bool DisableGithubUpload, bool DisableUpdateServerReload, bool DisableDiscourseAnnounce, bool UseHostedBuilds, bool ResumeFromUpload, bool PropagateRelease, bool DisableCleanSource, bool AllowAssemblyMismatch ); static async Task DoBuild(CommandInput input) { if (input.ResumeFromUpload) input = input with { KeepBuilds = true }; Console.WriteLine($"Building {input.Channel} release ..."); var configuration = Configuration.Create(input.Channel); var buildTargets = input.Targets; if (!buildTargets.Any()) buildTargets = Program.SupportedPackageTargets.ToArray(); if (!input.SolutionFile.Exists) throw new FileNotFoundException($"Solution file not found: {input.SolutionFile.FullName}"); // This could be fixed, so we will throw an exception if the build is not possible if (buildTargets.Any(x => x.Package == PackageType.MSI) && !configuration.IsMSIBuildPossible() && !input.CompileOnly) throw new Exception("WiX toolset not configured, cannot build MSI files"); // This will be fixed in the future, but requires a new http-
CommandInput
csharp
MassTransit__MassTransit
tests/MassTransit.Azure.ServiceBus.Core.Tests/Container_Specs.cs
{ "start": 279, "end": 2539 }
public class ____ : AzureServiceBusTestFixture { [Test] public async Task Should_work_as_expected() { Task<ConsumeContext<TestStarted>> started = await ConnectPublishHandler<TestStarted>(); Task<ConsumeContext<TestUpdated>> updated = await ConnectPublishHandler<TestUpdated>(); var correlationId = NewId.NextGuid(); await InputQueueSendEndpoint.Send(new StartTest { CorrelationId = correlationId, TestKey = "Unique" }, x => { x.SetSessionId(correlationId.ToString()); }); await started; await InputQueueSendEndpoint.Send(new UpdateTest { TestId = correlationId, TestKey = "Unique" }, x => { x.SetSessionId(correlationId.ToString()); }); await updated; } readonly IServiceProvider _provider; public Using_the_container_integration() : base("saga_input_queue_session") { _provider = new ServiceCollection() .AddMassTransit(ConfigureRegistration) .AddScoped<PublishTestStartedActivity>().BuildServiceProvider(); } protected void ConfigureRegistration(IBusRegistrationConfigurator configurator) { configurator.AddSagaStateMachine<TestStateMachineSaga, TestInstance>() .MessageSessionRepository(); configurator.AddBus(provider => BusControl); } protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator) { configurator.RequiresSession = true; configurator.EnablePartitioning = true; configurator.UseInMemoryOutbox(); configurator.ConfigureSaga<TestInstance>(_provider.GetRequiredService<IBusRegistrationContext>()); } }
Using_the_container_integration
csharp
dotnet__extensions
test/Shared/JsonSchemaExporter/TestTypes.cs
{ "start": 48460, "end": 48947 }
public class ____ { public PocoWithPolymorphism PolymorphicValue { get; set; } = new PocoWithPolymorphism.DerivedPocoNoDiscriminator { DerivedValue = "derived" }; public PocoWithPolymorphism.DerivedPocoNoDiscriminator DerivedValue1 { get; set; } = new() { DerivedValue = "derived" }; public PocoWithPolymorphism.DerivedPocoStringDiscriminator DerivedValue2 { get; set; } = new() { DerivedValue = "derived" }; }
PocoCombiningPolymorphicTypeAndDerivedTypes
csharp
dotnet__aspnetcore
src/Components/test/testassets/BasicTestApp/ServerReliability/JSInterop.cs
{ "start": 209, "end": 588 }
public class ____ { [JSInvokable] public static DotNetObjectReference<ImportantInformation> CreateImportant() { return DotNetObjectReference.Create(new ImportantInformation()); } [JSInvokable] public static string ReceiveTrivial(DotNetObjectReference<TrivialInformation> information) { return information.Value.Message; } }
JSInterop
csharp
dotnet__efcore
test/EFCore.InMemory.FunctionalTests/Query/NorthwindIncludeNoTrackingQueryInMemoryTest.cs
{ "start": 187, "end": 659 }
public class ____(NorthwindQueryInMemoryFixture<NoopModelCustomizer> fixture) : NorthwindIncludeNoTrackingQueryTestBase<NorthwindQueryInMemoryFixture<NoopModelCustomizer>>(fixture) { // Right join not supported in InMemory public override Task Include_collection_with_right_join_clause_with_filter(bool async) => AssertTranslationFailed(() => base.Include_collection_with_right_join_clause_with_filter(async)); }
NorthwindIncludeNoTrackingQueryInMemoryTest
csharp
ShareX__ShareX
ShareX/Forms/QRCodeForm.Designer.cs
{ "start": 24, "end": 8262 }
partial class ____ { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QRCodeForm)); this.txtText = new System.Windows.Forms.TextBox(); this.lblQRCodeSizeHint = new System.Windows.Forms.Label(); this.lblQRCodeSize = new System.Windows.Forms.Label(); this.nudQRCodeSize = new System.Windows.Forms.NumericUpDown(); this.pbQRCode = new ShareX.HelpersLib.MyPictureBox(); this.lblQRCode = new System.Windows.Forms.Label(); this.lblText = new System.Windows.Forms.Label(); this.btnCopyImage = new System.Windows.Forms.Button(); this.btnSaveImage = new System.Windows.Forms.Button(); this.btnUploadImage = new System.Windows.Forms.Button(); this.btnScanScreen = new System.Windows.Forms.Button(); this.btnScanRegion = new System.Windows.Forms.Button(); this.btnScanImageFile = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.nudQRCodeSize)).BeginInit(); this.SuspendLayout(); // // txtText // resources.ApplyResources(this.txtText, "txtText"); this.txtText.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtText.Name = "txtText"; this.txtText.TextChanged += new System.EventHandler(this.txtText_TextChanged); // // lblQRCodeSizeHint // resources.ApplyResources(this.lblQRCodeSizeHint, "lblQRCodeSizeHint"); this.lblQRCodeSizeHint.Name = "lblQRCodeSizeHint"; // // lblQRCodeSize // resources.ApplyResources(this.lblQRCodeSize, "lblQRCodeSize"); this.lblQRCodeSize.Name = "lblQRCodeSize"; // // nudQRCodeSize // this.nudQRCodeSize.Increment = new decimal(new int[] { 64, 0, 0, 0}); resources.ApplyResources(this.nudQRCodeSize, "nudQRCodeSize"); this.nudQRCodeSize.Maximum = new decimal(new int[] { 2048, 0, 0, 0}); this.nudQRCodeSize.Name = "nudQRCodeSize"; this.nudQRCodeSize.ValueChanged += new System.EventHandler(this.nudQRCodeSize_ValueChanged); // // pbQRCode // resources.ApplyResources(this.pbQRCode, "pbQRCode"); this.pbQRCode.BackColor = System.Drawing.SystemColors.Window; this.pbQRCode.FullscreenOnClick = true; this.pbQRCode.Name = "pbQRCode"; this.pbQRCode.PictureBoxBackColor = System.Drawing.SystemColors.Window; // // lblQRCode // resources.ApplyResources(this.lblQRCode, "lblQRCode"); this.lblQRCode.Name = "lblQRCode"; // // lblText // resources.ApplyResources(this.lblText, "lblText"); this.lblText.Name = "lblText"; // // btnCopyImage // resources.ApplyResources(this.btnCopyImage, "btnCopyImage"); this.btnCopyImage.Name = "btnCopyImage"; this.btnCopyImage.UseVisualStyleBackColor = true; this.btnCopyImage.Click += new System.EventHandler(this.btnCopyImage_Click); // // btnSaveImage // resources.ApplyResources(this.btnSaveImage, "btnSaveImage"); this.btnSaveImage.Name = "btnSaveImage"; this.btnSaveImage.UseVisualStyleBackColor = true; this.btnSaveImage.Click += new System.EventHandler(this.btnSaveImage_Click); // // btnUploadImage // resources.ApplyResources(this.btnUploadImage, "btnUploadImage"); this.btnUploadImage.Name = "btnUploadImage"; this.btnUploadImage.UseVisualStyleBackColor = true; this.btnUploadImage.Click += new System.EventHandler(this.btnUploadImage_Click); // // btnScanScreen // resources.ApplyResources(this.btnScanScreen, "btnScanScreen"); this.btnScanScreen.Name = "btnScanScreen"; this.btnScanScreen.UseVisualStyleBackColor = true; this.btnScanScreen.Click += new System.EventHandler(this.btnScanScreen_Click); // // btnScanRegion // resources.ApplyResources(this.btnScanRegion, "btnScanRegion"); this.btnScanRegion.Name = "btnScanRegion"; this.btnScanRegion.UseVisualStyleBackColor = true; this.btnScanRegion.Click += new System.EventHandler(this.btnScanRegion_Click); // // btnScanImageFile // resources.ApplyResources(this.btnScanImageFile, "btnScanImageFile"); this.btnScanImageFile.Name = "btnScanImageFile"; this.btnScanImageFile.UseVisualStyleBackColor = true; this.btnScanImageFile.Click += new System.EventHandler(this.btnScanImageFile_Click); // // QRCodeForm // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.btnScanImageFile); this.Controls.Add(this.btnScanRegion); this.Controls.Add(this.btnScanScreen); this.Controls.Add(this.btnUploadImage); this.Controls.Add(this.btnSaveImage); this.Controls.Add(this.btnCopyImage); this.Controls.Add(this.lblText); this.Controls.Add(this.lblQRCode); this.Controls.Add(this.pbQRCode); this.Controls.Add(this.lblQRCodeSizeHint); this.Controls.Add(this.lblQRCodeSize); this.Controls.Add(this.nudQRCodeSize); this.Controls.Add(this.txtText); this.Name = "QRCodeForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Shown += new System.EventHandler(this.QRCodeForm_Shown); this.Resize += new System.EventHandler(this.QRCodeForm_Resize); ((System.ComponentModel.ISupportInitialize)(this.nudQRCodeSize)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtText; private System.Windows.Forms.NumericUpDown nudQRCodeSize; private HelpersLib.MyPictureBox pbQRCode; private System.Windows.Forms.Label lblQRCodeSize; private System.Windows.Forms.Label lblQRCodeSizeHint; private System.Windows.Forms.Label lblQRCode; private System.Windows.Forms.Label lblText; private System.Windows.Forms.Button btnCopyImage; private System.Windows.Forms.Button btnSaveImage; private System.Windows.Forms.Button btnUploadImage; private System.Windows.Forms.Button btnScanScreen; private System.Windows.Forms.Button btnScanRegion; private System.Windows.Forms.Button btnScanImageFile; } }
QRCodeForm
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/Shared/ModelWithFieldsOfDifferentAndNullableTypesFactory.cs
{ "start": 45, "end": 688 }
public class ____ : ModelFactoryBase<ModelWithFieldsOfDifferentAndNullableTypes> { public static ModelWithFieldsOfDifferentAndNullableTypesFactory Instance = new(); public override void AssertIsEqual( ModelWithFieldsOfDifferentAndNullableTypes actual, ModelWithFieldsOfDifferentAndNullableTypes expected) { ModelWithFieldsOfDifferentAndNullableTypes.AssertIsEqual(actual, expected); } public override ModelWithFieldsOfDifferentAndNullableTypes CreateInstance(int i) { return ModelWithFieldsOfDifferentAndNullableTypes.CreateConstant(i); } }
ModelWithFieldsOfDifferentAndNullableTypesFactory
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Webhooks/IWebhookSubscriptionManager.cs
{ "start": 109, "end": 5259 }
public interface ____ { /// <summary> /// Returns subscription for given id. /// </summary> /// <param name="id">Unique identifier of <see cref="WebhookSubscriptionInfo"/></param> Task<WebhookSubscription> GetAsync(Guid id); /// <summary> /// Returns subscription for given id. /// </summary> /// <param name="id">Unique identifier of <see cref="WebhookSubscriptionInfo"/></param> WebhookSubscription Get(Guid id); /// <summary> /// Returns all subscriptions of tenant /// </summary> /// <param name="tenantId"> /// Target tenant id. /// </param> Task<List<WebhookSubscription>> GetAllSubscriptionsAsync(int? tenantId); /// <summary> /// Returns all subscriptions of tenant /// </summary> /// <param name="tenantId"> /// Target tenant id. /// </param> List<WebhookSubscription> GetAllSubscriptions(int? tenantId); /// <summary> /// Returns all subscriptions for given webhook. /// </summary> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> /// <param name="tenantId"> /// Target tenant id. /// </param> Task<List<WebhookSubscription>> GetAllSubscriptionsIfFeaturesGrantedAsync(int? tenantId, string webhookName); /// <summary> /// Returns all subscriptions for given webhook. /// </summary> /// <param name="tenantId"> /// Target tenant id. /// </param> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> List<WebhookSubscription> GetAllSubscriptionsIfFeaturesGranted(int? tenantId, string webhookName); /// <summary> /// Returns all subscriptions of tenant /// </summary> /// <returns></returns> Task<List<WebhookSubscription>> GetAllSubscriptionsOfTenantsAsync(int?[] tenantIds); /// <summary> /// Returns all subscriptions of tenant /// </summary> /// <param name="tenantIds"> /// Target tenant id(s). /// </param> List<WebhookSubscription> GetAllSubscriptionsOfTenants(int?[] tenantIds); /// <summary> /// Returns all subscriptions for given webhook. /// </summary> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> /// <param name="tenantIds"> /// Target tenant id(s). /// </param> Task<List<WebhookSubscription>> GetAllSubscriptionsOfTenantsIfFeaturesGrantedAsync(int?[] tenantIds, string webhookName); /// <summary> /// Returns all subscriptions for given webhook. /// </summary> /// <param name="tenantIds"> /// Target tenant id(s). /// </param> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> List<WebhookSubscription> GetAllSubscriptionsOfTenantsIfFeaturesGranted(int?[] tenantIds, string webhookName); /// <summary> /// Checks if tenant subscribed for a webhook. (Checks if webhook features are granted) /// </summary> /// <param name="tenantId"> /// Target tenant id(s). /// </param> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> Task<bool> IsSubscribedAsync(int? tenantId, string webhookName); /// <summary> /// Checks if tenant subscribed for a webhook. (Checks if webhook features are granted) /// </summary> /// <param name="tenantId"> /// Target tenant id(s). /// </param> /// <param name="webhookName"><see cref="WebhookDefinition.Name"/></param> bool IsSubscribed(int? tenantId, string webhookName); /// <summary> /// If id is the default(Guid) adds new subscription, else updates current one. (Checks if webhook features are granted) /// </summary> Task AddOrUpdateSubscriptionAsync(WebhookSubscription webhookSubscription); /// <summary> /// If id is the default(Guid) adds it, else updates it. (Checks if webhook features are granted) /// </summary> void AddOrUpdateSubscription(WebhookSubscription webhookSubscription); /// <summary> /// Activates/Deactivates given webhook subscription /// </summary> /// <param name="id">unique identifier of <see cref="WebhookSubscriptionInfo"/></param> /// <param name="active">IsActive</param> Task ActivateWebhookSubscriptionAsync(Guid id, bool active); /// <summary> /// Delete given webhook subscription. /// </summary> /// <param name="id">unique identifier of <see cref="WebhookSubscriptionInfo"/></param> Task DeleteSubscriptionAsync(Guid id); /// <summary> /// Delete given webhook subscription. /// </summary> /// <param name="id">unique identifier of <see cref="WebhookSubscriptionInfo"/></param> void DeleteSubscription(Guid id); } }
IWebhookSubscriptionManager
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.Layout/GridSplitter/GridSplitter.Options.cs
{ "start": 498, "end": 8707 }
public partial class ____ { /// <summary> /// Identifies the <see cref="Element"/> dependency property. /// </summary> public static readonly DependencyProperty ElementProperty = DependencyProperty.Register( nameof(Element), typeof(UIElement), typeof(GridSplitter), new PropertyMetadata(default(UIElement), OnElementPropertyChanged)); /// <summary> /// Identifies the <see cref="ResizeDirection"/> dependency property. /// </summary> public static readonly DependencyProperty ResizeDirectionProperty = DependencyProperty.Register( nameof(ResizeDirection), typeof(GridResizeDirection), typeof(GridSplitter), new PropertyMetadata(GridResizeDirection.Auto)); /// <summary> /// Identifies the <see cref="ResizeBehavior"/> dependency property. /// </summary> public static readonly DependencyProperty ResizeBehaviorProperty = DependencyProperty.Register( nameof(ResizeBehavior), typeof(GridResizeBehavior), typeof(GridSplitter), new PropertyMetadata(GridResizeBehavior.BasedOnAlignment)); /// <summary> /// Identifies the <see cref="GripperForeground"/> dependency property. /// </summary> public static readonly DependencyProperty GripperForegroundProperty = DependencyProperty.Register( nameof(GripperForeground), typeof(Brush), typeof(GridSplitter), new PropertyMetadata(default(Brush), OnGripperForegroundPropertyChanged)); /// <summary> /// Identifies the <see cref="ParentLevel"/> dependency property. /// </summary> public static readonly DependencyProperty ParentLevelProperty = DependencyProperty.Register( nameof(ParentLevel), typeof(int), typeof(GridSplitter), new PropertyMetadata(default(int))); /// <summary> /// Identifies the <see cref="GripperCursor"/> dependency property. /// </summary> public static readonly DependencyProperty GripperCursorProperty = DependencyProperty.RegisterAttached( nameof(GripperCursor), typeof(CoreCursorType?), typeof(GridSplitter), new PropertyMetadata(GripperCursorType.Default, OnGripperCursorPropertyChanged)); /// <summary> /// Identifies the <see cref="GripperCustomCursorResource"/> dependency property. /// </summary> public static readonly DependencyProperty GripperCustomCursorResourceProperty = DependencyProperty.RegisterAttached( nameof(GripperCustomCursorResource), typeof(uint), typeof(GridSplitter), new PropertyMetadata(GripperCustomCursorDefaultResource, GripperCustomCursorResourcePropertyChanged)); /// <summary> /// Identifies the <see cref="CursorBehavior"/> dependency property. /// </summary> public static readonly DependencyProperty CursorBehaviorProperty = DependencyProperty.RegisterAttached( nameof(CursorBehavior), typeof(SplitterCursorBehavior), typeof(GridSplitter), new PropertyMetadata(SplitterCursorBehavior.ChangeOnSplitterHover, CursorBehaviorPropertyChanged)); /// <summary> /// Gets or sets the visual content of this Grid Splitter /// </summary> public UIElement Element { get { return (UIElement)GetValue(ElementProperty); } set { SetValue(ElementProperty, value); } } /// <summary> /// Gets or sets whether the Splitter resizes the Columns, Rows, or Both. /// </summary> public GridResizeDirection ResizeDirection { get { return (GridResizeDirection)GetValue(ResizeDirectionProperty); } set { SetValue(ResizeDirectionProperty, value); } } /// <summary> /// Gets or sets which Columns or Rows the Splitter resizes. /// </summary> public GridResizeBehavior ResizeBehavior { get { return (GridResizeBehavior)GetValue(ResizeBehaviorProperty); } set { SetValue(ResizeBehaviorProperty, value); } } /// <summary> /// Gets or sets the foreground color of grid splitter grip /// </summary> public Brush GripperForeground { get { return (Brush)GetValue(GripperForegroundProperty); } set { SetValue(GripperForegroundProperty, value); } } /// <summary> /// Gets or sets the level of the parent grid to resize /// </summary> public int ParentLevel { get { return (int)GetValue(ParentLevelProperty); } set { SetValue(ParentLevelProperty, value); } } /// <summary> /// Gets or sets the gripper Cursor type /// </summary> public GripperCursorType GripperCursor { get { return (GripperCursorType)GetValue(GripperCursorProperty); } set { SetValue(GripperCursorProperty, value); } } /// <summary> /// Gets or sets the gripper Custom Cursor resource number /// </summary> public int GripperCustomCursorResource { get { return (int)GetValue(GripperCustomCursorResourceProperty); } set { SetValue(GripperCustomCursorResourceProperty, value); } } /// <summary> /// Gets or sets splitter cursor on hover behavior /// </summary> public SplitterCursorBehavior CursorBehavior { get { return (SplitterCursorBehavior)GetValue(CursorBehaviorProperty); } set { SetValue(CursorBehaviorProperty, value); } } private static void OnGripperForegroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var gridSplitter = (GridSplitter)d; if (gridSplitter._gripperDisplay == null) { return; } gridSplitter._gripperDisplay.Foreground = gridSplitter.GripperForeground; } private static void OnGripperCursorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var gridSplitter = (GridSplitter)d; if (gridSplitter._hoverWrapper == null) { return; } gridSplitter._hoverWrapper.GripperCursor = gridSplitter.GripperCursor; } private static void GripperCustomCursorResourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var gridSplitter = (GridSplitter)d; if (gridSplitter._hoverWrapper == null) { return; } gridSplitter._hoverWrapper.GripperCustomCursorResource = gridSplitter.GripperCustomCursorResource; } private static void CursorBehaviorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var gridSplitter = (GridSplitter)d; gridSplitter._hoverWrapper?.UpdateHoverElement(gridSplitter.CursorBehavior == SplitterCursorBehavior.ChangeOnSplitterHover ? gridSplitter : gridSplitter.Element); } private static void OnElementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var gridSplitter = (GridSplitter)d; gridSplitter._hoverWrapper?.UpdateHoverElement(gridSplitter.CursorBehavior == SplitterCursorBehavior.ChangeOnSplitterHover ? gridSplitter : gridSplitter.Element); } } }
GridSplitter
csharp
dotnet__orleans
test/TesterInternal/StorageTests/TestDataSets/GrainTypeGenerator.cs
{ "start": 1224, "end": 2964 }
public class ____<T>: Grain, ITestGrainGenericWithStringKey<T> { } private static Dictionary<Type, Func<Type, Type, Type>> GrainTypeSwitch { get; } = new Dictionary<Type, Func<Type, Type, Type>> { [typeof(Guid)] = (grainType, stateType) => { if(grainType == typeof(NotApplicable)) { return typeof(TestGrainWithGuidKey); } return typeof(TestGrainGenericWithGuidKey<double>); }, [typeof(long)] = (grainType, stateType) => { if(grainType == typeof(NotApplicable)) { return typeof(TestGrainWithIntegerKey); } return typeof(TestGrainGenericWithIntegerKey<double>); }, [typeof(string)] = (grainType, stateType) => { if(grainType == typeof(NotApplicable)) { return typeof(TestGrainWithStringKey); } return typeof(TestGrainGenericWithStringKey<double>); } }; public static string GetGrainType<TGrainKey>() { return GetGrainType<TGrainKey, NotApplicable>(); } // Orleans.Storage.AdoNetStorageProvider cannot be resolved, because the containing assembly is not referenced since not needed. #pragma warning disable 1574 /// <summary> /// Returns a grain type name. /// </summary> /// <typeparam name="TGrainKey">Used to choose the key type interface.</typeparam> /// <typeparam name="TGrain">Used to choose the type of grain.</typeparam> /// <returns>The
TestGrainGenericWithStringKey
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/UniTask.Delay.cs
{ "start": 586, "end": 9549 }
public partial struct ____ { public static YieldAwaitable Yield() { // optimized for single continuation return new YieldAwaitable(PlayerLoopTiming.Update); } public static YieldAwaitable Yield(PlayerLoopTiming timing) { // optimized for single continuation return new YieldAwaitable(timing); } public static UniTask Yield(CancellationToken cancellationToken, bool cancelImmediately = false) { return new UniTask(YieldPromise.Create(PlayerLoopTiming.Update, cancellationToken, cancelImmediately, out var token), token); } public static UniTask Yield(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately = false) { return new UniTask(YieldPromise.Create(timing, cancellationToken, cancelImmediately, out var token), token); } /// <summary> /// Similar as UniTask.Yield but guaranteed run on next frame. /// </summary> public static UniTask NextFrame() { return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, CancellationToken.None, false, out var token), token); } /// <summary> /// Similar as UniTask.Yield but guaranteed run on next frame. /// </summary> public static UniTask NextFrame(PlayerLoopTiming timing) { return new UniTask(NextFramePromise.Create(timing, CancellationToken.None, false, out var token), token); } /// <summary> /// Similar as UniTask.Yield but guaranteed run on next frame. /// </summary> public static UniTask NextFrame(CancellationToken cancellationToken, bool cancelImmediately = false) { return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, cancellationToken, cancelImmediately, out var token), token); } /// <summary> /// Similar as UniTask.Yield but guaranteed run on next frame. /// </summary> public static UniTask NextFrame(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately = false) { return new UniTask(NextFramePromise.Create(timing, cancellationToken, cancelImmediately, out var token), token); } #if UNITY_2023_1_OR_NEWER public static async UniTask WaitForEndOfFrame(CancellationToken cancellationToken = default) { await Awaitable.EndOfFrameAsync(cancellationToken); } #else [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")] public static YieldAwaitable WaitForEndOfFrame() { return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate); } [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")] public static UniTask WaitForEndOfFrame(CancellationToken cancellationToken, bool cancelImmediately = false) { return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate, cancellationToken, cancelImmediately); } #endif public static UniTask WaitForEndOfFrame(MonoBehaviour coroutineRunner) { var source = WaitForEndOfFramePromise.Create(coroutineRunner, CancellationToken.None, false, out var token); return new UniTask(source, token); } public static UniTask WaitForEndOfFrame(MonoBehaviour coroutineRunner, CancellationToken cancellationToken, bool cancelImmediately = false) { var source = WaitForEndOfFramePromise.Create(coroutineRunner, cancellationToken, cancelImmediately, out var token); return new UniTask(source, token); } /// <summary> /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate). /// </summary> public static YieldAwaitable WaitForFixedUpdate() { // use LastFixedUpdate instead of FixedUpdate // https://github.com/Cysharp/UniTask/issues/377 return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate); } /// <summary> /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken). /// </summary> public static UniTask WaitForFixedUpdate(CancellationToken cancellationToken, bool cancelImmediately = false) { return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken, cancelImmediately); } public static UniTask WaitForSeconds(float duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { return Delay(Mathf.RoundToInt(1000 * duration), ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); } public static UniTask WaitForSeconds(int duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { return Delay(1000 * duration, ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); } public static UniTask DelayFrame(int delayFrameCount, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { if (delayFrameCount < 0) { throw new ArgumentOutOfRangeException("Delay does not allow minus delayFrameCount. delayFrameCount:" + delayFrameCount); } return new UniTask(DelayFramePromise.Create(delayFrameCount, delayTiming, cancellationToken, cancelImmediately, out var token), token); } public static UniTask Delay(int millisecondsDelay, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay); return Delay(delayTimeSpan, ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); } public static UniTask Delay(TimeSpan delayTimeSpan, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { var delayType = ignoreTimeScale ? DelayType.UnscaledDeltaTime : DelayType.DeltaTime; return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken, cancelImmediately); } public static UniTask Delay(int millisecondsDelay, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay); return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken, cancelImmediately); } public static UniTask Delay(TimeSpan delayTimeSpan, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) { if (delayTimeSpan < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("Delay does not allow minus delayTimeSpan. delayTimeSpan:" + delayTimeSpan); } #if UNITY_EDITOR // force use Realtime. if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying) { delayType = DelayType.Realtime; } #endif switch (delayType) { case DelayType.UnscaledDeltaTime: { return new UniTask(DelayIgnoreTimeScalePromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); } case DelayType.Realtime: { return new UniTask(DelayRealtimePromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); } case DelayType.DeltaTime: default: { return new UniTask(DelayPromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); } } }
UniTask
csharp
dotnet__extensions
src/Analyzers/Microsoft.Analyzers.Extra/CallAnalysis/LegacyCollection.cs
{ "start": 406, "end": 1312 }
internal sealed class ____ { private static readonly string[] _collectionTypes = new[] { "System.Collections.ArrayList", "System.Collections.Hashtable", "System.Collections.Queue", "System.Collections.Stack", "System.Collections.SortedList", "System.Collections.Specialized.HybridDictionary", "System.Collections.Specialized.ListDictionary", "System.Collections.Specialized.OrderedDictionary", }; public LegacyCollection(CallAnalyzer.Registrar reg) { reg.RegisterConstructors(_collectionTypes, HandleConstructor); static void HandleConstructor(OperationAnalysisContext context, IObjectCreationOperation op) { var diagnostic = Diagnostic.Create(DiagDescriptors.LegacyCollection, op.Syntax.GetLocation()); context.ReportDiagnostic(diagnostic); } } }
LegacyCollection
csharp
EventStore__EventStore
src/KurrentDB.Core/Messages/TcpClientMessageDto.cs
{ "start": 6138, "end": 6617 }
partial class ____ { public TransactionCommitCompleted(long transactionId, OperationResult result, string message, long firstEventNumber, long lastEventNumber, long preparePosition, long commitPosition) { TransactionId = transactionId; Result = result; if (message != null) Message = message; FirstEventNumber = firstEventNumber; LastEventNumber = lastEventNumber; PreparePosition = preparePosition; CommitPosition = commitPosition; } }
TransactionCommitCompleted
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/GossipService/NodeGossipServiceTests.cs
{ "start": 6649, "end": 7499 }
class ____ : IGossipSeedSource { public IAsyncResult BeginGetHostEndpoints(AsyncCallback requestCallback, object state) { throw new NotImplementedException(); } public EndPoint[] EndGetHostEndpoints(IAsyncResult asyncResult) { throw new NotImplementedException(); } } public when_retrieving_gossip_seed_sources_and_gossip_seed_source_throws() { _gossipSeedSource = new ThrowingGossipSeedSource(); } protected override Message[] Given() => new Message[] { new SystemMessage.SystemInit() }; protected override Message When() => new GossipMessage.RetrieveGossipSeedSources(); [Test] public void should_schedule_retry_retrieve_gossip_seed_sources() { ExpectMessages( TimerMessage.Schedule.Create(GossipServiceBase.DnsRetryTimeout, _bus, new GossipMessage.RetrieveGossipSeedSources())); } }
ThrowingGossipSeedSource
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.Testing/Statistics/FileSystemStatistics.cs
{ "start": 54, "end": 3677 }
internal sealed class ____ : IFileSystemStatistics { internal readonly CallStatistics<IDirectory> Directory; internal readonly PathStatistics<IDirectoryInfoFactory, IDirectoryInfo> DirectoryInfo; internal readonly PathStatistics<IDriveInfoFactory, IDriveInfo> DriveInfo; internal readonly CallStatistics<IFile> File; internal readonly PathStatistics<IFileInfoFactory, IFileInfo> FileInfo; internal readonly PathStatistics<IFileStreamFactory, FileSystemStream> FileStream; internal readonly PathStatistics<IFileSystemWatcherFactory, IFileSystemWatcher> FileSystemWatcher; internal readonly PathStatistics<IFileVersionInfoFactory, IFileVersionInfo> FileVersionInfo; internal readonly CallStatistics<IPath> Path; private readonly MockFileSystem _fileSystem; public FileSystemStatistics(MockFileSystem fileSystem) { _fileSystem = fileSystem; IStatisticsGate statisticsGate = fileSystem.Registration; Directory = new CallStatistics<IDirectory>( statisticsGate, nameof(IFileSystem.Directory)); DirectoryInfo = new PathStatistics<IDirectoryInfoFactory, IDirectoryInfo>( statisticsGate, fileSystem, nameof(IFileSystem.DirectoryInfo)); DriveInfo = new PathStatistics<IDriveInfoFactory, IDriveInfo>( statisticsGate, fileSystem, nameof(IFileSystem.DriveInfo)); File = new CallStatistics<IFile>( statisticsGate, nameof(IFileSystem.File)); FileInfo = new PathStatistics<IFileInfoFactory, IFileInfo>( statisticsGate, fileSystem, nameof(IFileSystem.FileInfo)); FileStream = new PathStatistics<IFileStreamFactory, FileSystemStream>( statisticsGate, fileSystem, nameof(IFileSystem.FileStream)); FileSystemWatcher = new PathStatistics<IFileSystemWatcherFactory, IFileSystemWatcher>( statisticsGate, fileSystem, nameof(IFileSystem.FileSystemWatcher)); FileVersionInfo = new PathStatistics<IFileVersionInfoFactory, IFileVersionInfo>( statisticsGate, fileSystem, nameof(IFileSystem.FileVersionInfo)); Path = new CallStatistics<IPath>( statisticsGate, nameof(IFileSystem.Path)); } #region IFileSystemStatistics Members /// <inheritdoc cref="IFileSystemStatistics.TotalCount" /> public int TotalCount => _fileSystem.Registration.TotalCount; /// <inheritdoc cref="IFileSystemStatistics.Directory" /> IStatistics<IDirectory> IFileSystemStatistics.Directory => Directory; /// <inheritdoc cref="IFileSystemStatistics.DirectoryInfo" /> IPathStatistics<IDirectoryInfoFactory, IDirectoryInfo> IFileSystemStatistics.DirectoryInfo => DirectoryInfo; /// <inheritdoc cref="IFileSystemStatistics.DriveInfo" /> IPathStatistics<IDriveInfoFactory, IDriveInfo> IFileSystemStatistics.DriveInfo => DriveInfo; /// <inheritdoc cref="IFileSystemStatistics.File" /> IStatistics<IFile> IFileSystemStatistics.File => File; /// <inheritdoc cref="IFileSystemStatistics.FileInfo" /> IPathStatistics<IFileInfoFactory, IFileInfo> IFileSystemStatistics.FileInfo => FileInfo; /// <inheritdoc cref="IFileSystemStatistics.FileStream" /> IPathStatistics<IFileStreamFactory, FileSystemStream> IFileSystemStatistics.FileStream => FileStream; /// <inheritdoc cref="IFileSystemStatistics.FileSystemWatcher" /> IPathStatistics<IFileSystemWatcherFactory, IFileSystemWatcher> IFileSystemStatistics.FileSystemWatcher => FileSystemWatcher; /// <inheritdoc cref="IFileSystemStatistics.FileSystemWatcher" /> IPathStatistics<IFileVersionInfoFactory, IFileVersionInfo> IFileSystemStatistics.FileVersionInfo => FileVersionInfo; /// <inheritdoc cref="IFileSystemStatistics.Path" /> IStatistics<IPath> IFileSystemStatistics.Path => Path; #endregion }
FileSystemStatistics
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Reverse.cs
{ "start": 950, "end": 2431 }
sealed class ____ : MoveNextSource, IUniTaskAsyncEnumerator<TSource> { readonly IUniTaskAsyncEnumerable<TSource> source; CancellationToken cancellationToken; TSource[] array; int index; public _Reverse(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken) { this.source = source; this.cancellationToken = cancellationToken; TaskTracker.TrackActiveTask(this, 3); } public TSource Current { get; private set; } // after consumed array, don't use await so allow async(not require UniTaskCompletionSourceCore). public async UniTask<bool> MoveNextAsync() { cancellationToken.ThrowIfCancellationRequested(); if (array == null) { array = await source.ToArrayAsync(cancellationToken); index = array.Length - 1; } if (index != -1) { Current = array[index]; --index; return true; } else { return false; } } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); return default; } } } }
_Reverse
csharp
dotnet__orleans
src/Orleans.Serialization.SystemTextJson/JsonCodecOptions.cs
{ "start": 143, "end": 1096 }
public class ____ { /// <summary> /// Gets or sets the <see cref="JsonSerializerOptions"/>. /// </summary> public JsonSerializerOptions SerializerOptions { get; set; } = new(); /// <summary> /// Gets or sets the <see cref="JsonReaderOptions"/>. /// </summary> public JsonReaderOptions ReaderOptions { get; set; } /// <summary> /// Gets or sets the <see cref="JsonWriterOptions"/>. /// </summary> public JsonWriterOptions WriterOptions { get; set; } /// <summary> /// Gets or sets a delegate used to determine if a type is supported by the JSON serializer for serialization and deserialization. /// </summary> public Func<Type, bool?> IsSerializableType { get; set; } /// <summary> /// Gets or sets a delegate used to determine if a type is supported by the JSON serializer for copying. /// </summary> public Func<Type, bool?> IsCopyableType { get; set; } }
JsonCodecOptions
csharp
AutoFixture__AutoFixture
Src/AutoFixture.NUnit2/Addins/Builders/AutoDataProvider.cs
{ "start": 296, "end": 2598 }
public class ____ : ITestCaseProvider2 { /// <summary> /// Determine whether any test cases are available for a parameterized method. /// </summary> /// <param name="method">A MethodInfo representing a parameterized test.</param> /// <returns>True if any cases are available, otherwise false.</returns> public bool HasTestCasesFor(MethodInfo method) { return Reflect.HasAttribute(method, Constants.AutoDataAttribute, false); } /// <summary> /// Return an IEnumerable providing test cases for use in /// running a parameterized test. /// </summary> /// <param name="method"></param> /// <returns></returns> public IEnumerable GetTestCasesFor(MethodInfo method) { return this.GetTestCasesFor(method, null); } /// <summary> /// Determine whether any test cases are available for a parameterized method. /// </summary> /// <param name="method">A MethodInfo representing a parameterized test.</param> /// <param name="suite">A Suite representing a NUnit TestSuite.</param> /// <returns>True if any cases are available, otherwise false.</returns> public bool HasTestCasesFor(MethodInfo method, Test suite) { return this.HasTestCasesFor(method); } /// <summary> /// Return an IEnumerable providing test cases for use in /// running a parameterized test. /// </summary> /// <param name="method"></param> /// <param name="suite"></param> /// <returns></returns> public IEnumerable GetTestCasesFor(MethodInfo method, Test suite) { ArrayList parameterList = new ArrayList(); var attributes = Reflect.GetAttributes(method, Constants.AutoDataAttribute, false); foreach (DataAttribute attr in attributes) { foreach (var arguments in attr.GetData(method)) { ParameterSet parms = new ParameterSet(); parms.Arguments = arguments; parameterList.Add(parms); } } return parameterList; } } }
AutoDataProvider
csharp
nunit__nunit
src/NUnitFramework/framework/Constraints/TypeConstraint.cs
{ "start": 298, "end": 2436 }
public abstract class ____ : Constraint { #pragma warning disable IDE1006 /// <summary> /// The expected Type used by the constraint /// </summary> // ReSharper disable once InconsistentNaming // Disregarding naming convention for back-compat protected Type expectedType; /// <summary> /// The type of the actual argument to which the constraint was applied /// </summary> // ReSharper disable once InconsistentNaming // Disregarding naming convention for back-compat protected Type? actualType; #pragma warning restore IDE1006 /// <summary> /// Construct a TypeConstraint for a given Type /// </summary> /// <param name="type">The expected type for the constraint</param> /// <param name="descriptionPrefix">Prefix used in forming the constraint description</param> protected TypeConstraint(Type type, string descriptionPrefix) : base(type) { expectedType = type; Description = descriptionPrefix + MsgUtils.FormatValue(expectedType); } /// <inheritdoc/> public override string Description { get; } /// <summary> /// Applies the constraint to an actual value, returning a ConstraintResult. /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>A ConstraintResult</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { actualType = actual?.GetType(); if (actual is Exception) return new ConstraintResult(this, actual, Matches(actual)); return new ConstraintResult(this, actualType, Matches(actual)); } /// <summary> /// Apply the constraint to an actual value, returning true if it succeeds /// </summary> /// <param name="actual">The actual argument</param> /// <returns>True if the constraint succeeds, otherwise false.</returns> protected abstract bool Matches(object? actual); } }
TypeConstraint
csharp
nunit__nunit
src/NUnitFramework/testdata/CancelAfterFixture.cs
{ "start": 1124, "end": 1518 }
public sealed class ____ : CancelAfterFixture { [TearDown] public async Task TearDown2() { await Task.Delay(1000, TestContext.CurrentContext.CancellationToken).ConfigureAwait(false); } [Test, CancelAfter(50)] public void Test() { } } [TestFixture, CancelAfter(50)]
CancelAfterFixtureWithTimeoutInTearDown
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet/Attributes/ExceptionDiagnoserConfig.cs
{ "start": 141, "end": 616 }
public class ____ { /// <param name="displayExceptionsIfZeroValue">Determines whether the Exceptions column is displayed when its value is not calculated. True by default.</param> [PublicAPI] public ExceptionDiagnoserConfig(bool displayExceptionsIfZeroValue = true) { DisplayExceptionsIfZeroValue = displayExceptionsIfZeroValue; } public bool DisplayExceptionsIfZeroValue { get; } } }
ExceptionDiagnoserConfig
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Grid/VerticalAlign.cs
{ "start": 66, "end": 140 }
public enum ____ { Default, Start, Center, End }
VerticalAlign
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Core/Misc/IReadOnlyDictionaryExtensions.cs
{ "start": 671, "end": 2090 }
internal static class ____ { public static bool IsEquivalentTo<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> x, IReadOnlyDictionary<TKey, TValue> y, Func<TValue, TValue, bool> equals) { if (object.ReferenceEquals(x, y)) { return true; } if (object.ReferenceEquals(x, null) || object.ReferenceEquals(y, null)) { return false; } if (x.Count != y.Count) { return false; } foreach (var keyValuePair in x) { var key = keyValuePair.Key; var xValue = keyValuePair.Value; if (!y.TryGetValue(key, out var yValue) || !equals(xValue, yValue)) { return false; } } return true; } public static TValueResult GetValueOrDefault<TValueResult, TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) where TValue : class { if (dictionary == null) { return default; } if (dictionary.TryGetValue(key, out TValue value) && value is TValueResult result) { return result; } return default; } } }
IReadOnlyDictionaryExtensions
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/IService.cs
{ "start": 1727, "end": 1783 }
public interface ____<T> { object Get(T request); }
IGet
csharp
PrismLibrary__Prism
src/Uno/Prism.Uno/Dialogs/DialogWindow.xaml.cs
{ "start": 208, "end": 970 }
public partial class ____ : ContentDialog, IDialogWindow { public DialogWindow() { this.InitializeComponent(); } public IDialogResult? Result { get; set; } event RoutedEventHandler IDialogWindow.Loaded { add => Loaded += value; remove => Loaded -= value; } event TypedEventHandler<ContentDialog, ContentDialogClosingEventArgs> IDialogWindow.Closing { add => Closing += value; remove => Closing -= value; } event TypedEventHandler<ContentDialog, ContentDialogClosedEventArgs> IDialogWindow.Closed { add => Closed += value; remove => Closed -= value; } } }
DialogWindow
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 1812981, "end": 1813314 }
public partial interface ____ : IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes, IArgumentRemoved { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes_ArgumentRemoved
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Core/ExitException.cs
{ "start": 42, "end": 212 }
public sealed class ____ : Exception { public ExitException() : base("") { } public ExitException(string message) : base(message) { } }
ExitException
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite/Dapper/SqlMapper.TypeDeserializerCache.cs
{ "start": 209, "end": 1749 }
private class ____ { private TypeDeserializerCache(Type type) { this.type = type; } private static readonly Hashtable byType = new Hashtable(); private readonly Type type; internal static void Purge(Type type) { lock (byType) { byType.Remove(type); } } internal static void Purge() { lock (byType) { byType.Clear(); } } internal static Func<IDataReader, object> GetReader(Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing) { var found = (TypeDeserializerCache)byType[type]; if (found == null) { lock (byType) { found = (TypeDeserializerCache)byType[type]; if (found == null) { byType[type] = found = new TypeDeserializerCache(type); } } } return found.GetReader(reader, startBound, length, returnNullIfFirstMissing); } private readonly Dictionary<DeserializerKey, Func<IDataReader, object>> readers = new Dictionary<DeserializerKey, Func<IDataReader, object>>();
TypeDeserializerCache
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs
{ "start": 10488, "end": 10692 }
public class ____ { public Bar4 Bar { get; set; } = new() { Id1 = "123" }; } [ObjectType("Bar")] [Node( IdField = nameof(Id1), NodeResolver = nameof(GetFoo))]
Foo4
csharp
icsharpcode__AvalonEdit
ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs
{ "start": 1994, "end": 7853 }
struct ____ { public int lfHeight; public int lfWidth; public int lfEscapement; public int lfOrientation; public int lfWeight; public byte lfItalic; public byte lfUnderline; public byte lfStrikeOut; public byte lfCharSet; public byte lfOutPrecision; public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string lfFaceName; } const int CPS_CANCEL = 0x4; const int NI_COMPOSITIONSTR = 0x15; const int GCS_COMPSTR = 0x0008; public const int WM_IME_COMPOSITION = 0x10F; public const int WM_IME_SETCONTEXT = 0x281; public const int WM_INPUTLANGCHANGE = 0x51; [DllImport("imm32.dll")] public static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC); [DllImport("imm32.dll")] internal static extern IntPtr ImmGetContext(IntPtr hWnd); [DllImport("imm32.dll")] internal static extern IntPtr ImmGetDefaultIMEWnd(IntPtr hWnd); [DllImport("imm32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC); [DllImport("imm32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ImmNotifyIME(IntPtr hIMC, int dwAction, int dwIndex, int dwValue = 0); [DllImport("imm32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ImmSetCompositionWindow(IntPtr hIMC, ref CompositionForm form); [DllImport("imm32.dll", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ImmSetCompositionFont(IntPtr hIMC, ref LOGFONT font); [DllImport("imm32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ImmGetCompositionFont(IntPtr hIMC, out LOGFONT font); [DllImport("msctf.dll")] static extern int TF_CreateThreadMgr(out ITfThreadMgr threadMgr); [ThreadStatic] static bool textFrameworkThreadMgrInitialized; [ThreadStatic] static ITfThreadMgr textFrameworkThreadMgr; public static ITfThreadMgr GetTextFrameworkThreadManager() { if (!textFrameworkThreadMgrInitialized) { textFrameworkThreadMgrInitialized = true; try { TF_CreateThreadMgr(out textFrameworkThreadMgr); } catch { // The call will fail if the current runtime doesn't have COM interop } } return textFrameworkThreadMgr; } public static bool NotifyIme(IntPtr hIMC) { return ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL); } public static bool SetCompositionWindow(HwndSource source, IntPtr hIMC, TextArea textArea) { if (textArea == null) throw new ArgumentNullException("textArea"); Rect textViewBounds = textArea.TextView.GetBounds(source); Rect characterBounds = textArea.TextView.GetCharacterBounds(textArea.Caret.Position, source); CompositionForm form = new CompositionForm(); form.dwStyle = 0x0020; form.ptCurrentPos.x = (int)Math.Max(characterBounds.Left, textViewBounds.Left); form.ptCurrentPos.y = (int)Math.Max(characterBounds.Top, textViewBounds.Top); form.rcArea.left = (int)textViewBounds.Left; form.rcArea.top = (int)textViewBounds.Top; form.rcArea.right = (int)textViewBounds.Right; form.rcArea.bottom = (int)textViewBounds.Bottom; return ImmSetCompositionWindow(hIMC, ref form); } public static bool SetCompositionFont(HwndSource source, IntPtr hIMC, TextArea textArea) { if (textArea == null) throw new ArgumentNullException("textArea"); LOGFONT lf = new LOGFONT(); Rect characterBounds = textArea.TextView.GetCharacterBounds(textArea.Caret.Position, source); lf.lfFaceName = textArea.FontFamily.Source; lf.lfHeight = (int)characterBounds.Height; return ImmSetCompositionFont(hIMC, ref lf); } static Rect GetBounds(this TextView textView, HwndSource source) { // this may happen during layout changes in AvalonDock, so we just return an empty rectangle // in those cases. It should be refreshed immediately. if (source.RootVisual == null || !source.RootVisual.IsAncestorOf(textView)) return EMPTY_RECT; Rect displayRect = new Rect(0, 0, textView.ActualWidth, textView.ActualHeight); return textView .TransformToAncestor(source.RootVisual).TransformBounds(displayRect) // rect on root visual .TransformToDevice(source.RootVisual); // rect on HWND } static readonly Rect EMPTY_RECT = new Rect(0, 0, 0, 0); static Rect GetCharacterBounds(this TextView textView, TextViewPosition pos, HwndSource source) { VisualLine vl = textView.GetVisualLine(pos.Line); if (vl == null) return EMPTY_RECT; // this may happen during layout changes in AvalonDock, so we just return an empty rectangle // in those cases. It should be refreshed immediately. if (source.RootVisual == null || !source.RootVisual.IsAncestorOf(textView)) return EMPTY_RECT; TextLine line = vl.GetTextLine(pos.VisualColumn, pos.IsAtEndOfLine); Rect displayRect; // calculate the display rect for the current character if (pos.VisualColumn < vl.VisualLengthWithEndOfLineMarker) { displayRect = line.GetTextBounds(pos.VisualColumn, 1).First().Rectangle; displayRect.Offset(0, vl.GetTextLineVisualYPosition(line, VisualYPosition.LineTop)); } else { // if we are in virtual space, we just use one wide-space as character width displayRect = new Rect(vl.GetVisualPosition(pos.VisualColumn, VisualYPosition.TextTop), new Size(textView.WideSpaceWidth, textView.DefaultLineHeight)); } // adjust to current scrolling displayRect.Offset(-textView.ScrollOffset); return textView .TransformToAncestor(source.RootVisual).TransformBounds(displayRect) // rect on root visual .TransformToDevice(source.RootVisual); // rect on HWND } } [ComImport, Guid("aa80e801-2021-11d2-93e0-0060b067b86e"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
LOGFONT
csharp
unoplatform__uno
src/Uno.UI/DirectUI/TrackableDateCollection.cs
{ "start": 2661, "end": 4196 }
record ____ changes hence we don't raise SelectedDatesChangedEvent if (!m_areEquivalentComparer(date, item)) { m_addedDates.Add(item); m_removedDates.Add(date); } base.SetAt(index, item); return; } public override void InsertAt(uint index, DateTime item) { RaiseCollectionChanging(CollectionChanging.ItemInserting, item); m_addedDates.Add(item); base.InsertAt(index, item); return; } public override void IndexOf(DateTime value, out uint index, out bool found) { index = 0; found = false; CheckThread(); for (uint i = 0; i < m_vector.Count; ++i) { if (m_areEquivalentComparer(m_vector[(int)i], value)) { index = i; found = true; break; } } return; } internal void CountOf(DateTime value, out uint pCount) { uint count = 0; pCount = 0; for (uint i = 0; i < m_vector.Count; ++i) { if (m_areEquivalentComparer(m_vector[(int)i], value)) { count++; } } pCount = count; return; } internal void RemoveAll(DateTime value, uint? pFromHint = null) { int from = (int)(pFromHint.HasValue ? pFromHint : 0); int i = (int)(m_vector.Count) - 1; for (; i >= from; --i) { if (m_areEquivalentComparer(m_vector[i], value)) { RemoveAt(i); } } return; } private void RaiseCollectionChanging(CollectionChanging action, DateTime addingDate) { if (m_collectionChanging is { }) { m_collectionChanging(action, addingDate); } return; } } }
the
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ContentPresenter/ContentPresenter_NativeEmbedding_Android_FillType.xaml.cs
{ "start": 444, "end": 631 }
partial class ____ : UserControl { public ContentPresenter_NativeEmbedding_Android_FillType() { this.InitializeComponent(); } } }
ContentPresenter_NativeEmbedding_Android_FillType
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Data/BindingExpression_With_Converter.xaml.cs
{ "start": 1984, "end": 2320 }
public partial class ____ : UserControl { public static DependencyProperty PropProperty { get; } = DependencyProperty.Register( nameof(Prop), typeof(string), typeof(MyElement), new PropertyMetadata(null)); public string Prop { get => (string)GetValue(PropProperty); set => SetValue(PropProperty, value); } }
MyElement
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Automation/ScrollPatternIdentifiers.cs
{ "start": 263, "end": 1586 }
public partial class ____ { // Skipping already declared property HorizontalScrollPercentProperty // Skipping already declared property HorizontalViewSizeProperty // Skipping already declared property HorizontallyScrollableProperty // Skipping already declared property NoScroll // Skipping already declared property VerticalScrollPercentProperty // Skipping already declared property VerticalViewSizeProperty // Skipping already declared property VerticallyScrollableProperty // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.HorizontallyScrollableProperty.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.HorizontalScrollPercentProperty.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.HorizontalViewSizeProperty.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.NoScroll.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.VerticallyScrollableProperty.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.VerticalScrollPercentProperty.get // Forced skipping of method Microsoft.UI.Xaml.Automation.ScrollPatternIdentifiers.VerticalViewSizeProperty.get } }
ScrollPatternIdentifiers
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/MongoClient.cs
{ "start": 9751, "end": 28755 }
interface ____ return ExecuteWriteOperationAsync(session, opertion, null, cancellationToken); } /// <inheritdoc/> public IMongoDatabase GetDatabase(string name, MongoDatabaseSettings settings = null) { ThrowIfDisposed(); settings = settings == null ? new MongoDatabaseSettings() : settings.Clone(); settings.ApplyDefaultValues(_settings); return new MongoDatabase(this, new DatabaseNamespace(name), settings, _cluster, _operationExecutor); } /// <inheritdoc /> public IAsyncCursor<string> ListDatabaseNames(CancellationToken cancellationToken = default) => ListDatabaseNames(options: null, cancellationToken); /// <inheritdoc /> public IAsyncCursor<string> ListDatabaseNames( ListDatabaseNamesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return ListDatabaseNames(session, options, cancellationToken); } /// <inheritdoc /> public IAsyncCursor<string> ListDatabaseNames( IClientSessionHandle session, CancellationToken cancellationToken = default) => ListDatabaseNames(session, options: null, cancellationToken); /// <inheritdoc /> public IAsyncCursor<string> ListDatabaseNames( IClientSessionHandle session, ListDatabaseNamesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); var listDatabasesOptions = CreateListDatabasesOptionsFromListDatabaseNamesOptions(options); var databases = ListDatabases(session, listDatabasesOptions, cancellationToken); return CreateDatabaseNamesCursor(databases); } /// <inheritdoc /> public Task<IAsyncCursor<string>> ListDatabaseNamesAsync(CancellationToken cancellationToken = default) => ListDatabaseNamesAsync(options: null, cancellationToken); /// <inheritdoc /> public async Task<IAsyncCursor<string>> ListDatabaseNamesAsync( ListDatabaseNamesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return await ListDatabaseNamesAsync(session, options, cancellationToken).ConfigureAwait(false); } /// <inheritdoc /> public Task<IAsyncCursor<string>> ListDatabaseNamesAsync( IClientSessionHandle session, CancellationToken cancellationToken = default) => ListDatabaseNamesAsync(session, options: null, cancellationToken); /// <inheritdoc /> public async Task<IAsyncCursor<string>> ListDatabaseNamesAsync( IClientSessionHandle session, ListDatabaseNamesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); var listDatabasesOptions = CreateListDatabasesOptionsFromListDatabaseNamesOptions(options); var databases = await ListDatabasesAsync(session, listDatabasesOptions, cancellationToken).ConfigureAwait(false); return CreateDatabaseNamesCursor(databases); } /// <inheritdoc/> public IAsyncCursor<BsonDocument> ListDatabases(CancellationToken cancellationToken) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return ListDatabases(session, cancellationToken); } /// <inheritdoc/> public IAsyncCursor<BsonDocument> ListDatabases( ListDatabasesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return ListDatabases(session, options, cancellationToken); } /// <inheritdoc/> public IAsyncCursor<BsonDocument> ListDatabases( IClientSessionHandle session, CancellationToken cancellationToken = default) => ListDatabases(session, null, cancellationToken); /// <inheritdoc/> public IAsyncCursor<BsonDocument> ListDatabases( IClientSessionHandle session, ListDatabasesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); Ensure.IsNotNull(session, nameof(session)); var operation = CreateListDatabasesOperation(options); return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken); } /// <inheritdoc/> public async Task<IAsyncCursor<BsonDocument>> ListDatabasesAsync(CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return await ListDatabasesAsync(session, cancellationToken).ConfigureAwait(false); } /// <inheritdoc/> public async Task<IAsyncCursor<BsonDocument>> ListDatabasesAsync( ListDatabasesOptions options, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return await ListDatabasesAsync(session, options, cancellationToken).ConfigureAwait(false); } /// <inheritdoc/> public Task<IAsyncCursor<BsonDocument>> ListDatabasesAsync( IClientSessionHandle session, CancellationToken cancellationToken = default) => ListDatabasesAsync(session, null, cancellationToken); /// <inheritdoc/> public Task<IAsyncCursor<BsonDocument>> ListDatabasesAsync( IClientSessionHandle session, ListDatabasesOptions options, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); var operation = CreateListDatabasesOperation(options); return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken); } /// <inheritdoc/> public IClientSessionHandle StartSession(ClientSessionOptions options = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); return StartSession(options); } /// <inheritdoc/> public Task<IClientSessionHandle> StartSessionAsync(ClientSessionOptions options = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); return Task.FromResult(StartSession(options)); } /// <inheritdoc/> public IChangeStreamCursor<TResult> Watch<TResult>( PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return Watch(session, pipeline, options, cancellationToken); } /// <inheritdoc/> public IChangeStreamCursor<TResult> Watch<TResult>( IClientSessionHandle session, PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(pipeline, nameof(pipeline)); ThrowIfDisposed(); var operation = CreateChangeStreamOperation(pipeline, options); return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken); } /// <inheritdoc/> public async Task<IChangeStreamCursor<TResult>> WatchAsync<TResult>( PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); using var session = _operationExecutor.StartImplicitSession(); return await WatchAsync(session, pipeline, options, cancellationToken).ConfigureAwait(false); } /// <inheritdoc/> public Task<IChangeStreamCursor<TResult>> WatchAsync<TResult>( IClientSessionHandle session, PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(pipeline, nameof(pipeline)); ThrowIfDisposed(); var operation = CreateChangeStreamOperation(pipeline, options); return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken); } /// <inheritdoc/> public IMongoClient WithReadConcern(ReadConcern readConcern) { Ensure.IsNotNull(readConcern, nameof(readConcern)); ThrowIfDisposed(); var newSettings = Settings.Clone(); newSettings.ReadConcern = readConcern; return new MongoClient(newSettings, _operationExecutorFactory); } /// <inheritdoc/> public IMongoClient WithReadPreference(ReadPreference readPreference) { Ensure.IsNotNull(readPreference, nameof(readPreference)); ThrowIfDisposed(); var newSettings = Settings.Clone(); newSettings.ReadPreference = readPreference; return new MongoClient(newSettings, _operationExecutorFactory); } /// <inheritdoc/> public IMongoClient WithWriteConcern(WriteConcern writeConcern) { Ensure.IsNotNull(writeConcern, nameof(writeConcern)); ThrowIfDisposed(); var newSettings = Settings.Clone(); newSettings.WriteConcern = writeConcern; return new MongoClient(newSettings, _operationExecutorFactory); } // private methods private ClientBulkWriteOperation CreateClientBulkWriteOperation(IReadOnlyList<BulkWriteModel> models, ClientBulkWriteOptions options) { if (_settings.AutoEncryptionOptions != null) { throw new NotSupportedException("BulkWrite does not currently support automatic encryption."); } if (options?.WriteConcern?.IsAcknowledged == false && options?.IsOrdered == true) { throw new NotSupportedException("Cannot request unacknowledged write concern and ordered writes."); } if (options?.WriteConcern?.IsAcknowledged == false && options?.VerboseResult == true) { throw new NotSupportedException("Cannot request unacknowledged write concern and verbose results"); } var messageEncoderSettings = GetMessageEncoderSettings(); var renderArgs = GetRenderArgs(); var operation = new ClientBulkWriteOperation(models, options, messageEncoderSettings, renderArgs) { RetryRequested = _settings.RetryWrites, }; if (options?.WriteConcern == null) { operation.WriteConcern = _settings.WriteConcern; } return operation; } private IAsyncCursor<string> CreateDatabaseNamesCursor(IAsyncCursor<BsonDocument> cursor) => new BatchTransformingAsyncCursor<BsonDocument, string>( cursor, databases => databases.Select(database => database["name"].AsString)); private DropDatabaseOperation CreateDropDatabaseOperation(string name) => new(new DatabaseNamespace(name), GetMessageEncoderSettings()) { WriteConcern = _settings.WriteConcern }; private ListDatabasesOperation CreateListDatabasesOperation(ListDatabasesOptions options) { options ??= new ListDatabasesOptions(); var messageEncoderSettings = GetMessageEncoderSettings(); var translationOptions = _settings.TranslationOptions; return new ListDatabasesOperation(messageEncoderSettings) { AuthorizedDatabases = options.AuthorizedDatabases, Comment = options.Comment, Filter = options.Filter?.Render(new(BsonDocumentSerializer.Instance, BsonSerializer.SerializerRegistry, translationOptions: translationOptions)), NameOnly = options.NameOnly, RetryRequested = _settings.RetryReads }; } private ListDatabasesOptions CreateListDatabasesOptionsFromListDatabaseNamesOptions(ListDatabaseNamesOptions options) { var listDatabasesOptions = new ListDatabasesOptions { NameOnly = true }; if (options != null) { listDatabasesOptions.AuthorizedDatabases = options.AuthorizedDatabases; listDatabasesOptions.Filter = options.Filter; listDatabasesOptions.Comment = options.Comment; listDatabasesOptions.Timeout = options.Timeout; } return listDatabasesOptions; } private ChangeStreamOperation<TResult> CreateChangeStreamOperation<TResult>( PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline, ChangeStreamOptions options) => ChangeStreamHelper.CreateChangeStreamOperation( pipeline, options, _settings.ReadConcern, GetMessageEncoderSettings(), _settings.RetryReads, _settings.TranslationOptions); private OperationContext CreateOperationContext(IClientSessionHandle session, TimeSpan? timeout, CancellationToken cancellationToken) { var operationContext = session.WrappedCoreSession.CurrentTransaction?.OperationContext; if (operationContext != null && timeout != null) { throw new InvalidOperationException("Cannot specify per operation timeout inside transaction."); } return operationContext?.Fork() ?? new OperationContext(timeout ?? _settings.Timeout, cancellationToken); } private TResult ExecuteReadOperation<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return _operationExecutor.ExecuteReadOperation(operationContext, session, operation, readPreference, false); } private async Task<TResult> ExecuteReadOperationAsync<TResult>(IClientSessionHandle session, IReadOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return await _operationExecutor.ExecuteReadOperationAsync(operationContext, session, operation, readPreference, false).ConfigureAwait(false); } private TResult ExecuteWriteOperation<TResult>(IClientSessionHandle session, IWriteOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return _operationExecutor.ExecuteWriteOperation(operationContext, session, operation, false); } private async Task<TResult> ExecuteWriteOperationAsync<TResult>(IClientSessionHandle session, IWriteOperation<TResult> operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, cancellationToken); return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, session, operation, false).ConfigureAwait(false); } private MessageEncoderSettings GetMessageEncoderSettings() { var messageEncoderSettings = new MessageEncoderSettings { { MessageEncoderSettingsName.ReadEncoding, _settings.ReadEncoding ?? Utf8Encodings.Strict }, { MessageEncoderSettingsName.WriteEncoding, _settings.WriteEncoding ?? Utf8Encodings.Strict } }; ConfigureAutoEncryptionMessageEncoderSettings(messageEncoderSettings); return messageEncoderSettings; } private RenderArgs<BsonDocument> GetRenderArgs() { var translationOptions = Settings.TranslationOptions; var serializerRegistry = BsonSerializer.SerializerRegistry; return new RenderArgs<BsonDocument>(BsonDocumentSerializer.Instance, serializerRegistry, translationOptions: translationOptions); } private IClientSessionHandle StartSession(ClientSessionOptions options) { if (options != null && options.Snapshot && options.CausalConsistency == true) { throw new NotSupportedException("Combining both causal consistency and snapshot options is not supported."); } options ??= new ClientSessionOptions(); if (_settings.Timeout.HasValue && options.DefaultTransactionOptions?.Timeout == null) { options.DefaultTransactionOptions = new TransactionOptions( _settings.Timeout, options.DefaultTransactionOptions?.ReadConcern, options.DefaultTransactionOptions?.ReadPreference, options.DefaultTransactionOptions?.WriteConcern, options.DefaultTransactionOptions?.MaxCommitTime); } var coreSession = _cluster.StartSession(options.ToCore()); return new ClientSessionHandle(this, options, coreSession); } private void ThrowIfDisposed() => ThrowIfDisposed(string.Empty); private T ThrowIfDisposed<T>(T value) => _disposed ? throw new ObjectDisposedException(GetType().Name) : value; } }
method
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Acceptance.Specs/FieldReports/Issue577_CannotSetOutValue.cs
{ "start": 2368, "end": 2465 }
public interface ____ : IKeyValue { string Value { get; set; } }
IKeyValueString
csharp
SixLabors__ImageSharp
src/ImageSharp/Formats/Tiff/Compression/Decompressors/NoneTiffCompression.cs
{ "start": 313, "end": 1191 }
internal sealed class ____ : TiffBaseDecompressor { /// <summary> /// Initializes a new instance of the <see cref="NoneTiffCompression" /> class. /// </summary> /// <param name="memoryAllocator">The memory allocator.</param> /// <param name="width">The width of the image.</param> /// <param name="bitsPerPixel">The bits per pixel.</param> public NoneTiffCompression(MemoryAllocator memoryAllocator, int width, int bitsPerPixel) : base(memoryAllocator, width, bitsPerPixel) { } /// <inheritdoc/> protected override void Decompress(BufferedReadStream stream, int byteCount, int stripHeight, Span<byte> buffer, CancellationToken cancellationToken) => _ = stream.Read(buffer, 0, Math.Min(buffer.Length, byteCount)); /// <inheritdoc/> protected override void Dispose(bool disposing) { } }
NoneTiffCompression
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/src/CodeGeneration/Analyzers/SelectionSet.cs
{ "start": 109, "end": 548 }
public class ____( ITypeDefinition type, SelectionSetNode syntaxNode, IReadOnlyList<FieldSelection> fields, IReadOnlyList<FragmentNode> fragmentNodes) { public ITypeDefinition Type { get; } = type; public SelectionSetNode SyntaxNode { get; } = syntaxNode; public IReadOnlyList<FieldSelection> Fields { get; } = fields; public IReadOnlyList<FragmentNode> FragmentNodes { get; } = fragmentNodes; }
SelectionSet
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/Model/IHasLongId.cs
{ "start": 167, "end": 213 }
public interface ____ : IHasId<long> { }
IHasLongId
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Rendering/Composition/Drawing/Nodes/RenderDataNodes.cs
{ "start": 4906, "end": 5316 }
class ____ : RenderDataPushNode { public double Opacity { get; set; } public override void Push(ref RenderDataNodeRenderContext context) { if (Opacity != 1) context.Context.PushOpacity(Opacity, null); } public override void Pop(ref RenderDataNodeRenderContext context) { if (Opacity != 1) context.Context.PopOpacity(); } }
RenderDataOpacityNode
csharp
MassTransit__MassTransit
src/Persistence/MassTransit.NHibernateIntegration/NHibernateIntegration/BinaryGuidType.cs
{ "start": 288, "end": 2376 }
public class ____ : IUserType { static readonly int[] _byteOrder = {10, 11, 12, 13, 14, 15, 8, 9, 6, 7, 4, 5, 0, 1, 2, 3}; static readonly SqlType[] _types = {new SqlType(DbType.Binary)}; public SqlType[] SqlTypes => _types; public Type ReturnedType => typeof(Guid); public new bool Equals(object x, object y) { return x != null && x.Equals(y); } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) { var bytes = (byte[])NHibernateUtil.Binary.NullSafeGet(rs, names[0], session); if (bytes == null || bytes.Length == 0) return null; var reorderedBytes = new byte[16]; for (var i = 0; i < 16; i++) reorderedBytes[_byteOrder[i]] = bytes[i]; return new Guid(reorderedBytes); } public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) { if (null != value) { byte[] bytes = ((Guid)value).ToByteArray(); var reorderedBytes = new byte[16]; for (var i = 0; i < 16; i++) reorderedBytes[i] = bytes[_byteOrder[i]]; NHibernateUtil.Binary.NullSafeSet(cmd, reorderedBytes, index, session); } else NHibernateUtil.Binary.NullSafeSet(cmd, null, index, session); } public object DeepCopy(object value) { return value; } public bool IsMutable => false; public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } } }
BinaryGuidType
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/VectorData.ConformanceTests/TypeTests/EmbeddingTypeTests.cs
{ "start": 8475, "end": 8640 }
public class ____<TVector> { public TKey Key { get; set; } public TVector Vector { get; set; } public int Int { get; set; } }
Record
csharp
dotnet__efcore
test/EFCore.Specification.Tests/Query/NorthwindSelectQueryTestBase.cs
{ "start": 97252, "end": 98264 }
public class ____(Customer customer) { public string Id { get; } = customer.CustomerID; } [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Set_operation_in_pending_collection(bool async) => AssertQuery( async, ss => ss.Set<Customer>() .OrderBy(x => x.CustomerID) .Select(x => new { OrderIds = (from o1 in ss.Set<Order>() where o1.CustomerID == x.CustomerID select o1.OrderID) .Union( from o2 in ss.Set<Order>() where o2.CustomerID == x.CustomerID select o2.OrderID) .ToList() }).Take(5), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e.OrderIds, a.OrderIds, elementSorter: ee => ee)); }
CustomerDtoWithEntityInCtor
csharp
AutoMapper__AutoMapper
src/UnitTests/AttributeBasedMaps.cs
{ "start": 30878, "end": 31438 }
public interface ____ { int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.AddMaps(typeof(When_specifying_as_proxy_via_attribute)); }); [Fact] public void Should_convert_to_interface() { var source = new Source { Value = 15 }; IDest dest = Mapper.Map<IDest>(source); dest.Value.ShouldBe(15); } }
IDest
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs
{ "start": 1502, "end": 6118 }
public abstract class ____ : IMember { protected readonly IMember baseMember; TypeParameterSubstitution substitution; IType declaringType; IType returnType; protected SpecializedMember(IMember memberDefinition) { if (memberDefinition == null) throw new ArgumentNullException(nameof(memberDefinition)); if (memberDefinition is SpecializedMember) throw new ArgumentException("Member definition cannot be specialized. Please use IMember.Specialize() instead of directly constructing SpecializedMember instances."); this.baseMember = memberDefinition; this.substitution = TypeParameterSubstitution.Identity; } /// <summary> /// Performs a substitution. This method may only be called by constructors in derived classes. /// </summary> protected void AddSubstitution(TypeParameterSubstitution newSubstitution) { Debug.Assert(declaringType == null); Debug.Assert(returnType == null); this.substitution = TypeParameterSubstitution.Compose(newSubstitution, this.substitution); } internal IMethod WrapAccessor(ref IMethod cachingField, IMethod accessorDefinition) { if (accessorDefinition == null) return null; var result = LazyInit.VolatileRead(ref cachingField); if (result != null) { return result; } else { var sm = accessorDefinition.Specialize(substitution); //sm.AccessorOwner = this; return LazyInit.GetOrSet(ref cachingField, sm); } } /// <summary> /// Gets the substitution belonging to this specialized member. /// </summary> public TypeParameterSubstitution Substitution { get { return substitution; } } public IType DeclaringType { get { var result = LazyInit.VolatileRead(ref this.declaringType); if (result != null) return result; IType definitionDeclaringType = baseMember.DeclaringType; ITypeDefinition definitionDeclaringTypeDef = definitionDeclaringType as ITypeDefinition; if (definitionDeclaringTypeDef != null && definitionDeclaringType.TypeParameterCount > 0) { if (substitution.ClassTypeArguments != null && substitution.ClassTypeArguments.Count == definitionDeclaringType.TypeParameterCount) { result = new ParameterizedType(definitionDeclaringTypeDef, substitution.ClassTypeArguments); } else { result = new ParameterizedType(definitionDeclaringTypeDef, definitionDeclaringTypeDef.TypeParameters).AcceptVisitor(substitution); } } else if (definitionDeclaringType != null) { result = definitionDeclaringType.AcceptVisitor(substitution); } return LazyInit.GetOrSet(ref this.declaringType, result); } internal set { // This setter is used as an optimization when the code constructing // the SpecializedMember already knows the declaring type. Debug.Assert(this.declaringType == null); // As this setter is used only during construction before the member is published // to other threads, we don't need a volatile write. this.declaringType = value; } } public IMember MemberDefinition { get { return baseMember.MemberDefinition; } } public IType ReturnType { get { var result = LazyInit.VolatileRead(ref this.returnType); if (result != null) return result; else return LazyInit.GetOrSet(ref this.returnType, baseMember.ReturnType.AcceptVisitor(substitution)); } protected set { // This setter is used for LiftedUserDefinedOperator, a special case of specialized member // (not a normal type parameter substitution). // As this setter is used only during construction before the member is published // to other threads, we don't need a volatile write. this.returnType = value; } } public System.Reflection.Metadata.EntityHandle MetadataToken => baseMember.MetadataToken; public bool IsVirtual { get { return baseMember.IsVirtual; } } public bool IsOverride { get { return baseMember.IsOverride; } } public bool IsOverridable { get { return baseMember.IsOverridable; } } public SymbolKind SymbolKind { get { return baseMember.SymbolKind; } } public ITypeDefinition DeclaringTypeDefinition { get { return baseMember.DeclaringTypeDefinition; } } IEnumerable<IAttribute> IEntity.GetAttributes() => baseMember.GetAttributes(); bool IEntity.HasAttribute(KnownAttribute attribute) => baseMember.HasAttribute(attribute); IAttribute IEntity.GetAttribute(KnownAttribute attribute) => baseMember.GetAttribute(attribute); public IEnumerable<IMember> ExplicitlyImplementedInterfaceMembers { get { // Note: if the
SpecializedMember
csharp
dotnetcore__CAP
src/DotNetCore.CAP/Persistence/IStorageInitializer.cs
{ "start": 251, "end": 459 }
public interface ____ { Task InitializeAsync(CancellationToken cancellationToken); string GetPublishedTableName(); string GetReceivedTableName(); string GetLockTableName(); }
IStorageInitializer
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_Xaml/Controls/When_TemplateBinding_And_VisualState_Setter_ClearValue.xaml.cs
{ "start": 630, "end": 827 }
partial class ____ : UserControl { public When_TemplateBinding_And_VisualState_Setter_ClearValue() { this.InitializeComponent(); } } }
When_TemplateBinding_And_VisualState_Setter_ClearValue
csharp
dotnet__maui
src/Core/tests/UnitTests/LocalizationTests.cs
{ "start": 16687, "end": 17017 }
public class ____ : IDisposable { string _globalFilePath = Path.Combine("localizationTestsOutput", "GlobalLog.txt"); public GlobalLogSetup() { // Delete the global log file if it exists if (File.Exists(_globalFilePath)) { File.Delete(_globalFilePath); } } public void Dispose() { } } }
GlobalLogSetup
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Validation/Events/ValidationEvents.cs
{ "start": 3196, "end": 3415 }
public sealed record ____(IOutputFieldDefinition OutputField) : IValidationEvent; /// <summary> /// Represents an event that is triggered when a type is encountered during schema validation. /// </summary>
OutputFieldEvent
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.FileSystem.Interface/IDirectoryInfo.cs
{ "start": 111, "end": 4587 }
public interface ____ : IFileSystemInfo { /// <inheritdoc cref="DirectoryInfo.Parent" /> IDirectoryInfo? Parent { get; } /// <inheritdoc cref="DirectoryInfo.Root" /> IDirectoryInfo Root { get; } /// <inheritdoc cref="DirectoryInfo.Create()" /> void Create(); /// <inheritdoc cref="DirectoryInfo.CreateSubdirectory(string)" /> IDirectoryInfo CreateSubdirectory(string path); /// <inheritdoc cref="DirectoryInfo.Delete(bool)" /> void Delete(bool recursive); /// <inheritdoc cref="DirectoryInfo.EnumerateDirectories()" /> IEnumerable<IDirectoryInfo> EnumerateDirectories(); /// <inheritdoc cref="DirectoryInfo.EnumerateDirectories(string)" /> IEnumerable<IDirectoryInfo> EnumerateDirectories( string searchPattern); /// <inheritdoc cref="DirectoryInfo.EnumerateDirectories(string, SearchOption)" /> IEnumerable<IDirectoryInfo> EnumerateDirectories( string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.EnumerateDirectories(string, EnumerationOptions)" /> IEnumerable<IDirectoryInfo> EnumerateDirectories( string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.EnumerateFiles()" /> IEnumerable<IFileInfo> EnumerateFiles(); /// <inheritdoc cref="DirectoryInfo.EnumerateFiles(string)" /> IEnumerable<IFileInfo> EnumerateFiles(string searchPattern); /// <inheritdoc cref="DirectoryInfo.EnumerateFiles(string, SearchOption)" /> IEnumerable<IFileInfo> EnumerateFiles( string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.EnumerateFiles(string, EnumerationOptions)" /> IEnumerable<IFileInfo> EnumerateFiles( string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.EnumerateFileSystemInfos()" /> IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos(); /// <inheritdoc cref="DirectoryInfo.EnumerateFileSystemInfos(string)" /> IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos( string searchPattern); /// <inheritdoc cref="DirectoryInfo.EnumerateFileSystemInfos(string, SearchOption)" /> IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos( string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.EnumerateFileSystemInfos(string, EnumerationOptions)" /> IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos( string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.GetDirectories()" /> IDirectoryInfo[] GetDirectories(); /// <inheritdoc cref="DirectoryInfo.GetDirectories(string)" /> IDirectoryInfo[] GetDirectories(string searchPattern); /// <inheritdoc cref="DirectoryInfo.GetDirectories(string, SearchOption)" /> IDirectoryInfo[] GetDirectories( string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.GetDirectories(string, EnumerationOptions)" /> IDirectoryInfo[] GetDirectories( string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.GetFiles()" /> IFileInfo[] GetFiles(); /// <inheritdoc cref="DirectoryInfo.GetFiles(string)" /> IFileInfo[] GetFiles(string searchPattern); /// <inheritdoc cref="DirectoryInfo.GetFiles(string, SearchOption)" /> IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.GetFiles(string, EnumerationOptions)" /> IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.GetFileSystemInfos()" /> IFileSystemInfo[] GetFileSystemInfos(); /// <inheritdoc cref="DirectoryInfo.GetFileSystemInfos(string)" /> IFileSystemInfo[] GetFileSystemInfos(string searchPattern); /// <inheritdoc cref="DirectoryInfo.GetFileSystemInfos(string, SearchOption)" /> IFileSystemInfo[] GetFileSystemInfos( string searchPattern, SearchOption searchOption); #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS /// <inheritdoc cref="DirectoryInfo.GetFileSystemInfos(string, EnumerationOptions)" /> IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="DirectoryInfo.MoveTo(string)" /> void MoveTo(string destDirName); }
IDirectoryInfo
csharp
EventStore__EventStore
src/KurrentDB.Testing.ClusterVNodeApp/KurrentContext.cs
{ "start": 386, "end": 1370 }
public sealed class ____ : IAsyncInitializer { [ClassDataSource<NodeShim>(Shared = SharedType.PerTestSession)] public required NodeShim NodeShim { get; init; } [ClassDataSource<GrpcChannelShim>()] public required GrpcChannelShim GrpcChannelShim { get; init; } [ClassDataSource<RestClientShim>()] public required RestClientShim RestClientShim { get; init; } public INode Node => NodeShim.Node; public ConnectorsCommandService.ConnectorsCommandServiceClient ConnectorsClient { get; private set; } = null!; public PersistentSubscriptions.PersistentSubscriptionsClient PersistentSubscriptionsClient { get; private set; } = null!; public StreamsService.StreamsServiceClient StreamsV2Client { get; private set; } = null!; public Task InitializeAsync() { ConnectorsClient = new(GrpcChannelShim.GrpcChannel); PersistentSubscriptionsClient = new(GrpcChannelShim.GrpcChannel); StreamsV2Client = new(GrpcChannelShim.GrpcChannel); return Task.CompletedTask; } }
KurrentContext
csharp
dotnet__maui
src/Controls/src/Core/Interactivity/IAttachedObject.cs
{ "start": 55, "end": 183 }
internal interface ____ { void AttachTo(BindableObject bindable); void DetachFrom(BindableObject bindable); } }
IAttachedObject
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 3110203, "end": 3110606 }
public partial interface ____ : IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Deployment_Errors_2, IPersistedQueryValidationError { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Deployment_Errors_PersistedQueryValidationError_2
csharp
ServiceStack__ServiceStack
ServiceStack/tests/Check.ServiceInterface/CustomRoutesService.cs
{ "start": 99, "end": 253 }
public class ____ { public string LeadType { get; set; } public int MyId { get; set; } } [Route("/info/{Id}")]
LegacyLeadPost
csharp
jellyfin__jellyfin
MediaBrowser.Controller/Providers/RemoteSearchQuery.cs
{ "start": 116, "end": 727 }
public class ____<T> where T : ItemLookupInfo { public T SearchInfo { get; set; } public Guid ItemId { get; set; } /// <summary> /// Gets or sets the provider name to search within if set. /// </summary> public string SearchProviderName { get; set; } /// <summary> /// Gets or sets a value indicating whether disabled providers should be included. /// </summary> /// <value><c>true</c> if disabled providers should be included.</value> public bool IncludeDisabledProviders { get; set; } } }
RemoteSearchQuery
csharp
dotnet__machinelearning
src/Microsoft.ML.Transforms/HashJoiningTransform.cs
{ "start": 1606, "end": 1862 }
private static class ____ { public const bool Join = true; public const int NumberOfBits = NumBitsLim - 1; public const uint Seed = 314489979; public const bool Ordered = true; }
Defaults
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Serializers/SerializePolymorphicClassTests.cs
{ "start": 1275, "end": 1367 }
private class ____ : B { public string FE { get; set; } }
E
csharp
dotnet__efcore
test/EFCore.Specification.Tests/TestModels/ManyToManyModel/UnidirectionalEntityLeaf.cs
{ "start": 227, "end": 550 }
public class ____ : UnidirectionalEntityBranch { public virtual bool? IsGreen { get; set; } public virtual ICollection<UnidirectionalEntityCompositeKey> CompositeKeySkipFull { get; set; } public virtual ICollection<UnidirectionalJoinCompositeKeyToLeaf> JoinCompositeKeyFull { get; set; } }
UnidirectionalEntityLeaf
csharp
dotnet__aspire
tests/Aspire.Hosting.Tests/Backchannel/AuxiliaryBackchannelTests.cs
{ "start": 381, "end": 12238 }
public class ____(ITestOutputHelper outputHelper) { [Fact] public async Task CanStartAuxiliaryBackchannelService() { using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); var connectedEventReceived = new TaskCompletionSource<AuxiliaryBackchannelConnectedEvent>(); builder.Eventing.Subscribe<AuxiliaryBackchannelConnectedEvent>((e, ct) => { connectedEventReceived.TrySetResult(e); return Task.CompletedTask; }); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service and verify it started var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); Assert.True(File.Exists(service.SocketPath)); // Connect a client var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); // Verify the connected event was published var connectedEvent = await connectedEventReceived.Task.WaitAsync(TimeSpan.FromSeconds(60)); Assert.NotNull(connectedEvent); Assert.Equal(service.SocketPath, connectedEvent.SocketPath); socket.Dispose(); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } [Fact] public async Task CanConnectMultipleClientsToAuxiliaryBackchannel() { using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); var connectedEventCount = 0; var connectedEventLock = new object(); builder.Eventing.Subscribe<AuxiliaryBackchannelConnectedEvent>((e, ct) => { lock (connectedEventLock) { connectedEventCount++; } return Task.CompletedTask; }); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); // Connect multiple clients concurrently var client1Socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var client2Socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var client3Socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await client1Socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); await client2Socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); await client3Socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); // Give some time for events to be published await Task.Delay(1000); // Verify that all three connections triggered events lock (connectedEventLock) { Assert.Equal(3, connectedEventCount); } client1Socket.Dispose(); client2Socket.Dispose(); client3Socket.Dispose(); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } [Fact] public async Task CanInvokeRpcMethodOnAuxiliaryBackchannel() { // This test verifies that RPC methods can be invoked // When the Dashboard is not part of the app model, null should be returned using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); // Connect a client var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); using var stream = new NetworkStream(socket, ownsSocket: true); using var rpc = JsonRpc.Attach(stream); // Invoke the GetDashboardMcpConnectionInfoAsync RPC method var connectionInfo = await rpc.InvokeAsync<DashboardMcpConnectionInfo?>( "GetDashboardMcpConnectionInfoAsync", Array.Empty<object>() ).WaitAsync(TimeSpan.FromSeconds(60)); // Since the dashboard is not part of the app model, it should return null Assert.Null(connectionInfo); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } [Fact] public async Task GetAppHostInformationAsyncReturnsAppHostPath() { // This test verifies that GetAppHostInformationAsync returns the AppHost path using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); // Connect a client var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); using var stream = new NetworkStream(socket, ownsSocket: true); using var rpc = JsonRpc.Attach(stream); // Invoke the GetAppHostInformationAsync RPC method var appHostInfo = await rpc.InvokeAsync<AppHostInformation>( "GetAppHostInformationAsync", Array.Empty<object>() ).WaitAsync(TimeSpan.FromSeconds(60)); // The AppHost path should be set Assert.NotNull(appHostInfo); Assert.NotNull(appHostInfo.AppHostPath); Assert.NotEmpty(appHostInfo.AppHostPath); // The ProcessId should be set and valid Assert.True(appHostInfo.ProcessId > 0); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } [Fact] public async Task MultipleClientsCanInvokeRpcMethodsConcurrently() { // This test verifies that multiple clients can invoke RPC methods concurrently // When the Dashboard is not part of the app model, null should be returned using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); // Create multiple clients and invoke RPC methods concurrently var tasks = Enumerable.Range(0, 5).Select(async i => { var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await socket.ConnectAsync(endpoint); using var stream = new NetworkStream(socket, ownsSocket: true); using var rpc = JsonRpc.Attach(stream); var connectionInfo = await rpc.InvokeAsync<DashboardMcpConnectionInfo?>( "GetDashboardMcpConnectionInfoAsync", Array.Empty<object>() ); // Since the dashboard is not part of the app model, it should return null Assert.Null(connectionInfo); return connectionInfo; }); var results = await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(60)); Assert.Equal(5, results.Length); Assert.All(results, Assert.Null); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } [Fact] public async Task GetAppHostInformationAsyncReturnsFilePathWithExtension() { // This test verifies that GetAppHostInformationAsync returns the full file path with extension // For .csproj-based AppHosts, it should include the .csproj extension using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper); // Register the auxiliary backchannel service builder.Services.AddSingleton<AuxiliaryBackchannelService>(); builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<AuxiliaryBackchannelService>()); using var app = builder.Build(); await app.StartAsync().WaitAsync(TimeSpan.FromSeconds(60)); // Get the service var service = app.Services.GetRequiredService<AuxiliaryBackchannelService>(); Assert.NotNull(service.SocketPath); // Connect a client var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); var endpoint = new UnixDomainSocketEndPoint(service.SocketPath); await socket.ConnectAsync(endpoint).WaitAsync(TimeSpan.FromSeconds(60)); using var stream = new NetworkStream(socket, ownsSocket: true); using var rpc = JsonRpc.Attach(stream); // Invoke the GetAppHostInformationAsync RPC method var appHostInfo = await rpc.InvokeAsync<AppHostInformation>( "GetAppHostInformationAsync", Array.Empty<object>() ).WaitAsync(TimeSpan.FromSeconds(60)); // Verify the AppHost path is returned Assert.NotNull(appHostInfo); Assert.NotNull(appHostInfo.AppHostPath); Assert.NotEmpty(appHostInfo.AppHostPath); // The path should be an absolute path Assert.True(Path.IsPathRooted(appHostInfo.AppHostPath), $"Expected absolute path but got: {appHostInfo.AppHostPath}"); // In test scenarios where assembly metadata is not available, we may get a path without extension // (falling back to AppHost:Path). In real scenarios with proper metadata, we should get .csproj or .cs // So we just verify the path is non-empty and rooted outputHelper.WriteLine($"AppHost path returned: {appHostInfo.AppHostPath}"); await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(60)); } }
AuxiliaryBackchannelTests