language stringclasses 1 value | repo stringclasses 133 values | path stringlengths 13 229 | class_span dict | source stringlengths 14 2.92M | target stringlengths 1 153 |
|---|---|---|---|---|---|
csharp | MassTransit__MassTransit | src/Transports/MassTransit.KafkaIntegration/KafkaIntegration/IConsumerContextSupervisor.cs | {
"start": 69,
"end": 175
} | public interface ____ :
ITransportSupervisor<ConsumerContext>
{
}
}
| IConsumerContextSupervisor |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs | {
"start": 66950,
"end": 67212
} | private class ____
{
[ApiExplorerSettings(IgnoreApi = true)]
public void Edit() { }
}
[Route("AttributeRouting/IsRequired/ForApiExplorer")]
[ApiExplorerSettings(IgnoreApi = true)]
| ApiExplorerExplicitlyNotVisibleOnActionController |
csharp | MassTransit__MassTransit | src/MassTransit/InMemoryTransport/InMemoryTransport/Configuration/IInMemoryConsumeTopologySpecification.cs | {
"start": 100,
"end": 260
} | public interface ____ :
ISpecification
{
void Apply(IMessageFabricConsumeTopologyBuilder builder);
}
}
| IInMemoryConsumeTopologySpecification |
csharp | exceptionless__Exceptionless | src/Exceptionless.Core/Plugins/EventProcessor/Default/03_ManualStackingPlugin.cs | {
"start": 178,
"end": 738
} | public sealed class ____ : EventProcessorPluginBase
{
public ManualStackingPlugin(AppOptions options, ILoggerFactory loggerFactory) : base(options, loggerFactory) { }
public override Task EventProcessingAsync(EventContext context)
{
var msi = context.Event.GetManualStackingInfo();
if (msi?.SignatureData is not null)
{
foreach (var kvp in msi.SignatureData)
context.StackSignatureData.AddItemIfNotEmpty(kvp.Key, kvp.Value);
}
return Task.CompletedTask;
}
}
| ManualStackingPlugin |
csharp | smartstore__Smartstore | test/Smartstore.Core.Tests/Checkout/Shipping/ShippingServiceTests.cs | {
"start": 611,
"end": 5368
} | public class ____ : ServiceTestBase
{
ShippingSettings _shippingSettings;
IShippingService _shippingService;
IProductAttributeMaterializer _productAttributeMaterializer;
IStoreContext _storeContext;
IRequestCache _requestCache;
[OneTimeSetUp]
public new void SetUp()
{
_shippingSettings = new ShippingSettings
{
ActiveShippingRateComputationMethodSystemNames = new List<string>
{
"FixedRateTestShippingRateComputationMethod"
}
};
_requestCache = new NullRequestCache();
var downloadService = new Mock<IDownloadService>();
_productAttributeMaterializer = new ProductAttributeMaterializer(
null,
null,
NullRequestCache.Instance,
null,
new Lazy<IDownloadService>(() => downloadService.Object),
null);
var storeContextMock = new Mock<IStoreContext>();
_storeContext = storeContextMock.Object;
DbContext.ShippingMethods.Add(new() { Name = "1" });
DbContext.ShippingMethods.Add(new() { Name = "2" });
DbContext.ShippingMethods.Add(new() { Name = "3" });
DbContext.ShippingMethods.Add(new() { Name = "4" });
DbContext.SaveChanges();
var ruleProviderFactoryMock = new Mock<IRuleProviderFactory>();
ruleProviderFactoryMock.Setup(x => x.GetProvider(RuleScope.Cart, null)).Returns(new Mock<ICartRuleProvider>().Object);
_shippingService = new ShippingService(
_productAttributeMaterializer,
null,
ruleProviderFactoryMock.Object,
_shippingSettings,
ProviderManager,
null,
_requestCache,
null,
_storeContext,
DbContext);
}
[Test]
public async Task Can_load_shippingRateComputationMethods()
{
var srcm = await _shippingService.GetAllShippingMethodsAsync();
srcm.ShouldNotBeNull();
(srcm.Count > 0).ShouldBeTrue();
}
[Test]
public void Can_load_shippingRateComputationMethod_by_systemKeyword()
{
var srcm = _shippingService.LoadEnabledShippingProviders(systemName: "FixedRateTestShippingRateComputationMethod").FirstOrDefault();
srcm.Value.ShouldNotBeNull();
}
[Test]
public void Can_load_active_shippingRateComputationMethods()
{
var srcm = _shippingService.LoadEnabledShippingProviders();
srcm.ShouldNotBeNull();
srcm.Any().ShouldBeTrue();
}
[Test]
public async Task Can_get_shoppingCartItem_totalWeight_without_attributes()
{
var sci = new ShoppingCartItem
{
RawAttributes = "",
Quantity = 3,
Product = new Product
{
Weight = 1.5M,
Height = 2.5M,
Length = 3.5M,
Width = 4.5M
}
};
var item = new OrganizedShoppingCartItem(sci);
(await _shippingService.GetCartItemWeightAsync(item)).ShouldEqual(4.5M);
}
[Test]
public async Task Can_get_shoppingCart_totalWeight_without_attributes()
{
var sci1 = new ShoppingCartItem
{
RawAttributes = string.Empty,
Quantity = 3,
Product = new Product
{
Weight = 1.5M,
Height = 2.5M,
Length = 3.5M,
Width = 4.5M
}
};
var sci2 = new ShoppingCartItem
{
RawAttributes = string.Empty,
Quantity = 4,
Product = new Product
{
Weight = 11.5M,
Height = 12.5M,
Length = 13.5M,
Width = 14.5M
}
};
var items = new List<OrganizedShoppingCartItem>
{
new OrganizedShoppingCartItem(sci1),
new OrganizedShoppingCartItem(sci2)
};
var customer = new Customer
{
Id = 1,
};
var cart = new ShoppingCart(customer, 0, items);
(await _shippingService.GetCartTotalWeightAsync(cart)).ShouldEqual(50.5M);
}
}
}
| ShippingServiceTests |
csharp | NLog__NLog | tests/NLog.UnitTests/LayoutRenderers/TempDirRendererTests.cs | {
"start": 1741,
"end": 2618
} | public class ____ : NLogTestBase
{
[Fact]
public void RenderTempDir()
{
Layout layout = "${tempdir}";
layout.Initialize(null);
string actual = layout.Render(LogEventInfo.CreateNullEvent());
layout.Close();
Assert.NotNull(actual);
Assert.Equal(Path.GetTempPath(), actual);
}
[Fact]
public void RenderTempDir_with_file_and_dir()
{
Layout layout = "${tempdir:dir=test:file=file1.txt}";
layout.Initialize(null);
string actual = layout.Render(LogEventInfo.CreateNullEvent());
layout.Close();
Assert.NotNull(actual);
Assert.Equal(Path.Combine(Path.Combine(Path.GetTempPath(), "test" + Path.DirectorySeparatorChar), "file1.txt"), actual);
}
}
}
| TempDirRendererTests |
csharp | IdentityModel__IdentityModel | src/Internal/QueryHelpers.cs | {
"start": 301,
"end": 3187
} | internal static class ____
{
/// <summary>
/// Append the given query key and value to the URI.
/// </summary>
/// <param name="uri">The base URI.</param>
/// <param name="name">The name of the query key.</param>
/// <param name="value">The query value.</param>
/// <returns>The combined result.</returns>
public static string AddQueryString(string uri, string name, string value)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return AddQueryString(
uri, new[] { new KeyValuePair<string, string>(name, value) });
}
/// <summary>
/// Append the given query keys and values to the uri.
/// </summary>
/// <param name="uri">The base uri.</param>
/// <param name="queryString">A collection of name value query pairs to append.</param>
/// <returns>The combined result.</returns>
public static string AddQueryString(string uri, IDictionary<string, string> queryString)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (queryString == null)
{
throw new ArgumentNullException(nameof(queryString));
}
return AddQueryString(uri, (IEnumerable<KeyValuePair<string, string>>)queryString);
}
public static string AddQueryString(
string uri,
IEnumerable<KeyValuePair<string, string>> queryString)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (queryString == null)
{
throw new ArgumentNullException(nameof(queryString));
}
var anchorIndex = uri.IndexOf('#');
var uriToBeAppended = uri;
var anchorText = "";
// If there is an anchor, then the query string must be inserted before its first occurance.
if (anchorIndex != -1)
{
anchorText = uri.Substring(anchorIndex);
uriToBeAppended = uri.Substring(0, anchorIndex);
}
var queryIndex = uriToBeAppended.IndexOf('?');
var hasQuery = queryIndex != -1;
var sb = new StringBuilder();
sb.Append(uriToBeAppended);
foreach (var parameter in queryString)
{
if (parameter.Value == null) continue;
sb.Append(hasQuery ? '&' : '?');
sb.Append(UrlEncoder.Default.Encode(parameter.Key));
sb.Append('=');
sb.Append(UrlEncoder.Default.Encode(parameter.Value));
hasQuery = true;
}
sb.Append(anchorText);
return sb.ToString();
}
} | QueryHelpers |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs | {
"start": 353,
"end": 436
} | class ____ static helper methods for background tasks.
/// </summary>
| provides |
csharp | dotnet__orleans | src/api/Orleans.Core.Abstractions/Orleans.Core.Abstractions.cs | {
"start": 152186,
"end": 153768
} | partial class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<global::Orleans.Metadata.ClusterManifest>, global::Orleans.Serialization.Codecs.IFieldCodec
{
public Codec_ClusterManifest(global::Orleans.Serialization.Activators.IActivator<global::Orleans.Metadata.ClusterManifest> _activator, global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { }
public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Metadata.ClusterManifest instance) { }
public global::Orleans.Metadata.ClusterManifest ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; }
public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, global::Orleans.Metadata.ClusterManifest instance)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, global::Orleans.Metadata.ClusterManifest value)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
}
[System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public sealed | Codec_ClusterManifest |
csharp | dotnet__maui | src/Controls/tests/ManualTests/Performance/CollectionViewPool/Models/Enums.cs | {
"start": 37,
"end": 98
} | public enum ____
{
US, //0
Metric, // 1
Imperial // 2
}
| Units |
csharp | ServiceStack__ServiceStack | ServiceStack.Blazor/tests/UI.Gallery/Gallery/MyApp/MarkdownPagesBase.cs | {
"start": 24645,
"end": 24847
} | public class ____
{
public string? Icon { get; set; }
public string? Text { get; set; }
public string? Link { get; set; }
public List<MarkdownMenuItem>? Children { get; set; }
}
| MarkdownMenu |
csharp | npgsql__npgsql | test/Npgsql.Tests/NpgsqlEventSourceTests.cs | {
"start": 166,
"end": 1361
} | public class ____ : TestBase
{
[Test]
public void Command_start_stop()
{
using (var conn = OpenConnection())
{
// There is a new pool created, which sends a few queries to load pg types
ClearEvents();
conn.ExecuteScalar("SELECT 1");
}
var commandStart = _events.Single(e => e.EventId == NpgsqlEventSource.CommandStartId);
Assert.That(commandStart.EventName, Is.EqualTo("CommandStart"));
var commandStop = _events.Single(e => e.EventId == NpgsqlEventSource.CommandStopId);
Assert.That(commandStop.EventName, Is.EqualTo("CommandStop"));
}
[OneTimeSetUp]
public void EnableEventSource()
{
_listener = new TestEventListener(_events);
_listener.EnableEvents(NpgsqlSqlEventSource.Log, EventLevel.Informational);
}
[OneTimeTearDown]
public void DisableEventSource()
{
_listener.DisableEvents(NpgsqlSqlEventSource.Log);
_listener.Dispose();
}
[SetUp]
public void ClearEvents() => _events.Clear();
TestEventListener _listener = null!;
readonly List<EventWrittenEventArgs> _events = [];
| NpgsqlEventSourceTests |
csharp | abpframework__abp | modules/feature-management/src/Volo.Abp.FeatureManagement.MongoDB/Volo/Abp/FeatureManagement/MongoDB/MongoFeatureDefinitionRecordRepository.cs | {
"start": 231,
"end": 1029
} | public class ____ :
MongoDbRepository<IFeatureManagementMongoDbContext, FeatureDefinitionRecord, Guid>,
IFeatureDefinitionRecordRepository
{
public MongoFeatureDefinitionRecordRepository(
IMongoDbContextProvider<IFeatureManagementMongoDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
public virtual async Task<FeatureDefinitionRecord> FindByNameAsync(string name, CancellationToken cancellationToken = default)
{
cancellationToken = GetCancellationToken(cancellationToken);
return await (await GetQueryableAsync(cancellationToken))
.OrderBy(x => x.Id)
.FirstOrDefaultAsync(
s => s.Name == name,
cancellationToken
);
}
}
| MongoFeatureDefinitionRecordRepository |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsIntrospectionTest.Client.cs | {
"start": 147030,
"end": 147190
} | enum ____ what kind of type a given `__Type` is.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
| describing |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Exceptions/RoutingSlipArgumentException.cs | {
"start": 108,
"end": 790
} | public class ____ :
RoutingSlipException
{
public RoutingSlipArgumentException()
{
}
public RoutingSlipArgumentException(string message)
: base(message)
{
}
public RoutingSlipArgumentException(string message, Exception innerException)
: base(message, innerException)
{
}
#if NET8_0_OR_GREATER
[Obsolete("Formatter-based serialization is obsolete and should not be used.")]
#endif
protected RoutingSlipArgumentException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| RoutingSlipArgumentException |
csharp | microsoft__PowerToys | src/modules/cmdpal/Microsoft.CmdPal.UI/Program.cs | {
"start": 717,
"end": 5630
} | internal sealed class ____
{
private static DispatcherQueueSynchronizationContext? uiContext;
private static App? app;
// LOAD BEARING
//
// Main cannot be async. If it is, then the clipboard won't work, and neither will narrator.
// That means you, the person thinking about making this a MTA thread. Don't
// do it. It won't work. That's not the solution.
[STAThread]
private static int Main(string[] args)
{
if (Helpers.GpoValueChecker.GetConfiguredCmdPalEnabledValue() == Helpers.GpoRuleConfiguredValue.Disabled)
{
// There's a GPO rule configured disabling CmdPal. Exit as soon as possible.
return 0;
}
try
{
Logger.InitializeLogger("\\CmdPal\\Logs\\");
}
catch (COMException e)
{
// This is unexpected. For the sake of debugging:
// pop a message box
PInvoke.MessageBox(
(HWND)IntPtr.Zero,
$"Failed to initialize the logger. COMException: \r{e.Message}",
"Command Palette",
MESSAGEBOX_STYLE.MB_OK | MESSAGEBOX_STYLE.MB_ICONERROR);
return 0;
}
catch (Exception e2)
{
// This is unexpected. For the sake of debugging:
// pop a message box
PInvoke.MessageBox(
(HWND)IntPtr.Zero,
$"Failed to initialize the logger. Unknown Exception: \r{e2.Message}",
"Command Palette",
MESSAGEBOX_STYLE.MB_OK | MESSAGEBOX_STYLE.MB_ICONERROR);
return 0;
}
Logger.LogDebug($"Starting at {DateTime.UtcNow}");
PowerToysTelemetry.Log.WriteEvent(new CmdPalProcessStarted());
WinRT.ComWrappersSupport.InitializeComWrappers();
var isRedirect = DecideRedirection();
if (!isRedirect)
{
Microsoft.UI.Xaml.Application.Start((p) =>
{
uiContext = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread());
SynchronizationContext.SetSynchronizationContext(uiContext);
app = new App();
});
}
return 0;
}
private static bool DecideRedirection()
{
var isRedirect = false;
var args = AppInstance.GetCurrent().GetActivatedEventArgs();
var keyInstance = AppInstance.FindOrRegisterForKey("randomKey");
if (keyInstance.IsCurrent)
{
PowerToysTelemetry.Log.WriteEvent(new ColdLaunch());
keyInstance.Activated += OnActivated;
}
else
{
isRedirect = true;
PowerToysTelemetry.Log.WriteEvent(new ReactivateInstance());
RedirectActivationTo(args, keyInstance);
}
return isRedirect;
}
private static void RedirectActivationTo(AppActivationArguments args, AppInstance keyInstance)
{
// Do the redirection on another thread, and use a non-blocking
// wait method to wait for the redirection to complete.
using var redirectSemaphore = new Semaphore(0, 1);
var redirectTimeout = TimeSpan.FromSeconds(32);
_ = Task.Run(() =>
{
using var cts = new CancellationTokenSource(redirectTimeout);
try
{
keyInstance.RedirectActivationToAsync(args)
.AsTask(cts.Token)
.GetAwaiter()
.GetResult();
}
catch (OperationCanceledException)
{
Logger.LogError($"Failed to activate existing instance; timed out after {redirectTimeout}.");
}
catch (Exception ex)
{
Logger.LogError("Failed to activate existing instance", ex);
}
finally
{
redirectSemaphore.Release();
}
});
_ = PInvoke.CoWaitForMultipleObjects(
(uint)CWMO_FLAGS.CWMO_DEFAULT,
PInvoke.INFINITE,
[new HANDLE(redirectSemaphore.SafeWaitHandle.DangerousGetHandle())],
out _);
}
private static void OnActivated(object? sender, AppActivationArguments args)
{
// If we already have a form, display the message now.
// Otherwise, add it to the collection for displaying later.
if (App.Current?.AppWindow is MainWindow mainWindow)
{
// LOAD BEARING
// This must be synchronous to ensure the method does not return
// before the activation is fully handled and the parameters are processed.
// The sending instance remains blocked until this returns; afterward it may quit,
// causing the activation arguments to be lost.
mainWindow.HandleLaunchNonUI(args);
}
}
}
| Program |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/IO/DirectoryAliasesTests.cs | {
"start": 21773,
"end": 24882
} | public sealed class ____
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var path = new DirectoryPath("/Temp");
// When
var result = Record.Exception(() =>
DirectoryAliases.CreateDirectory(null, path));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Directory_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
DirectoryAliases.CreateDirectory(context, null));
// Then
AssertEx.IsArgumentNullException(result, "path");
}
[Fact]
public void Should_Create_Non_Existing_Directory()
{
// Given
var fileSystem = Substitute.For<IFileSystem>();
var directory = Substitute.For<IDirectory>();
directory.Exists.Returns(false);
fileSystem.GetDirectory(Arg.Is<DirectoryPath>(p => p.FullPath == "/Temp")).Returns(directory);
var context = Substitute.For<ICakeContext>();
context.FileSystem.Returns(fileSystem);
// When
DirectoryAliases.CreateDirectory(context, "/Temp");
// Then
directory.Received(1).Create();
}
[Fact]
public void Should_Not_Try_To_Create_Directory_If_It_Already_Exist()
{
// Given
var fileSystem = Substitute.For<IFileSystem>();
var directory = Substitute.For<IDirectory>();
directory.Exists.Returns(true);
fileSystem.GetDirectory(Arg.Is<DirectoryPath>(p => p.FullPath == "/Temp")).Returns(directory);
var context = Substitute.For<ICakeContext>();
context.FileSystem.Returns(fileSystem);
// When
DirectoryAliases.CreateDirectory(context, "/Temp");
// Then
directory.Received(0).Create();
}
[Fact]
public void Should_Make_Relative_Path_Absolute()
{
// Given
var fileSystem = Substitute.For<IFileSystem>();
var context = Substitute.For<ICakeContext>();
var environment = Substitute.For<ICakeEnvironment>();
environment.WorkingDirectory.Returns("/Temp");
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When
DirectoryAliases.CreateDirectory(context, "Hello");
// Then
fileSystem.Received(1).GetDirectory(Arg.Is<DirectoryPath>(
p => p.FullPath == "/Temp/Hello"));
}
}
| TheCreateMethod |
csharp | atata-framework__atata | test/Atata.UnitTests/Sessions/AtataSessionEventSubscriptionsBuilderTests.cs | {
"start": 107,
"end": 7923
} | public sealed class ____
{
private Subject<AtataSessionEventSubscriptionsBuilder<AtataContextBuilder>> _sut = null!;
[SetUp]
public void SetUp() =>
_sut = new AtataSessionEventSubscriptionsBuilder<AtataContextBuilder>(AtataContext.CreateDefaultNonScopedBuilder())
.ToSutSubject();
[Test]
public void NullAsAction() =>
_sut.Invoking(x => x.Add<TestEvent>((null as Action)!))
.Should.Throw<ArgumentNullException>();
[Test]
public void Action() =>
_sut.Act(x => x.Add<TestEvent>(StubMethod))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void AsyncAction() =>
_sut.Act(x => x.Add<TestEvent>(StubMethodAsync))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void ActionWith1GenericParameter() =>
_sut.Act(x => x.Add<TestEvent>(_ => StubMethod()))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void AsyncActionWith1GenericParameter() =>
_sut.Act(x => x.Add<TestEvent>((_, ct) => StubMethodAsync(ct)))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void ActionWith2GenericParameters() =>
_sut.Act(x => x.Add<TestEvent>((_, _) => StubMethod()))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void AsyncActionWith2GenericParameters() =>
_sut.Act(x => x.Add<TestEvent>((_, _, ct) => StubMethodAsync(ct)))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler != null);
[Test]
public void TwoGenericParameters_WithInvalidEventHandlerType() =>
_sut.Invoking(x => x.Add<TestEvent, TestEvent>())
.Should.ThrowExactly<ArgumentException>(
$"'eventHandlerType' of {typeof(TestEvent).FullName} type doesn't implement Atata.IEventHandler`1[*] or Atata.IAsyncEventHandler`1[*]. (Parameter 'eventHandlerType')");
[Test]
public void TwoGenericParameters_WithSyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, TestEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestEventHandler);
[Test]
public void TwoGenericParameters_WithAsyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, TestAsyncEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestAsyncEventHandler);
[Test]
public void EventHandler()
{
var eventHandler = new TestEventHandler();
_sut.Act(x => x.Add(eventHandler))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler == eventHandler);
}
[Test]
public void AsyncEventHandler()
{
var eventHandler = new TestAsyncEventHandler();
_sut.Act(x => x.Add(eventHandler))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler == eventHandler);
}
[Test]
public void EventHandler_Multiple()
{
var eventHandler1 = new TestEventHandler();
var eventHandler2 = new UniversalEventHandler();
var eventHandler3 = new TestAsyncEventHandler();
_sut.Act(x => x.Add(eventHandler1))
.Act(x => x.Add<TestEvent>(eventHandler2))
.Act(x => x.Add(eventHandler3))
.ResultOf(x => x.Items)
.Should.ConsistSequentiallyOf(
x => x.EventType == typeof(TestEvent) && x.EventHandler == eventHandler1,
x => x.EventType == typeof(TestEvent) && x.EventHandler == eventHandler2,
x => x.EventType == typeof(TestEvent) && x.EventHandler == eventHandler3);
}
[Test]
public void EventHandlerType_WithSyncEventHandlerType() =>
_sut.Act(x => x.Add(typeof(TestEventHandler)))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestEventHandler);
[Test]
public void EventHandlerType_WithAsyncEventHandlerType() =>
_sut.Act(x => x.Add(typeof(TestAsyncEventHandler)))
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestAsyncEventHandler);
[Test]
public void EventHandlerType_WithInvalidEventHandlerType() =>
_sut.Invoking(x => x.Add(typeof(AtataSessionEventSubscriptionsBuilderTests)))
.Should.ThrowExactly<ArgumentException>();
[Test]
public void EventTypeAndEventHandlerType_WithExactSyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, TestEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestEventHandler);
[Test]
public void EventTypeAndEventHandlerType_WithExactAsyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, TestAsyncEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is TestAsyncEventHandler);
[Test]
public void EventTypeAndEventHandlerType_WithBaseSyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, UniversalEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is UniversalEventHandler);
[Test]
public void EventTypeAndEventHandlerType_WithBaseAsyncEventHandlerType() =>
_sut.Act(x => x.Add<TestEvent, UniversalAsyncEventHandler>())
.ResultOf(x => x.Items)
.Should.ConsistOfSingle(
x => x.EventType == typeof(TestEvent) && x.EventHandler is UniversalAsyncEventHandler);
[Test]
public void EventTypeAndEventHandlerType_WithInvalidEventHandlerType() =>
_sut.Invoking(x => x.Add(typeof(TestEvent), typeof(AtataSessionEventSubscriptionsBuilderTests)))
.Should.ThrowExactly<ArgumentException>();
private static void StubMethod()
{
// Method intentionally left empty.
}
private static Task StubMethodAsync(CancellationToken cancellationToken) =>
Task.CompletedTask;
| Add |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Models/Catalog/CollectionListModel.cs | {
"start": 163,
"end": 569
} | public class ____ : BaseModel
{
[GrandResourceDisplayName("Admin.Catalog.Collections.List.SearchCollectionName")]
public string SearchCollectionName { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Collections.List.SearchStore")]
public string SearchStoreId { get; set; }
public IList<SelectListItem> AvailableStores { get; set; } = new List<SelectListItem>();
} | CollectionListModel |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Attributes/MutationTypeAttribute.cs | {
"start": 124,
"end": 194
} | class ____ an extension of the mutation operation type.
/// </summary>
| as |
csharp | microsoft__semantic-kernel | dotnet/src/SemanticKernel.Abstractions/Filters/Function/FunctionInvocationContext.cs | {
"start": 194,
"end": 2292
} | public class ____
{
/// <summary>
/// Initializes a new instance of the <see cref="FunctionInvocationContext"/> class.
/// </summary>
/// <param name="kernel">The <see cref="Microsoft.SemanticKernel.Kernel"/> containing services, plugins, and other state for use throughout the operation.</param>
/// <param name="function">The <see cref="KernelFunction"/> with which this filter is associated.</param>
/// <param name="arguments">The arguments associated with the operation.</param>
/// <param name="result">The result of the function's invocation.</param>
internal FunctionInvocationContext(Kernel kernel, KernelFunction function, KernelArguments arguments, FunctionResult result)
{
Verify.NotNull(kernel);
Verify.NotNull(function);
Verify.NotNull(arguments);
this.Kernel = kernel;
this.Function = function;
this.Arguments = arguments;
this.Result = result;
}
/// <summary>
/// The <see cref="System.Threading.CancellationToken"/> to monitor for cancellation requests.
/// The default is <see cref="CancellationToken.None"/>.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Boolean flag which indicates whether a filter is invoked within streaming or non-streaming mode.
/// </summary>
public bool IsStreaming { get; init; }
/// <summary>
/// Gets the <see cref="Microsoft.SemanticKernel.Kernel"/> containing services, plugins, and other state for use throughout the operation.
/// </summary>
public Kernel Kernel { get; }
/// <summary>
/// Gets the <see cref="KernelFunction"/> with which this filter is associated.
/// </summary>
public KernelFunction Function { get; }
/// <summary>
/// Gets the arguments associated with the operation.
/// </summary>
public KernelArguments Arguments { get; }
/// <summary>
/// Gets or sets the result of the function's invocation.
/// </summary>
public FunctionResult Result { get; set; }
}
| FunctionInvocationContext |
csharp | moq__moq4 | src/Moq/DefaultValueProvider.cs | {
"start": 344,
"end": 721
} | class ____ default value providers.
/// These are responsible for producing e. g. return values when mock methods or properties get invoked unexpectedly.
/// In other words, whenever there is no setup that would determine the return value for a particular invocation,
/// Moq asks the mock's default value provider to produce a return value.
/// </summary>
| for |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsGetFriendsDeferredTest.cs | {
"start": 137,
"end": 1326
} | public class ____ : ServerTestBase
{
public StarWarsGetFriendsDeferredTest(TestServerFactory serverFactory) : base(serverFactory)
{
}
/*
[Fact]
public async Task Execute_StarWarsGetFriendsDeferred_Test()
{
// arrange
CancellationToken ct = new CancellationTokenSource(20_000).Token;
using IWebHost host = TestServerHelper.CreateServer(
_ => { },
out var port);
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient(
StarWarsGetFriendsDeferredClient.ClientName,
c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"));
serviceCollection.AddWebSocketClient(
StarWarsGetFriendsDeferredClient.ClientName,
c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));
serviceCollection.AddStarWarsGetFriendsDeferredClient();
IServiceProvider services = serviceCollection.BuildServiceProvider();
StarWarsGetFriendsDeferredClient client = services.GetRequiredService<StarWarsGetFriendsDeferredClient>();
// act
// assert
}
*/
}
| StarWarsGetFriendsDeferredTest |
csharp | MassTransit__MassTransit | src/MassTransit/RetryPolicies/IncrementalRetryPolicy.cs | {
"start": 62,
"end": 1847
} | public class ____ :
IRetryPolicy
{
readonly IExceptionFilter _filter;
public IncrementalRetryPolicy(IExceptionFilter filter, int retryLimit, TimeSpan initialInterval,
TimeSpan intervalIncrement)
{
if (initialInterval < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(initialInterval),
"The initialInterval must be non-negative or -1, and it must be less than or equal to TimeSpan.MaxValue.");
}
if (intervalIncrement < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(intervalIncrement),
"The intervalIncrement must be non-negative or -1, and it must be less than or equal to TimeSpan.MaxValue.");
}
_filter = filter;
RetryLimit = retryLimit;
InitialInterval = initialInterval;
IntervalIncrement = intervalIncrement;
}
public int RetryLimit { get; }
public TimeSpan InitialInterval { get; }
public TimeSpan IntervalIncrement { get; }
void IProbeSite.Probe(ProbeContext context)
{
context.Set(new
{
Policy = "Incremental",
Limit = RetryLimit,
Initial = InitialInterval,
Increment = IntervalIncrement
});
_filter.Probe(context);
}
RetryPolicyContext<T> IRetryPolicy.CreatePolicyContext<T>(T context)
{
return new IncrementalRetryPolicyContext<T>(this, context);
}
public bool IsHandled(Exception exception)
{
return _filter.Match(exception);
}
}
}
| IncrementalRetryPolicy |
csharp | nuke-build__nuke | source/Nuke.Build.Tests/SchemaUtilityTest.cs | {
"start": 1468,
"end": 1522
} | private class ____ : NukeBuild
{
}
| EmptyBuild |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/Storage/ReadIndex/GetStreamLastEventNumber_KnownCollisions.cs | {
"start": 811,
"end": 1092
} | public class ____ : GetStreamLastEventNumber_KnownCollisions {
[Test]
public void verify_that_streams_collide() {
Assert.AreEqual(Hasher.Hash(Stream), Hasher.Hash(CollidingStream));
Assert.AreEqual(Hasher.Hash(Stream), Hasher.Hash(CollidingStream1));
}
}
| VerifyCollision |
csharp | dotnet__efcore | src/EFCore/ValueGeneration/ValueGeneratorCache.cs | {
"start": 1773,
"end": 3578
} | struct ____(IProperty property, ITypeBase typeBase) : IEquatable<CacheKey>
{
private readonly Guid _modelId = typeBase.Model.ModelId;
private readonly string? _property = property.Name;
private readonly string? _typeBase = typeBase.Name;
public bool Equals(CacheKey other)
=> (_property!.Equals(other._property, StringComparison.Ordinal)
&& _typeBase!.Equals(other._typeBase, StringComparison.Ordinal)
&& _modelId.Equals(other._modelId));
public override bool Equals(object? obj)
=> obj is CacheKey cacheKey && Equals(cacheKey);
public override int GetHashCode()
=> HashCode.Combine(_property!, _typeBase!, _modelId);
}
/// <summary>
/// Gets the existing value generator from the cache, or creates a new one if one is not present in
/// the cache.
/// </summary>
/// <param name="property">The property to get the value generator for.</param>
/// <param name="typeBase">
/// The entity type that the value generator will be used for. When called on inherited properties on derived entity types,
/// this entity type may be different from the declared entity type on <paramref name="property" />
/// </param>
/// <param name="factory">Factory to create a new value generator if one is not present in the cache.</param>
/// <returns>The existing or newly created value generator.</returns>
public virtual ValueGenerator? GetOrAdd(
IProperty property,
ITypeBase typeBase,
Func<IProperty, ITypeBase, ValueGenerator?> factory)
=> _cache.GetOrAdd(
new CacheKey(property, typeBase), static (ck, p) => p.factory(p.property, p.typeBase), (factory, typeBase, property));
}
| CacheKey |
csharp | files-community__Files | src/Files.App/UserControls/ComboBoxEx/ComboBoxEx.cs | {
"start": 167,
"end": 685
} | public partial class ____ : ComboBox
{
double _cachedWidth;
protected override void OnDropDownOpened(object e)
{
Width = _cachedWidth;
base.OnDropDownOpened(e);
}
protected override void OnDropDownClosed(object e)
{
Width = double.NaN;
base.OnDropDownClosed(e);
}
protected override Size MeasureOverride(Size availableSize)
{
var baseSize = base.MeasureOverride(availableSize);
if (baseSize.Width != 64)
_cachedWidth = baseSize.Width;
return baseSize;
}
}
}
| ComboBoxEx |
csharp | dotnetcore__Util | src/Util.Generators/SystemType.cs | {
"start": 68,
"end": 832
} | public enum ____ {
/// <summary>
/// 全局唯一标识
/// </summary>
Guid,
/// <summary>
/// 字符串
/// </summary>
String,
/// <summary>
/// 字节
/// </summary>
Byte,
/// <summary>
/// 16位整型
/// </summary>
Short,
/// <summary>
/// 32位整型
/// </summary>
Int,
/// <summary>
/// 64位整型
/// </summary>
Long,
/// <summary>
/// 32位浮点型
/// </summary>
Single,
/// <summary>
/// 64位浮点型
/// </summary>
Double,
/// <summary>
/// 128位浮点型
/// </summary>
Decimal,
/// <summary>
/// 布尔
/// </summary>
Bool,
/// <summary>
/// 日期
/// </summary>
DateTime,
/// <summary>
/// 字节流
/// </summary>
Binary
} | SystemType |
csharp | smartstore__Smartstore | src/Smartstore.Web/Areas/Admin/Controllers/DiscountController.cs | {
"start": 465,
"end": 13832
} | public class ____ : AdminController
{
private readonly SmartDbContext _db;
private readonly IRuleService _ruleService;
private readonly ICurrencyService _currencyService;
private readonly ILocalizedEntityService _localizedEntityService;
public DiscountController(
SmartDbContext db,
IRuleService ruleService,
ICurrencyService currencyService,
ILocalizedEntityService localizedEntityService)
{
_db = db;
_ruleService = ruleService;
_currencyService = currencyService;
_localizedEntityService = localizedEntityService;
}
/// <summary>
/// (AJAX) Gets a list of all available discounts.
/// </summary>
/// <param name="label">Text for optional entry. If not null an entry with the specified label text and the Id 0 will be added to the list.</param>
/// <param name="selectedIds">Ids of selected entities.</param>
/// <param name="DiscountType">Specifies the <see cref="DiscountType"/>.</param>
/// <returns>List of all discounts as JSON.</returns>
public async Task<IActionResult> AllDiscounts(string label, string selectedIds, DiscountType? type)
{
var discounts = await _db.Discounts
.AsNoTracking()
.Where(x => x.DiscountTypeId == (int)type)
.ToListAsync();
var selectedArr = selectedIds.ToIntArray();
if (label.HasValue())
{
discounts.Insert(0, new Discount { Name = label, Id = 0 });
}
var data = discounts
.Select(x => new ChoiceListItem
{
Id = x.Id.ToString(),
Text = x.Name,
Selected = selectedArr.Contains(x.Id)
})
.ToList();
return new JsonResult(data);
}
public IActionResult Index()
{
return RedirectToAction(nameof(List));
}
[Permission(Permissions.Promotion.Discount.Read)]
public IActionResult List()
{
return View(new DiscountListModel());
}
[Permission(Permissions.Promotion.Discount.Read)]
public async Task<IActionResult> DiscountList(GridCommand command, DiscountListModel model)
{
var query = _db.Discounts.AsNoTracking();
if (model.SearchName.HasValue())
{
query = query.ApplySearchFilterFor(x => x.Name, model.SearchName);
}
if (model.SearchDiscountTypeId.HasValue)
{
query = query.Where(x => x.DiscountTypeId == model.SearchDiscountTypeId);
}
if (model.SearchUsePercentage.HasValue)
{
query = query.Where(x => x.UsePercentage == model.SearchUsePercentage.Value);
}
if (model.SearchRequiresCouponCode.HasValue)
{
query = query.Where(x => x.RequiresCouponCode == model.SearchRequiresCouponCode.Value);
}
var discounts = await query
.Include(x => x.RuleSets)
.OrderBy(x => x.Name)
.ThenBy(x => x.Id)
.ApplyGridCommand(command)
.ToPagedList(command)
.LoadAsync();
var mapper = MapperFactory.GetMapper<Discount, DiscountModel>();
var rows = await discounts
.SelectAwait(async x => await mapper.MapAsync(x))
.AsyncToList();
return Json(new GridModel<DiscountModel>
{
Rows = rows,
Total = discounts.TotalCount
});
}
[HttpPost]
[Permission(Permissions.Promotion.Discount.Delete)]
public async Task<IActionResult> DiscountDelete(GridSelection selection)
{
var entities = await _db.Discounts.GetManyAsync(selection.GetEntityIds(), true);
if (entities.Count > 0)
{
_db.Discounts.RemoveRange(entities);
await _db.SaveChangesAsync();
Services.ActivityLogger.LogActivity(
KnownActivityLogTypes.DeleteDiscount,
T("ActivityLog.DeleteDiscount"),
string.Join(", ", entities.Select(x => x.Name)));
}
return Json(new { Success = true, entities.Count });
}
[Permission(Permissions.Promotion.Discount.Create)]
public IActionResult Create()
{
var model = new DiscountModel
{
LimitationTimes = 1
};
AddLocales(model.Locales);
PrepareDiscountModel(model, null);
return View(model);
}
[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
[Permission(Permissions.Promotion.Discount.Create)]
public async Task<IActionResult> Create(DiscountModel model, bool continueEditing)
{
if (ModelState.IsValid)
{
var discount = await MapperFactory.MapAsync<DiscountModel, Discount>(model);
discount.CouponCode = discount.CouponCode?.Trim();
_db.Discounts.Add(discount);
await _db.SaveChangesAsync();
await ApplyLocales(model, discount);
await _ruleService.ApplyRuleSetMappingsAsync(discount, model.SelectedRuleSetIds);
await _db.SaveChangesAsync();
Services.ActivityLogger.LogActivity(KnownActivityLogTypes.AddNewDiscount, T("ActivityLog.AddNewDiscount"), discount.Name);
NotifySuccess(T("Admin.Promotions.Discounts.Added"));
return continueEditing
? RedirectToAction(nameof(Edit), new { id = discount.Id })
: RedirectToAction("Index");
}
PrepareDiscountModel(model, null);
return View(model);
}
[Permission(Permissions.Promotion.Discount.Read)]
public async Task<IActionResult> Edit(int id)
{
// INFO: CacheableEntity! Always load "tracked" otherwise RuleSets loaded with old values after saving.
var discount = await _db.Discounts
.AsSplitQuery()
.Include(x => x.RuleSets)
.Include(x => x.AppliedToCategories)
.Include(x => x.AppliedToManufacturers)
.Include(x => x.AppliedToProducts)
.FindByIdAsync(id);
if (discount == null)
{
return NotFound();
}
var model = await MapperFactory.MapAsync<Discount, DiscountModel>(discount);
PrepareDiscountModel(model, discount);
AddLocales(model.Locales, (locale, languageId) =>
{
locale.OfferBadgeLabel = discount.GetLocalized(x => x.OfferBadgeLabel, languageId, false, false);
});
return View(model);
}
[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
[Permission(Permissions.Promotion.Discount.Update)]
public async Task<IActionResult> Edit(DiscountModel model, bool continueEditing)
{
var discount = await _db.Discounts
.AsSplitQuery()
.Include(x => x.RuleSets)
.Include(x => x.AppliedToCategories)
.Include(x => x.AppliedToManufacturers)
.Include(x => x.AppliedToProducts)
.FindByIdAsync(model.Id);
if (discount == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
await MapperFactory.MapAsync(model, discount);
discount.CouponCode = discount.CouponCode?.Trim();
await ApplyLocales(model, discount);
await _ruleService.ApplyRuleSetMappingsAsync(discount, model.SelectedRuleSetIds);
await _db.SaveChangesAsync();
Services.ActivityLogger.LogActivity(KnownActivityLogTypes.EditDiscount, T("ActivityLog.EditDiscount"), discount.Name);
NotifySuccess(T("Admin.Promotions.Discounts.Updated"));
return continueEditing
? RedirectToAction(nameof(Edit), new { id = discount.Id })
: RedirectToAction("Index");
}
PrepareDiscountModel(model, discount);
return View(model);
}
[HttpPost]
[Permission(Permissions.Promotion.Discount.Delete)]
public async Task<IActionResult> Delete(int id)
{
var discount = await _db.Discounts.FindByIdAsync(id);
if (discount == null)
{
return NotFound();
}
_db.Discounts.Remove(discount);
await _db.SaveChangesAsync();
Services.ActivityLogger.LogActivity(KnownActivityLogTypes.DeleteDiscount, T("ActivityLog.DeleteDiscount"), discount.Name);
NotifySuccess(T("Admin.Promotions.Discounts.Deleted"));
return RedirectToAction(nameof(List));
}
#region Discount usage history
[Permission(Permissions.Promotion.Discount.Read)]
public async Task<IActionResult> DiscountUsageHistoryList(GridCommand command, int discountId)
{
var historyEntries = await _db.DiscountUsageHistory
.AsNoTracking()
.Where(x => x.DiscountId == discountId)
.OrderByDescending(x => x.CreatedOnUtc)
.ApplyGridCommand(command, false)
.ToPagedList(command)
.LoadAsync();
var rows = historyEntries
.Select(x => new DiscountUsageHistoryModel
{
Id = x.Id,
DiscountId = x.DiscountId,
OrderId = x.OrderId,
CreatedOnUtc = x.CreatedOnUtc,
CreatedOn = Services.DateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc),
OrderEditUrl = Url.Action("Edit", "Order", new { id = x.OrderId, area = "Admin" }),
OrderEditLinkText = T("Admin.Common.ViewObject", x.OrderId)
})
.ToList();
return Json(new GridModel<DiscountUsageHistoryModel>
{
Rows = rows,
Total = historyEntries.TotalCount
});
}
[Permission(Permissions.Promotion.Discount.Update)]
public async Task<IActionResult> DiscountUsageHistoryDelete(GridSelection selection)
{
var success = false;
var numDeleted = 0;
var ids = selection.GetEntityIds();
if (ids.Any())
{
var historyEntries = await _db.DiscountUsageHistory.GetManyAsync(ids, true);
_db.DiscountUsageHistory.RemoveRange(historyEntries);
numDeleted = await _db.SaveChangesAsync();
success = true;
}
return Json(new { Success = success, Count = numDeleted });
}
#endregion
private void PrepareDiscountModel(DiscountModel model, Discount discount)
{
if (discount != null)
{
var language = Services.WorkContext.WorkingLanguage;
model.SelectedRuleSetIds = discount.RuleSets.Select(x => x.Id).ToArray();
ViewBag.AppliedToCategories = discount.AppliedToCategories
.Where(x => x != null && !x.Deleted)
.Select(x => new DiscountAppliedToEntityModel { Id = x.Id, Name = x.GetLocalized(y => y.Name, language) })
.ToList();
ViewBag.AppliedToManufacturers = discount.AppliedToManufacturers
.Where(x => x != null && !x.Deleted)
.Select(x => new DiscountAppliedToEntityModel { Id = x.Id, Name = x.GetLocalized(y => y.Name, language) })
.ToList();
ViewBag.AppliedToProducts = discount.AppliedToProducts
.Where(x => x != null && !x.Deleted)
.Select(x => new DiscountAppliedToEntityModel { Id = x.Id, Name = x.GetLocalized(y => y.Name, language) })
.ToList();
}
else
{
ViewBag.AppliedToCategories = new List<DiscountAppliedToEntityModel>();
ViewBag.AppliedToManufacturers = new List<DiscountAppliedToEntityModel>();
ViewBag.AppliedToProducts = new List<DiscountAppliedToEntityModel>();
}
ViewBag.PrimaryStoreCurrencyCode = _currencyService.PrimaryCurrency.CurrencyCode;
}
private async Task ApplyLocales(DiscountModel model, Discount discount)
{
foreach (var localized in model.Locales)
{
await _localizedEntityService.ApplyLocalizedValueAsync(discount, x => x.OfferBadgeLabel, localized.OfferBadgeLabel, localized.LanguageId);
}
}
}
}
| DiscountController |
csharp | microsoft__PowerToys | src/modules/launcher/Wox.Infrastructure/Hotkey/KeyEvent.cs | {
"start": 226,
"end": 640
} | public enum ____
{
/// <summary>
/// Key down
/// </summary>
WMKEYDOWN = 256,
/// <summary>
/// Key up
/// </summary>
WMKEYUP = 257,
/// <summary>
/// System key up
/// </summary>
WMSYSKEYUP = 261,
/// <summary>
/// System key down
/// </summary>
WMSYSKEYDOWN = 260,
}
}
| KeyEvent |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/src/core/Allocator/BlittableAllocator.cs | {
"start": 476,
"end": 9991
} | class ____ all data and most actual functionality. This must be the ONLY field in this structure so its size is sizeof(IntPtr).</summary>
private readonly BlittableAllocatorImpl<TKey, TValue, TStoreFunctions> _this;
public BlittableAllocator(AllocatorSettings settings, TStoreFunctions storeFunctions)
{
// Called by TsavoriteKV via allocatorCreator; must pass a wrapperCreator to AllocatorBase
_this = new(settings, storeFunctions, @this => new BlittableAllocator<TKey, TValue, TStoreFunctions>(@this));
}
public BlittableAllocator(object @this)
{
// Called by AllocatorBase via primary ctor wrapperCreator
_this = (BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>)@this;
}
/// <inheritdoc/>
public readonly AllocatorBase<TKey, TValue, TStoreFunctions, TAllocator> GetBase<TAllocator>()
where TAllocator : IAllocator<TKey, TValue, TStoreFunctions>
=> (AllocatorBase<TKey, TValue, TStoreFunctions, TAllocator>)(object)_this;
/// <inheritdoc/>
public readonly bool IsFixedLength => true;
/// <inheritdoc/>
public readonly bool HasObjectLog => false;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly long GetStartLogicalAddress(long page) => _this.GetStartLogicalAddress(page);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly long GetFirstValidLogicalAddress(long page) => _this.GetFirstValidLogicalAddress(page);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly long GetPhysicalAddress(long logicalAddress) => _this.GetPhysicalAddress(logicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ref RecordInfo GetInfo(long physicalAddress)
=> ref BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetInfo(physicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe ref RecordInfo GetInfoFromBytePointer(byte* ptr)
=> ref BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetInfoFromBytePointer(ptr);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ref TKey GetKey(long physicalAddress)
=> ref BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetKey(physicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ref TValue GetValue(long physicalAddress)
=> ref BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetValue(physicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ref TValue GetAndInitializeValue(long physicalAddress, long endPhysicalAddress) => ref GetValue(physicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly (int actualSize, int allocatedSize) GetRecordSize(long physicalAddress)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetRecordSize(physicalAddress);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly (int actualSize, int allocatedSize, int keySize) GetRMWCopyDestinationRecordSize<TInput, TVariableLengthInput>(ref TKey key, ref TInput input, ref TValue value, ref RecordInfo recordInfo, TVariableLengthInput varlenInput)
where TVariableLengthInput : IVariableLengthInput<TValue, TInput>
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetRMWCopyDestinationRecordSize(ref key, ref input, ref value, ref recordInfo, varlenInput);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (int actualSize, int allocatedSize, int keySize) GetTombstoneRecordSize(ref TKey key)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetTombstoneRecordSize(ref key);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int GetRequiredRecordSize(long physicalAddress, int availableBytes) => GetAverageRecordSize();
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int GetAverageRecordSize()
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetAverageRecordSize();
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int GetFixedRecordSize()
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetFixedRecordSize();
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly (int actualSize, int allocatedSize, int keySize) GetRMWInitialRecordSize<TInput, TSessionFunctionsWrapper>(ref TKey key, ref TInput input, TSessionFunctionsWrapper sessionFunctions)
where TSessionFunctionsWrapper : IVariableLengthInput<TValue, TInput>
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetRMWInitialRecordSize(ref key, ref input, sessionFunctions);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly (int actualSize, int allocatedSize, int keySize) GetUpsertRecordSize<TInput, TSessionFunctionsWrapper>(ref TKey key, ref TValue value, ref TInput input, TSessionFunctionsWrapper sessionFunctions)
where TSessionFunctionsWrapper : IVariableLengthInput<TValue, TInput>
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetUpsertRecordSize(ref key, ref value, ref input, sessionFunctions);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly (int actualSize, int allocatedSize, int keySize) GetRecordSize(ref TKey key, ref TValue value)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetRecordSize(ref key, ref value);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int GetValueLength(ref TValue value)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetValueLength(ref value);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe bool RetrievedFullRecord(byte* record, ref AsyncIOContext<TKey, TValue> ctx)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.RetrievedFullRecord(record, ref ctx);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void AllocatePage(int pageIndex) => _this.AllocatePage(pageIndex);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool IsAllocated(int pageIndex) => _this.IsAllocated(pageIndex);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe void PopulatePage(byte* src, int required_bytes, long destinationPageIndex)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.PopulatePage(src, required_bytes, destinationPageIndex);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void MarkPage(long logicalAddress, long version) => _this.MarkPage(logicalAddress, version);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void MarkPageAtomic(long logicalAddress, long version) => _this.MarkPageAtomic(logicalAddress, version);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void ClearPage(long page, int offset = 0) => _this.ClearPage(page, offset);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void FreePage(long pageIndex) => _this.FreePage(pageIndex);
/// <inheritdoc/>
public readonly ref TKey GetContextRecordKey(ref AsyncIOContext<TKey, TValue> ctx) => ref ctx.key;
/// <inheritdoc/>
public readonly ref TValue GetContextRecordValue(ref AsyncIOContext<TKey, TValue> ctx) => ref ctx.value;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly IHeapContainer<TKey> GetKeyContainer(ref TKey key) => new StandardHeapContainer<TKey>(ref key);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly IHeapContainer<TValue> GetValueContainer(ref TValue value) => new StandardHeapContainer<TValue>(ref value);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly long[] GetSegmentOffsets()
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.GetSegmentOffsets();
/// <inheritdoc/>
public readonly int OverflowPageCount => _this.OverflowPageCount;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void SerializeKey(ref TKey key, long physicalAddress)
=> BlittableAllocatorImpl<TKey, TValue, TStoreFunctions>.SerializeKey(ref key, physicalAddress);
}
} | containing |
csharp | unoplatform__uno | src/Uno.UI.Runtime.Skia.MacOS/Builder/HostBuilder.cs | {
"start": 204,
"end": 406
} | public static class ____
{
public static IUnoPlatformHostBuilder UseMacOS(this IUnoPlatformHostBuilder builder)
{
builder.AddHostBuilder(() => new MacOSHostBuilder());
return builder;
}
}
| HostBuilder |
csharp | abpframework__abp | framework/src/Volo.Abp.AzureServiceBus/Volo/Abp/AzureServiceBus/PublisherPool.cs | {
"start": 293,
"end": 1937
} | public class ____ : IPublisherPool, ISingletonDependency
{
public ILogger<PublisherPool> Logger { get; set; }
private bool _isDisposed;
private readonly IConnectionPool _connectionPool;
private readonly ConcurrentDictionary<string, Lazy<ServiceBusSender>> _publishers;
public PublisherPool(IConnectionPool connectionPool)
{
_connectionPool = connectionPool;
_publishers = new ConcurrentDictionary<string, Lazy<ServiceBusSender>>();
Logger = new NullLogger<PublisherPool>();
}
public async Task<ServiceBusSender> GetAsync(string topicName, string? connectionName)
{
var admin = _connectionPool.GetAdministrationClient(connectionName);
await admin.SetupTopicAsync(topicName);
return _publishers.GetOrAdd(
topicName, new Lazy<ServiceBusSender>(() =>
{
var client = _connectionPool.GetClient(connectionName);
return client.CreateSender(topicName);
})
).Value;
}
public async ValueTask DisposeAsync()
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
if (!_publishers.Any())
{
Logger.LogDebug($"Disposed publisher pool with no publisher in the pool.");
return;
}
Logger.LogInformation($"Disposing publisher pool ({_publishers.Count} publishers).");
foreach (var publisher in _publishers.Values)
{
await publisher.Value.CloseAsync();
await publisher.Value.DisposeAsync();
}
_publishers.Clear();
}
}
| PublisherPool |
csharp | dotnet__aspire | src/Aspire.Hosting/api/Aspire.Hosting.cs | {
"start": 17185,
"end": 19116
} | partial class ____
{
public static ApplicationModel.IResourceBuilder<ApplicationModel.ExecutableResource> AddExecutable(this IDistributedApplicationBuilder builder, string name, string command, string workingDirectory, params object[]? args) { throw null; }
public static ApplicationModel.IResourceBuilder<ApplicationModel.ExecutableResource> AddExecutable(this IDistributedApplicationBuilder builder, string name, string command, string workingDirectory, params string[]? args) { throw null; }
public static ApplicationModel.IResourceBuilder<T> PublishAsDockerFile<T>(this ApplicationModel.IResourceBuilder<T> builder, System.Action<ApplicationModel.IResourceBuilder<ApplicationModel.ContainerResource>>? configure)
where T : ApplicationModel.ExecutableResource { throw null; }
[System.Obsolete("Use builder.PublishAsDockerFile(c => c.WithBuildArg(name, value)) instead.")]
public static ApplicationModel.IResourceBuilder<T> PublishAsDockerFile<T>(this ApplicationModel.IResourceBuilder<T> builder, System.Collections.Generic.IEnumerable<ApplicationModel.DockerBuildArg>? buildArgs)
where T : ApplicationModel.ExecutableResource { throw null; }
public static ApplicationModel.IResourceBuilder<T> PublishAsDockerFile<T>(this ApplicationModel.IResourceBuilder<T> builder)
where T : ApplicationModel.ExecutableResource { throw null; }
public static ApplicationModel.IResourceBuilder<T> WithCommand<T>(this ApplicationModel.IResourceBuilder<T> builder, string command)
where T : ApplicationModel.ExecutableResource { throw null; }
public static ApplicationModel.IResourceBuilder<T> WithWorkingDirectory<T>(this ApplicationModel.IResourceBuilder<T> builder, string workingDirectory)
where T : ApplicationModel.ExecutableResource { throw null; }
}
public static | ExecutableResourceBuilderExtensions |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Users.Core/Services/UserService.cs | {
"start": 489,
"end": 14599
} | public sealed class ____ : IUserService
{
private readonly SignInManager<IUser> _signInManager;
private readonly UserManager<IUser> _userManager;
private readonly IdentityOptions _identityOptions;
private readonly IEnumerable<IPasswordRecoveryFormEvents> _passwordRecoveryFormEvents;
private readonly IEnumerable<IRegistrationFormEvents> _registrationFormEvents;
private readonly RegistrationOptions _registrationOptions;
private readonly ISiteService _siteService;
private readonly IEnumerable<IUserEventHandler> _handlers;
private readonly ILogger _logger;
internal readonly IStringLocalizer S;
public UserService(
SignInManager<IUser> signInManager,
UserManager<IUser> userManager,
IOptions<IdentityOptions> identityOptions,
IEnumerable<IPasswordRecoveryFormEvents> passwordRecoveryFormEvents,
IEnumerable<IRegistrationFormEvents> registrationFormEvents,
IOptions<RegistrationOptions> registrationOptions,
ISiteService siteService,
IEnumerable<IUserEventHandler> handlers,
ILogger<UserService> logger,
IStringLocalizer<UserService> stringLocalizer)
{
_signInManager = signInManager;
_userManager = userManager;
_identityOptions = identityOptions.Value;
_passwordRecoveryFormEvents = passwordRecoveryFormEvents;
_registrationFormEvents = registrationFormEvents;
_registrationOptions = registrationOptions.Value;
_siteService = siteService;
_handlers = handlers;
_logger = logger;
S = stringLocalizer;
}
public async Task<IUser> AuthenticateAsync(string usernameOrEmail, string password, Action<string, string> reportError)
{
var disableLocalLogin = (await _siteService.GetSettingsAsync<LoginSettings>()).DisableLocalLogin;
if (disableLocalLogin)
{
reportError(string.Empty, S["Local login is disabled."]);
return null;
}
if (string.IsNullOrWhiteSpace(usernameOrEmail))
{
reportError("Username", S["A user name is required."]);
return null;
}
if (string.IsNullOrWhiteSpace(password))
{
reportError("Password", S["A password is required."]);
return null;
}
var user = await GetUserAsync(usernameOrEmail);
if (user == null)
{
reportError(string.Empty, S["The specified username/password couple is invalid."]);
return null;
}
var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true);
if (result.IsLockedOut)
{
reportError(string.Empty, S["The user is locked out."]);
return null;
}
else if (result.IsNotAllowed)
{
reportError(string.Empty, S["The specified user is not allowed to sign in."]);
return null;
}
else if (result.RequiresTwoFactor)
{
reportError(string.Empty, S["The specified user is not allowed to sign in using password authentication."]);
return null;
}
else if (!result.Succeeded)
{
reportError(string.Empty, S["The specified username/password couple is invalid."]);
return null;
}
if (!(user as User).IsEnabled)
{
reportError(string.Empty, S["The specified user is not allowed to sign in."]);
return null;
}
return user;
}
public async Task<IUser> CreateUserAsync(IUser user, string password, Action<string, string> reportError)
{
if (user is not User newUser)
{
throw new ArgumentException("Expected a User instance.", nameof(user));
}
var hasPassword = !string.IsNullOrWhiteSpace(password);
// Accounts can be created with no password.
var identityResult = hasPassword
? await _userManager.CreateAsync(user, password)
: await _userManager.CreateAsync(user);
if (!identityResult.Succeeded)
{
if (hasPassword)
{
_logger.LogInformation("Unable to create a new account with password.");
}
else
{
_logger.LogInformation("Unable to create a new account with no password.");
}
ProcessValidationErrors(identityResult.Errors, newUser, reportError);
return null;
}
if (hasPassword)
{
_logger.LogInformation("User created a new account with password.");
}
else
{
_logger.LogInformation("User created a new account with no password.");
}
return user;
}
public async Task<bool> ChangeEmailAsync(IUser user, string newEmail, Action<string, string> reportError)
{
var token = await _userManager.GenerateChangeEmailTokenAsync(user, newEmail);
var identityResult = await _userManager.ChangeEmailAsync(user, newEmail, token);
if (!identityResult.Succeeded)
{
ProcessValidationErrors(identityResult.Errors, (User)user, reportError);
}
return identityResult.Succeeded;
}
public async Task<bool> ChangePasswordAsync(IUser user, string currentPassword, string newPassword, Action<string, string> reportError)
{
var identityResult = await _userManager.ChangePasswordAsync(user, currentPassword, newPassword);
if (!identityResult.Succeeded)
{
ProcessValidationErrors(identityResult.Errors, (User)user, reportError);
}
return identityResult.Succeeded;
}
public Task<IUser> GetAuthenticatedUserAsync(ClaimsPrincipal principal)
{
if (principal == null)
{
return Task.FromResult<IUser>(null);
}
return _userManager.GetUserAsync(principal);
}
public async Task<IUser> GetForgotPasswordUserAsync(string userId)
{
if (string.IsNullOrWhiteSpace(userId))
{
return null;
}
var user = await GetUserAsync(userId);
if (user == null)
{
return null;
}
if (user is User u)
{
u.ResetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
}
return user;
}
public async Task<bool> ResetPasswordAsync(string usernameOrEmail, string resetToken, string newPassword, Action<string, string> reportError)
{
var result = true;
if (string.IsNullOrWhiteSpace(usernameOrEmail))
{
reportError(nameof(ResetPasswordForm.UsernameOrEmail), S["A username or email address is required."]);
result = false;
}
if (string.IsNullOrWhiteSpace(newPassword))
{
reportError(nameof(ResetPasswordForm.NewPassword), S["A password is required."]);
result = false;
}
if (string.IsNullOrWhiteSpace(resetToken))
{
reportError(nameof(ResetPasswordForm.ResetToken), S["A token is required."]);
result = false;
}
if (!result)
{
return result;
}
var user = await GetUserAsync(usernameOrEmail) as User;
if (user == null)
{
return false;
}
var identityResult = await _userManager.ResetPasswordAsync(user, resetToken, newPassword);
if (!identityResult.Succeeded)
{
ProcessValidationErrors(identityResult.Errors, user, reportError);
}
if (identityResult.Succeeded)
{
var context = new PasswordRecoveryContext(user);
await _passwordRecoveryFormEvents.InvokeAsync((handler, context) => handler.PasswordResetAsync(context), context, _logger);
}
return identityResult.Succeeded;
}
public Task<ClaimsPrincipal> CreatePrincipalAsync(IUser user)
{
if (user == null)
{
return Task.FromResult<ClaimsPrincipal>(null);
}
return _signInManager.CreateUserPrincipalAsync(user);
}
public async Task<IUser> GetUserAsync(string usernameOrEmail)
{
var user = await _userManager.FindByNameAsync(usernameOrEmail);
if (user is null && _identityOptions.User.RequireUniqueEmail)
{
user = await _userManager.FindByEmailAsync(usernameOrEmail);
}
return user;
}
public Task<IUser> GetUserByUniqueIdAsync(string userId)
=> _userManager.FindByIdAsync(userId);
public void ProcessValidationErrors(IEnumerable<IdentityError> errors, User user, Action<string, string> reportError)
{
foreach (var error in errors)
{
switch (error.Code)
{
// Password.
case "PasswordRequiresDigit":
reportError("Password", S["Passwords must have at least one digit character ('0'-'9')."]);
break;
case "PasswordRequiresLower":
reportError("Password", S["Passwords must have at least one lowercase character ('a'-'z')."]);
break;
case "PasswordRequiresUpper":
reportError("Password", S["Passwords must have at least one uppercase character ('A'-'Z')."]);
break;
case "PasswordRequiresNonAlphanumeric":
reportError("Password", S["Passwords must have at least one non letter or digit character."]);
break;
case "PasswordTooShort":
reportError("Password", S["Passwords must be at least {0} characters.", _identityOptions.Password.RequiredLength]);
break;
case "PasswordRequiresUniqueChars":
reportError("Password", S["Passwords must contain at least {0} unique characters.", _identityOptions.Password.RequiredUniqueChars]);
break;
// CurrentPassword.
case "PasswordMismatch":
reportError("CurrentPassword", S["Incorrect password."]);
break;
// User name.
case "InvalidUserName":
reportError("UserName", S["User name '{0}' is invalid, can only contain letters or digits.", user.UserName]);
break;
case "DuplicateUserName":
reportError("UserName", S["User name '{0}' is already used.", user.UserName]);
break;
// Email.
case "DuplicateEmail":
reportError("Email", S["Email '{0}' is already used.", user.Email]);
break;
case "InvalidEmail":
reportError("Email", S["Email '{0}' is invalid.", user.Email]);
break;
case "InvalidToken":
reportError(string.Empty, S["The reset token is invalid. Please request a new token."]);
break;
default:
reportError(string.Empty, S["Unexpected error: '{0}'.", error.Code]);
break;
}
}
}
public async Task<IUser> RegisterAsync(RegisterUserForm model, Action<string, string> reportError)
{
await _registrationFormEvents.InvokeAsync((e, report) => e.RegistrationValidationAsync((key, message) => report(key, message)), reportError, _logger);
var user = await CreateUserAsync(new User
{
UserName = model.UserName,
Email = model.Email,
EmailConfirmed = !_registrationOptions.UsersMustValidateEmail,
IsEnabled = !_registrationOptions.UsersAreModerated,
}, model.Password, reportError);
if (user == null)
{
return null;
}
var context = new UserRegisteringContext(user);
await _registrationFormEvents.InvokeAsync((e, ctx) => e.RegisteringAsync(ctx), context, _logger);
if (!context.CancelSignIn)
{
await _signInManager.SignInAsync(user, isPersistent: false);
}
await _registrationFormEvents.InvokeAsync((e, user) => e.RegisteredAsync(user), user, _logger);
return user;
}
/// <inheritdoc/>
public async Task<bool> EnableAsync(IUser user)
{
ArgumentNullException.ThrowIfNull(user);
if (user is User u)
{
if (u.IsEnabled)
{
return true;
}
u.IsEnabled = true;
}
var result = await _userManager.UpdateAsync(user);
if (result.Succeeded)
{
var userContext = new UserContext(user);
await _handlers.InvokeAsync((handler, context) => handler.EnabledAsync(context), userContext, _logger);
}
return result.Succeeded;
}
/// <inheritdoc/>
public async Task<bool> DisableAsync(IUser user)
{
ArgumentNullException.ThrowIfNull(user);
var enabledUsersOfAdminRole = (await _userManager.GetUsersInRoleAsync(OrchardCoreConstants.Roles.Administrator))
.Cast<User>()
.Where(user => user.IsEnabled)
.Take(2)
.ToList();
if (enabledUsersOfAdminRole.Count == 1 && user.UserName == enabledUsersOfAdminRole.First().UserName)
{
return false;
}
if (user is User u)
{
if (!u.IsEnabled)
{
return true;
}
u.IsEnabled = false;
}
var result = await _userManager.UpdateAsync(user);
if (result.Succeeded)
{
var userContext = new UserContext(user);
await _handlers.InvokeAsync((handler, context) => handler.DisabledAsync(context), userContext, _logger);
}
return result.Succeeded;
}
}
| UserService |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Formatters.Xml/test/XmlSerializerInputFormatterTest.cs | {
"start": 782,
"end": 28355
} | public class ____
{
public string SampleString { get; set; }
public TestLevelOne TestOne { get; set; }
}
[Fact]
public async Task BuffersRequestBody_ByDefault()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature());
httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: true);
httpContext.Request.ContentType = "application/json";
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
}
[Fact]
public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody_ObsoleteParameter()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions { SuppressInputFormatterBuffering = true });
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature());
httpContext.Request.Body = new NonSeekableReadStream(contentBytes);
httpContext.Request.ContentType = "application/xml";
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
}
[Fact]
public async Task BuffersRequestBody_ByDefaultUsingMvcOptions()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature());
httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: false);
httpContext.Request.ContentType = "application/json";
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
}
[Fact]
public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions() { SuppressInputFormatterBuffering = true });
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature());
httpContext.Request.Body = new NonSeekableReadStream(contentBytes);
httpContext.Request.ContentType = "application/xml";
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
// Reading again should fail as buffering request body is disabled
await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context));
}
[Fact]
public async Task SuppressInputFormatterBufferingSetToTrue_UsingMutatedOptions()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var mvcOptions = new MvcOptions();
mvcOptions.SuppressInputFormatterBuffering = false;
var formatter = new XmlSerializerInputFormatter(mvcOptions);
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature());
httpContext.Request.Body = new NonSeekableReadStream(contentBytes);
httpContext.Request.ContentType = "application/xml";
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
// Mutate options after passing into the constructor to make sure that the value type is not store in the constructor
mvcOptions.SuppressInputFormatterBuffering = true;
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
// Reading again should fail as buffering request body is disabled
await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context));
}
[Theory]
[InlineData("application/xml", true)]
[InlineData("application/*", false)]
[InlineData("*/*", false)]
[InlineData("text/xml", true)]
[InlineData("text/*", false)]
[InlineData("text/json", false)]
[InlineData("application/json", false)]
[InlineData("application/some.entity+xml", true)]
[InlineData("application/some.entity+xml;v=2", true)]
[InlineData("application/some.entity+json", false)]
[InlineData("application/some.entity+*", false)]
[InlineData("text/some.entity+json", false)]
[InlineData("", false)]
[InlineData("invalid", false)]
[InlineData(null, false)]
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
{
// Arrange
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes("content");
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(string));
var formatterContext = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act
var result = formatter.CanRead(formatterContext);
// Assert
Assert.Equal(expectedCanRead, result);
}
[Theory]
[InlineData(typeof(Dictionary<string, object>), false)]
[InlineData(typeof(string), true)]
public void CanRead_ReturnsFalse_ForAnyUnsupportedModelType(Type modelType, bool expectedCanRead)
{
// Arrange
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes("content");
var context = GetInputFormatterContext(contentBytes, modelType);
// Act
var result = formatter.CanRead(context);
// Assert
Assert.Equal(expectedCanRead, result);
}
[Fact]
public void XmlSerializer_CachesSerializerForType()
{
// Arrange
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>10</SampleInt></DummyClass>";
var formatter = new TestXmlSerializerInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));
// Act
formatter.CanRead(context);
formatter.CanRead(context);
// Assert
Assert.Equal(1, formatter.createSerializerCalledCount);
}
[Fact]
public void HasProperSupportedMediaTypes()
{
// Arrange & Act
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
// Assert
Assert.Contains("application/xml", formatter.SupportedMediaTypes
.Select(content => content.ToString()));
Assert.Contains("text/xml", formatter.SupportedMediaTypes
.Select(content => content.ToString()));
}
[Fact]
public void HasProperSupportedEncodings()
{
// Arrange & Act
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
// Assert
Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-8");
Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-16");
}
[Fact]
public async Task ReadAsync_ReadsSimpleTypes()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.SampleDate);
}
[Fact]
public async Task ReadAsync_ReadsComplexTypes()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var expectedLevelTwoString = "102";
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelTwo><SampleString>" + expectedLevelTwoString + "</SampleString>" +
"<TestOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestOne></TestLevelTwo>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelTwo>(result.Model);
Assert.Equal(expectedLevelTwoString, model.SampleString);
Assert.Equal(expectedInt, model.TestOne.SampleInt);
Assert.Equal(expectedString, model.TestOne.sampleString);
Assert.Equal(
XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc),
model.TestOne.SampleDate);
}
[Fact]
public async Task ReadAsync_ReadsWhenMaxDepthIsModified()
{
// Arrange
var expectedInt = 10;
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
formatter.MaxDepth = 10;
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<DummyClass>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
}
[ConditionalFact]
// ReaderQuotas are not honored on Mono
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ThrowsOnExceededMaxDepth()
{
// Arrange
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelTwo><SampleString>test</SampleString>" +
"<TestOne><SampleInt>10</SampleInt>" +
"<sampleString>test</sampleString>" +
"<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc)
+ "</SampleDate></TestOne></TestLevelTwo>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
formatter.MaxDepth = 1;
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));
// Act & Assert
await Assert.ThrowsAsync<InputFormatterException>(() => formatter.ReadAsync(context));
}
[ConditionalFact]
// ReaderQuotas are not honored on Mono
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged()
{
// Arrange
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelTwo><SampleString>test</SampleString>" +
"<TestOne><SampleInt>10</SampleInt>" +
"<sampleString>test</sampleString>" +
"<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc)
+ "</SampleDate></TestOne></TestLevelTwo>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 10;
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));
// Act & Assert
await Assert.ThrowsAsync<InputFormatterException>(() => formatter.ReadAsync(context));
}
[Fact]
public void SetMaxDepth_ThrowsWhenMaxDepthIsBelowOne()
{
// Arrange
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
// Act & Assert
Assert.Throws<ArgumentOutOfRangeException>(() => formatter.MaxDepth = 0);
}
[Fact]
public async Task ReadAsync_VerifyStreamIsOpenAfterRead()
{
// Arrange
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>10</SampleInt></DummyClass>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
Assert.NotNull(result.Model);
Assert.True(context.HttpContext.Request.Body.CanRead);
}
[ReplaceCulture]
[Fact]
public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType()
{
// Arrange
var expectedException = typeof(XmlException);
var expectedMessage = "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'.";
var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
"<DummyClass><SampleInt>");
byte[] inp = { 192, 193 };
var inpEnd = Encoding.Unicode.GetBytes("</SampleInt></DummyClass>");
var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length];
Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length);
Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length);
Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length);
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));
// Act and Assert
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message);
}
[Fact]
[ReplaceCulture]
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
{
// Arrange
var expectedException = typeof(XmlException);
var expectedMessage = "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>1000</SampleInt></DummyClass>");
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(TestLevelOne));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act and Assert
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message);
}
[Fact]
public async Task ReadAsync_IgnoresBOMCharacters()
{
// Arrange
var sampleString = "Test";
var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString);
var inputStart = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine +
"<TestLevelTwo><SampleString>" + sampleString);
byte[] bom = { 0xef, 0xbb, 0xbf };
var inputEnd = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>");
var expectedBytes = new byte[sampleString.Length + bom.Length];
var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length];
Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length);
Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length);
Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length);
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelTwo>(result.Model);
Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length);
Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length);
Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString));
}
[Fact]
public async Task ReadAsync_AcceptsUTF16Characters()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString>" +
"<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.Unicode.GetBytes(input);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(TestLevelOne));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate);
}
[Fact]
public async Task ReadAsync_DoesNotDisposeBufferedStreamIfItDidNotCreateIt()
{
// Arrange
var expectedInt = 10;
var expectedString = "TestString";
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
"<sampleString>" + expectedString + "</sampleString></TestLevelOne>";
var formatter = new XmlSerializerInputFormatter(new MvcOptions());
var contentBytes = Encoding.UTF8.GetBytes(input);
var httpContext = new DefaultHttpContext();
var testBufferedReadStream = new VerifyDisposeFileBufferingReadStream(new MemoryStream(contentBytes), 1024);
httpContext.Request.Body = testBufferedReadStream;
var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.NotNull(result);
Assert.False(result.HasError);
var model = Assert.IsType<TestLevelOne>(result.Model);
Assert.Equal(expectedInt, model.SampleInt);
Assert.Equal(expectedString, model.sampleString);
Assert.False(testBufferedReadStream.Disposed);
}
private InputFormatterContext GetInputFormatterContext(byte[] contentBytes, Type modelType)
{
var httpContext = GetHttpContext(contentBytes);
return GetInputFormatterContext(httpContext, modelType);
}
private InputFormatterContext GetInputFormatterContext(HttpContext httpContext, Type modelType)
{
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(modelType);
return new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: new ModelStateDictionary(),
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
}
private static HttpContext GetHttpContext(
byte[] contentBytes,
string contentType = "application/xml")
{
var request = new Mock<HttpRequest>();
var headers = new Mock<IHeaderDictionary>();
request.SetupGet(r => r.Headers).Returns(headers.Object);
request.SetupGet(f => f.Body).Returns(new MemoryStream(contentBytes));
request.SetupGet(f => f.ContentType).Returns(contentType);
request.SetupGet(f => f.ContentLength).Returns(contentBytes.Length);
var httpContext = new Mock<HttpContext>();
var features = new Mock<IFeatureCollection>();
httpContext.SetupGet(c => c.Request).Returns(request.Object);
httpContext.SetupGet(c => c.Features).Returns(features.Object);
return httpContext.Object;
}
| TestLevelTwo |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Query/IncludeOneToOneInMemoryTest.cs | {
"start": 186,
"end": 396
} | public class ____(IncludeOneToOneInMemoryTest.OneToOneQueryInMemoryFixture fixture)
: IncludeOneToOneTestBase<IncludeOneToOneInMemoryTest.OneToOneQueryInMemoryFixture>(fixture)
{
| IncludeOneToOneInMemoryTest |
csharp | VerifyTests__Verify | src/Verify.XunitV3.Tests/AttachmentTests.cs | {
"start": 1,
"end": 1286
} | public class ____
{
#if NET10_0
[Fact]
public async Task Simple()
{
var path = CurrentFile.Relative("AttachmentTests.Simple.verified.txt");
var fullPath = Path.GetFullPath(path);
File.Delete(fullPath);
await Verify("Foo").AutoVerify();
File.Delete(fullPath);
var attachments = TestContext.Current.Attachments!;
Assert.Contains(attachments.Keys,
_ => _.Contains("Verify snapshot mismatch") &&
_.Contains("AttachmentTests.Simple."));
}
[Fact]
public async Task NestedWithSameName()
{
var path = CurrentFile.Relative("AttachmentTests");
var fullPath = Path.GetFullPath(path);
Delete();
await Verify("Foo")
.UseDirectory("AttachmentTests")
.UseMethodName("Simple")
.AutoVerify();
Delete();
void Delete()
{
if (Directory.Exists(fullPath))
{
Directory.Delete(fullPath, true);
}
}
var attachments = TestContext.Current.Attachments!;
Assert.Contains(attachments.Keys,
_ => _.Contains("Verify snapshot mismatch") &&
_.Contains("AttachmentTests.Simple."));
}
#endif
} | AttachmentTests |
csharp | files-community__Files | src/Files.App/Converters/Converters.cs | {
"start": 5576,
"end": 6714
} | partial class ____ : ValueConverter<string, bool>
{
/// <summary>
/// Determines whether an inverse conversion should take place.
/// </summary>
/// <remarks>If set, the value True results in <see cref="Visibility.Collapsed"/>, and false in <see cref="Visibility.Visible"/>.</remarks>
public bool Inverse { get; set; }
/// <summary>
/// Converts a source value to the target type.
/// </summary>
/// <param name="value"></param>
/// <param name="parameter"></param>
/// <param name="language"></param>
/// <returns></returns>
protected override bool Convert(string? value, object? parameter, string? language)
{
return Inverse ? !string.IsNullOrWhiteSpace(value) : string.IsNullOrWhiteSpace(value);
}
/// <summary>
/// Converts a target value back to the source type.
/// </summary>
/// <param name="value"></param>
/// <param name="parameter"></param>
/// <param name="language"></param>
/// <returns></returns>
protected override string ConvertBack(bool value, object? parameter, string? language)
{
return string.Empty;
}
}
internal sealed | StringNullOrWhiteSpaceToTrueConverter |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Pagination/IPageObserver.cs | {
"start": 115,
"end": 536
} | public interface ____
{
/// <summary>
/// Is called after the page has been sliced.
/// </summary>
/// <param name="items">
/// The items of the page.
/// </param>
/// <param name="pageInfo">
/// The page information.
/// </param>
/// <typeparam name="T">
/// The item type.
/// </typeparam>
void OnAfterSliced<T>(ReadOnlySpan<T> items, IPageInfo pageInfo);
}
| IPageObserver |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/NavigationViewDisplayMode.cs | {
"start": 224,
"end": 572
} | public enum ____
{
// Skipping already declared field Microsoft.UI.Xaml.Controls.NavigationViewDisplayMode.Minimal
// Skipping already declared field Microsoft.UI.Xaml.Controls.NavigationViewDisplayMode.Compact
// Skipping already declared field Microsoft.UI.Xaml.Controls.NavigationViewDisplayMode.Expanded
}
#endif
}
| NavigationViewDisplayMode |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/BenchmarkDotNet/BenchmarkDotNet.Generated.cs | {
"start": 81748,
"end": 82791
} | public partial class ____ : Enumeration
{
public static BenchmarkDotNetExporter GitHub = (BenchmarkDotNetExporter) "GitHub";
public static BenchmarkDotNetExporter StackOverflow = (BenchmarkDotNetExporter) "StackOverflow";
public static BenchmarkDotNetExporter RPlot = (BenchmarkDotNetExporter) "RPlot";
public static BenchmarkDotNetExporter CSV = (BenchmarkDotNetExporter) "CSV";
public static BenchmarkDotNetExporter JSON = (BenchmarkDotNetExporter) "JSON";
public static BenchmarkDotNetExporter HTML = (BenchmarkDotNetExporter) "HTML";
public static BenchmarkDotNetExporter XML = (BenchmarkDotNetExporter) "XML";
public static implicit operator BenchmarkDotNetExporter(string value)
{
return new BenchmarkDotNetExporter { Value = value };
}
}
#endregion
#region BenchmarkDotNetProfiler
/// <summary>Used within <see cref="BenchmarkDotNetTasks"/>.</summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<BenchmarkDotNetProfiler>))]
| BenchmarkDotNetExporter |
csharp | neuecc__MessagePack-CSharp | sandbox/SharedData/Class1.cs | {
"start": 2955,
"end": 3484
} | public class ____ : IMessagePackFormatter<ulong>
{
public OreOreFormatter2(int x, string y)
{
}
public ulong Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
throw new NotImplementedException();
}
public void Serialize(ref MessagePackWriter writer, ulong value, MessagePackSerializerOptions options)
{
throw new NotImplementedException();
}
}
[MessagePackObject(true)]
| OreOreFormatter2 |
csharp | CommunityToolkit__Maui | src/CommunityToolkit.Maui/Views/Popup/PopupPage.shared.cs | {
"start": 12202,
"end": 12614
} | partial class ____ : BaseConverterOneWay<LayoutOptions, LayoutOptions>
{
public override LayoutOptions DefaultConvertReturnValue { get; set; } = Options.DefaultPopupSettings.HorizontalOptions;
public override LayoutOptions ConvertFrom(LayoutOptions value, CultureInfo? culture) => value == LayoutOptions.Fill ? Options.DefaultPopupSettings.HorizontalOptions : value;
}
sealed | HorizontalOptionsConverter |
csharp | microsoft__garnet | libs/server/ArgSlice/ScratchBufferAllocator.cs | {
"start": 1569,
"end": 1766
} | class ____
{
/// <summary>
/// <see cref="ScratchBuffer"/> represents a buffer managed by <see cref="ScratchBufferAllocator"/>
/// </summary>
| ScratchBufferAllocator |
csharp | ardalis__SmartEnum | test/SmartEnum.Dapper.UnitTests/SmartEnumByValueTypeHandlerTests.cs | {
"start": 10818,
"end": 11045
} | private class ____ : SmartEnum<TestEnumULong, ulong>
{
protected TestEnumULong(ulong value, [CallerMemberName] string name = null) : base(name, value)
{
}
}
| TestEnumULong |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/XFIssue/Issue6258.cs | {
"start": 450,
"end": 891
} | public class ____ : _IssuesUITest
{
public Issue6258(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "[Android] ContextActions icon not working";
[Test]
[Category(UITestCategories.ListView)]
public void ContextActionsIconImageSource()
{
App.WaitForElement("ListViewItem");
App.ActivateContextMenu("ListViewItem");
App.WaitForElement(AppiumQuery.ByAccessibilityId("coffee.png"));
}
}
#endif | Issue6258 |
csharp | MahApps__MahApps.Metro | src/MahApps.Metro/Controls/Icons/PathIcon.cs | {
"start": 564,
"end": 2919
} | public class ____ : IconElement
{
/// <summary>Identifies the Data dependency property.</summary>
public static readonly DependencyProperty DataProperty
= Path.DataProperty.AddOwner(typeof(PathIcon),
new FrameworkPropertyMetadata(null));
/// <summary>
/// Gets or sets a Geometry that specifies the shape to be drawn. In XAML this can also be set using the Path Markup Syntax.
/// </summary>
[TypeConverter(typeof(GeometryConverter))]
public Geometry? Data
{
get => (Geometry?)this.GetValue(DataProperty);
set => this.SetValue(DataProperty, value);
}
static PathIcon()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PathIcon), new FrameworkPropertyMetadata(typeof(PathIcon)));
FocusableProperty.OverrideMetadata(typeof(PathIcon), new FrameworkPropertyMetadata(false));
}
private Path? PART_Path { get; set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.PART_Path = this.GetTemplateChild(nameof(this.PART_Path)) as Path;
if (this.PART_Path is not null && this.InheritsForegroundFromVisualParent)
{
this.PART_Path.Fill = this.VisualParentForeground;
}
}
protected override void OnInheritsForegroundFromVisualParentPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnInheritsForegroundFromVisualParentPropertyChanged(e);
if (this.PART_Path is not null)
{
if (this.InheritsForegroundFromVisualParent)
{
this.PART_Path.Fill = this.VisualParentForeground;
}
else
{
this.PART_Path.ClearValue(Shape.FillProperty);
}
}
}
protected override void OnVisualParentForegroundPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnVisualParentForegroundPropertyChanged(e);
if (this.PART_Path is not null && this.InheritsForegroundFromVisualParent)
{
this.PART_Path.Fill = e.NewValue as Brush;
}
}
}
} | PathIcon |
csharp | dotnet__BenchmarkDotNet | samples/BenchmarkDotNet.Samples/IntroStaThread.cs | {
"start": 100,
"end": 460
} | public class ____
{
[Benchmark, System.STAThread]
public void CheckForSTA()
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
throw new ThreadStateException(
"The current threads apartment state is not STA");
}
}
}
} | IntroStaThread |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/ViewRenderer.cs | {
"start": 604,
"end": 755
} | public interface ____
{
NativeView TabStop { get; }
}
[Obsolete("Use Microsoft.Maui.Controls.Handlers.Compatibility.ViewRenderer instead")]
| ITabStop |
csharp | dotnet__efcore | src/EFCore/Metadata/IModel.cs | {
"start": 2894,
"end": 9605
} | class ____ be a proxy derived from the
/// actual entity type. Returns <see langword="null" /> if no entity type with the given CLR type is found
/// or the given CLR type is being used by shared type entity type
/// or the entity type has a defining navigation.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="type">The type to find the corresponding entity type for.</param>
/// <returns>The entity type, or <see langword="null" /> if none is found.</returns>
IEntityType? FindRuntimeEntityType(Type? type)
{
Check.NotNull(type);
while (type != null)
{
var entityType = FindEntityType(type);
if (entityType != null)
{
return entityType;
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Gets all entity types defined in the model.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <returns>All entity types defined in the model.</returns>
new IEnumerable<IEntityType> GetEntityTypes();
/// <summary>
/// The runtime service dependencies.
/// </summary>
[DisallowNull]
RuntimeModelDependencies? ModelDependencies
{
get => (RuntimeModelDependencies?)FindRuntimeAnnotationValue(CoreAnnotationNames.ModelDependencies);
set => SetRuntimeAnnotation(CoreAnnotationNames.ModelDependencies, Check.NotNull(value));
}
/// <summary>
/// Gets the runtime service dependencies.
/// </summary>
RuntimeModelDependencies GetModelDependencies()
{
var dependencies = ModelDependencies;
if (dependencies == null)
{
throw new InvalidOperationException(CoreStrings.ModelNotFinalized(nameof(GetModelDependencies)));
}
return dependencies;
}
/// <summary>
/// Gets the entity that maps the given entity class. Returns <see langword="null" /> if no entity type with
/// the given CLR type is found or the given CLR type is being used by shared type entity type
/// or the entity type has a defining navigation.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="type">The type to find the corresponding entity type for.</param>
/// <returns>The entity type, or <see langword="null" /> if none is found.</returns>
new IEntityType? FindEntityType([DynamicallyAccessedMembers(IEntityType.DynamicallyAccessedMemberTypes)] Type type);
/// <summary>
/// Gets the entity type for the given name, defining navigation name
/// and the defining entity type. Returns <see langword="null" /> if no matching entity type is found.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="type">The type of the entity type to find.</param>
/// <param name="definingNavigationName">The defining navigation of the entity type to find.</param>
/// <param name="definingEntityType">The defining entity type of the entity type to find.</param>
/// <returns>The entity type, or <see langword="null" /> if none is found.</returns>
IEntityType? FindEntityType(
Type type,
string definingNavigationName,
IEntityType definingEntityType)
=> (IEntityType?)((IReadOnlyModel)this).FindEntityType(type, definingNavigationName, definingEntityType);
/// <summary>
/// Gets the entity types matching the given type.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="type">The type of the entity type to find.</param>
/// <returns>The entity types found.</returns>
[DebuggerStepThrough]
new IEnumerable<IEntityType> FindEntityTypes(Type type);
/// <summary>
/// Returns the entity types corresponding to the least derived types from the given.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="type">The base type.</param>
/// <param name="condition">An optional condition for filtering entity types.</param>
/// <returns>List of entity types corresponding to the least derived types from the given.</returns>
new IEnumerable<IEntityType> FindLeastDerivedEntityTypes(
Type type,
Func<IReadOnlyEntityType, bool>? condition = null)
=> ((IReadOnlyModel)this).FindLeastDerivedEntityTypes(type, condition)
.Cast<IEntityType>();
/// <summary>
/// Gets a value indicating whether the given <see cref="MethodInfo" /> represents an indexer access.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="methodInfo">The <see cref="MethodInfo" /> to check.</param>
bool IsIndexerMethod(MethodInfo methodInfo);
/// <summary>
/// Gets all the pre-convention configurations.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <returns>The pre-convention configurations.</returns>
IEnumerable<ITypeMappingConfiguration> GetTypeMappingConfigurations();
/// <summary>
/// Finds the pre-convention configuration for a given scalar <see cref="Type" />.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
/// <param name="scalarType">The CLR type.</param>
/// <returns>The pre-convention configuration or <see langword="null" /> if none is found.</returns>
ITypeMappingConfiguration? FindTypeMappingConfiguration(Type scalarType);
}
| may |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input.Inking/InkRecognizer.cs | {
"start": 298,
"end": 1068
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal InkRecognizer()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string Name
{
get
{
throw new global::System.NotImplementedException("The member string InkRecognizer.Name is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20InkRecognizer.Name");
}
}
#endif
// Forced skipping of method Windows.UI.Input.Inking.InkRecognizer.Name.get
}
}
| InkRecognizer |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1817871,
"end": 1818214
} | public partial interface ____ : IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes_3, IDescriptionChanged
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_Changes_DescriptionChanged_3 |
csharp | exceptionless__Exceptionless | src/Exceptionless.Core/Plugins/EventUpgrader/Default/V1R844_EventUpgrade.cs | {
"start": 170,
"end": 1331
} | public class ____ : PluginBase, IEventUpgraderPlugin
{
public V1R844EventUpgrade(AppOptions options, ILoggerFactory loggerFactory) : base(options, loggerFactory) { }
public void Upgrade(EventUpgraderContext ctx)
{
if (ctx.Version > new Version(1, 0, 0, 844))
return;
foreach (var doc in ctx.Documents)
{
if (!(doc["RequestInfo"] is JObject { HasValues: true } requestInfo))
return;
if (requestInfo["Cookies"] is not null && requestInfo["Cookies"]!.HasValues)
{
if (requestInfo["Cookies"] is JObject cookies)
cookies.Remove("");
}
if (requestInfo["Form"] is not null && requestInfo["Form"]!.HasValues)
{
if (requestInfo["Form"] is JObject form)
form.Remove("");
}
if (requestInfo["QueryString"] is not null && requestInfo["QueryString"]!.HasValues)
{
if (requestInfo["QueryString"] is JObject queryString)
queryString.Remove("");
}
}
}
}
| V1R844EventUpgrade |
csharp | MassTransit__MassTransit | tests/MassTransit.EntityFrameworkCoreIntegration.Tests/JobConsumer_Specs.cs | {
"start": 882,
"end": 1275
} | public class ____ :
IConsumer<JobCompleted<OddJob>>
{
public Task Consume(ConsumeContext<JobCompleted<OddJob>> context)
{
return Task.CompletedTask;
}
}
}
[Category("Flaky")]
[TestFixture(typeof(SqlServerTestDbParameters))]
[TestFixture(typeof(PostgresTestDbParameters))]
| OddJobCompletedConsumer |
csharp | dotnet__orleans | test/Extensions/Tester.Cosmos/PersistenceGrainTests_CosmosGrainStorage.cs | {
"start": 1820,
"end": 2013
} | public class ____ : GrainPersistenceTestsRunner, IClassFixture<PersistenceGrainTests_CosmosGrainStorage_DeleteStateOnClear.Fixture>
{
| PersistenceGrainTests_CosmosGrainStorage_DeleteStateOnClear |
csharp | AvaloniaUI__Avalonia | src/Windows/Avalonia.Win32/Interop/UnmanagedMethods.cs | {
"start": 87092,
"end": 87593
} | public struct ____
{
public int cbSize;
public uint dwFlags;
public IntPtr hwndTrack;
public int dwHoverTime;
}
// TrackMouseEvent flags
public const uint TME_HOVER = 0x00000001;
public const uint TME_LEAVE = 0x00000002;
public const uint TME_NONCLIENT = 0x00000010;
public const uint TME_QUERY = 0x40000000;
public const uint TME_CANCEL = 0x80000000;
[Flags]
| TRACKMOUSEEVENT |
csharp | EventStore__EventStore | src/KurrentDB.Core/Configuration/ClusterVNodeOptions.Framework.cs | {
"start": 9878,
"end": 9929
} | internal class ____ : Attribute;
}
| OptionGroupAttribute |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/BsonClassMapTests.cs | {
"start": 9855,
"end": 9970
} | public class ____
{
private static bool __firstTime = true;
| BsonClassMapGetRegisteredClassMapTests |
csharp | microsoft__semantic-kernel | dotnet/src/SemanticKernel.Core/Memory/SemanticTextMemory.cs | {
"start": 671,
"end": 4584
} | public sealed class ____ : ISemanticTextMemory
{
private readonly ITextEmbeddingGenerationService? _textEmbeddingsService;
private readonly IEmbeddingGenerator<string, Embedding<float>>? _embeddingGenerator;
private readonly IMemoryStore _storage;
/// <summary>
/// Initializes a new instance of the <see cref="SemanticTextMemory"/> class.
/// </summary>
/// <param name="storage">The memory store to use for storing and retrieving data.</param>
/// <param name="embeddingGenerator">The text embedding generator to use for generating embeddings.</param>
[Obsolete("Use the constructor with IEmbeddingGenerator instead.")]
public SemanticTextMemory(
IMemoryStore storage,
ITextEmbeddingGenerationService embeddingGenerator)
{
this._textEmbeddingsService = embeddingGenerator;
this._storage = storage;
}
/// <summary>
/// Initializes a new instance of the <see cref="SemanticTextMemory"/> class.
/// </summary>
/// <param name="storage">The memory store to use for storing and retrieving data.</param>
/// <param name="embeddingGenerator">The text embedding generator to use for generating embeddings.</param>
public SemanticTextMemory(
IMemoryStore storage,
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator)
{
this._embeddingGenerator = embeddingGenerator;
this._storage = storage;
}
/// <inheritdoc/>
public async Task<string> SaveInformationAsync(
string collection,
string text,
string id,
string? description = null,
string? additionalMetadata = null,
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
ReadOnlyMemory<float> embedding = await this.GenerateEmbeddingAsync(text, kernel, cancellationToken).ConfigureAwait(false);
MemoryRecord data = MemoryRecord.LocalRecord(
id: id,
text: text,
description: description,
additionalMetadata: additionalMetadata,
embedding: embedding);
if (!(await this._storage.DoesCollectionExistAsync(collection, cancellationToken).ConfigureAwait(false)))
{
await this._storage.CreateCollectionAsync(collection, cancellationToken).ConfigureAwait(false);
}
return await this._storage.UpsertAsync(collection, data, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<string> SaveReferenceAsync(
string collection,
string text,
string externalId,
string externalSourceName,
string? description = null,
string? additionalMetadata = null,
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
var embedding = await this.GenerateEmbeddingAsync(text, kernel, cancellationToken).ConfigureAwait(false);
var data = MemoryRecord.ReferenceRecord(externalId: externalId, sourceName: externalSourceName, description: description,
additionalMetadata: additionalMetadata, embedding: embedding);
if (!(await this._storage.DoesCollectionExistAsync(collection, cancellationToken).ConfigureAwait(false)))
{
await this._storage.CreateCollectionAsync(collection, cancellationToken).ConfigureAwait(false);
}
return await this._storage.UpsertAsync(collection, data, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<MemoryQueryResult?> GetAsync(
string collection,
string key,
bool withEmbedding = false,
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
MemoryRecord? record = await this._storage.GetAsync(collection, key, withEmbedding, cancellationToken).ConfigureAwait(false);
if ( | SemanticTextMemory |
csharp | microsoft__garnet | test/Garnet.test/TestProcedureLists.cs | {
"start": 470,
"end": 4134
} | sealed class ____ : CustomTransactionProcedure
{
public override bool Prepare<TGarnetReadApi>(TGarnetReadApi api, ref CustomProcedureInput procInput)
{
var offset = 0;
var lstKey = GetNextArg(ref procInput, ref offset);
var lstKeyB = GetNextArg(ref procInput, ref offset);
var lstKeyC = GetNextArg(ref procInput, ref offset);
if (lstKey.Length == 0 || lstKeyB.Length == 0 || lstKeyC.Length == 0)
return false;
AddKey(lstKey, LockType.Exclusive, true);
AddKey(lstKeyB, LockType.Exclusive, true);
AddKey(lstKeyC, LockType.Exclusive, true);
return true;
}
public override void Main<TGarnetApi>(TGarnetApi api, ref CustomProcedureInput procInput, ref MemoryResult<byte> output)
{
var result = TestAPI(api, ref procInput);
WriteSimpleString(ref output, result ? "SUCCESS" : "ERROR");
}
private static bool TestAPI<TGarnetApi>(TGarnetApi api, ref CustomProcedureInput procInput) where TGarnetApi : IGarnetApi
{
var offset = 0;
var elements = new ArgSlice[10];
var lstKeyA = GetNextArg(ref procInput, ref offset);
var lstKeyB = GetNextArg(ref procInput, ref offset);
var lstKeyC = GetNextArg(ref procInput, ref offset);
if (lstKeyA.Length == 0 || lstKeyB.Length == 0 || lstKeyC.Length == 0)
return false;
for (var i = 0; i < elements.Length; i++)
{
elements[i] = GetNextArg(ref procInput, ref offset);
}
var status = api.ListLeftPush(lstKeyA, elements, out var count);
if (status != GarnetStatus.OK || count != 10)
return false;
status = api.ListLeftPop(lstKeyA, out var elementPopped);
if (status != GarnetStatus.OK || !elementPopped.ReadOnlySpan.SequenceEqual(elements[9].ReadOnlySpan))
return false;
status = api.ListRightPush(lstKeyB, elements, out count);
if (status != GarnetStatus.OK || count != 10)
return false;
status = api.ListLeftPop(lstKeyB, 2, out var elementsPopped);
if (status != GarnetStatus.OK || elementsPopped.Length != 2 || !elementsPopped[0].ReadOnlySpan.SequenceEqual(elements[0].ReadOnlySpan)
|| !elementsPopped[1].ReadOnlySpan.SequenceEqual(elements[1].ReadOnlySpan))
return false;
status = api.ListRightPop(lstKeyB, out elementPopped);
if (status != GarnetStatus.OK || !elementPopped.ReadOnlySpan.SequenceEqual(elements[9].ReadOnlySpan))
return false;
status = api.ListLength(lstKeyB, out count);
if (status != GarnetStatus.OK || count != 7)
return false;
status = api.ListMove(lstKeyA, lstKeyB, OperationDirection.Left, OperationDirection.Right, out var element);
if (status != GarnetStatus.OK || !element.SequenceEqual(elements[8].ReadOnlySpan.ToArray()))
return false;
if (!api.ListTrim(lstKeyB, 1, 3))
return false;
status = api.ListLength(lstKeyB, out count);
if (status != GarnetStatus.OK || count != 3)
return false;
// LPOP when list is empty
status = api.ListLeftPop(lstKeyC, out var elementNotFound);
if (status != GarnetStatus.NOTFOUND || elementNotFound.Length != 0)
return false;
return true;
}
}
} | TestProcedureLists |
csharp | PrismLibrary__Prism | src/Prism.Events/EventBase.cs | {
"start": 2121,
"end": 5424
} | class ____ prune all the subscribers from the
/// list that return a <see langword="null" /> <see cref="Action{T}"/> when calling the
/// <see cref="IEventSubscription.GetExecutionStrategy"/> method.</remarks>
protected virtual void InternalPublish(params object[] arguments)
{
List<Action<object[]>> executionStrategies = PruneAndReturnStrategies();
foreach (var executionStrategy in executionStrategies)
{
executionStrategy(arguments);
}
}
/// <summary>
/// Removes the subscriber matching the <see cref="SubscriptionToken"/>.
/// </summary>
/// <param name="token">The <see cref="SubscriptionToken"/> returned by <see cref="EventBase"/> while subscribing to the event.</param>
public virtual void Unsubscribe(SubscriptionToken token)
{
lock (Subscriptions)
{
IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);
if (subscription != null)
{
Subscriptions.Remove(subscription);
}
}
}
/// <summary>
/// Returns <see langword="true"/> if there is a subscriber matching <see cref="SubscriptionToken"/>.
/// </summary>
/// <param name="token">The <see cref="SubscriptionToken"/> returned by <see cref="EventBase"/> while subscribing to the event.</param>
/// <returns><see langword="true"/> if there is a <see cref="SubscriptionToken"/> that matches; otherwise <see langword="false"/>.</returns>
public virtual bool Contains(SubscriptionToken token)
{
lock (Subscriptions)
{
IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);
return subscription != null;
}
}
private List<Action<object[]>> PruneAndReturnStrategies()
{
List<Action<object[]>> returnList = new List<Action<object[]>>();
lock (Subscriptions)
{
for (var i = Subscriptions.Count - 1; i >= 0; i--)
{
Action<object[]> listItem =
_subscriptions[i].GetExecutionStrategy();
if (listItem == null)
{
// Prune from main list. Log?
_subscriptions.RemoveAt(i);
}
else
{
returnList.Add(listItem);
}
}
}
return returnList;
}
/// <summary>
/// Forces the PubSubEvent to remove any subscriptions that no longer have an execution strategy.
/// </summary>
public void Prune()
{
lock (Subscriptions)
{
for (var i = Subscriptions.Count - 1; i >= 0; i--)
{
if (_subscriptions[i].GetExecutionStrategy() == null)
{
_subscriptions.RemoveAt(i);
}
}
}
}
}
}
| will |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/PostmanFeature.cs | {
"start": 3209,
"end": 3343
} | public class ____
{
public string name { get; set; }
public PostmanRequestDetails request { get; set; } = new();
}
| PostmanRequest |
csharp | App-vNext__Polly | test/Polly.Core.Tests/Registry/ConfigureBuilderContextTests.cs | {
"start": 62,
"end": 540
} | public static class ____
{
[Fact]
public static void AddReloadToken_Ok()
{
var context = new ConfigureBuilderContext<int>(0, "dummy", "dummy");
using var source = new CancellationTokenSource();
context.AddReloadToken(CancellationToken.None);
context.AddReloadToken(source.Token);
source.Cancel();
context.AddReloadToken(source.Token);
context.ReloadTokens.Count.ShouldBe(1);
}
}
| ConfigureBuilderContextTests |
csharp | dotnet__efcore | test/EFCore.Cosmos.FunctionalTests/ConcurrencyDetectorDisabledCosmosTest.cs | {
"start": 200,
"end": 1445
} | public class ____(ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture fixture)
: ConcurrencyDetectorDisabledTestBase<
ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture>(fixture)
{
[ConditionalTheory(Skip = "Issue #17246")]
public override Task Any(bool async)
=> base.Any(async);
public override Task SaveChanges(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.SaveChanges(a));
public override Task Count(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Count(a));
public override Task Find(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Find(a));
public override Task First(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.First(a));
public override Task Last(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Last(a));
public override Task Single(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Single(a));
public override Task ToList(bool async)
=> CosmosTestHelpers.Instance.NoSyncTest(async, a => base.ToList(a));
| ConcurrencyDetectorDisabledCosmosTest |
csharp | dotnet__maui | src/Controls/tests/Core.UnitTests/PageTests.cs | {
"start": 20006,
"end": 20502
} | class ____ : ScrollView
{
public int PlatformInvalidateMeasureCount { get; set; }
public int InvalidateMeasureCount { get; set; }
public ScrollViewInvalidationMeasureCheck()
{
MeasureInvalidated += (sender, args) =>
{
InvalidateMeasureCount++;
};
}
internal override void InvalidateMeasureInternal(InvalidationTrigger trigger)
{
base.InvalidateMeasureInternal(trigger);
PlatformInvalidateMeasureCount++;
}
}
| ScrollViewInvalidationMeasureCheck |
csharp | dotnet__orleans | src/Orleans.Analyzers/GrainInterfacePropertyDiagnosticAnalyzer.cs | {
"start": 271,
"end": 2457
} | public class ____ : DiagnosticAnalyzer
{
private const string BaseInterfaceName = "Orleans.Runtime.IAddressable";
public const string DiagnosticId = "ORLEANS0008";
public const string Title = "Grain interfaces must not contain properties";
public const string MessageFormat = Title;
public const string Category = "Usage";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.PropertyDeclaration);
}
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
if (context.Node is not PropertyDeclarationSyntax syntax) return;
var symbol = context.SemanticModel.GetDeclaredSymbol(syntax, context.CancellationToken);
if (symbol.ContainingType.TypeKind != TypeKind.Interface) return;
// ignore static members
if (symbol.IsStatic) return;
var isIAddressableInterface = false;
foreach (var implementedInterface in symbol.ContainingType.AllInterfaces)
{
if (BaseInterfaceName.Equals(implementedInterface.ToDisplayString(NullableFlowState.None), System.StringComparison.Ordinal))
{
isIAddressableInterface = true;
break;
}
}
if (!isIAddressableInterface) return;
var syntaxReference = symbol.DeclaringSyntaxReferences;
context.ReportDiagnostic(Diagnostic.Create(Rule, Location.Create(syntaxReference[0].SyntaxTree, syntaxReference[0].Span)));
}
}
}
| GrainInterfacePropertyDiagnosticAnalyzer |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Linq/Linq3Implementation/Ast/Stages/AstProjectStage.cs | {
"start": 1651,
"end": 1906
} | internal abstract class ____ : AstNode
{
public override BsonValue Render()
{
return new BsonDocument(RenderAsElement());
}
public abstract BsonElement RenderAsElement();
}
| AstProjectStageSpecification |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MethodTranslators/ContainsMethodToAggregationExpressionTranslator.cs | {
"start": 968,
"end": 4004
} | internal static class ____
{
// public methods
public static TranslatedExpression Translate(TranslationContext context, MethodCallExpression expression)
{
if (StartsWithContainsOrEndsWithMethodToAggregationExpressionTranslator.CanTranslate(expression))
{
return StartsWithContainsOrEndsWithMethodToAggregationExpressionTranslator.Translate(context, expression);
}
if (IsEnumerableContainsMethod(expression, out var sourceExpression, out var valueExpression))
{
return TranslateEnumerableContains(context, expression, sourceExpression, valueExpression);
}
throw new ExpressionNotSupportedException(expression);
}
// private methods
private static bool IsEnumerableContainsMethod(MethodCallExpression expression, out Expression sourceExpression, out Expression valueExpression)
{
var method = expression.Method;
var arguments = expression.Arguments;
if (method.IsOneOf(EnumerableMethod.Contains, QueryableMethod.Contains))
{
sourceExpression = arguments[0];
valueExpression = arguments[1];
return true;
}
if (!method.IsStatic && method.ReturnType == typeof(bool) && method.Name == "Contains" && arguments.Count == 1)
{
sourceExpression = expression.Object;
valueExpression = arguments[0];
if (sourceExpression.Type.TryGetIEnumerableGenericInterface(out var ienumerableInterface))
{
var itemType = ienumerableInterface.GetGenericArguments()[0];
if (itemType == valueExpression.Type)
{
// string.Contains(char) is not translated like other Contains methods because string is not represented as an array
return sourceExpression.Type != typeof(string) && valueExpression.Type != typeof(char);
}
}
}
sourceExpression = null;
valueExpression = null;
return false;
}
private static TranslatedExpression TranslateEnumerableContains(TranslationContext context, MethodCallExpression expression, Expression sourceExpression, Expression valueExpression)
{
var sourceTranslation = ExpressionToAggregationExpressionTranslator.TranslateEnumerable(context, sourceExpression);
NestedAsQueryableHelper.EnsureQueryableMethodHasNestedAsQueryableSource(expression, sourceTranslation);
var valueTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, valueExpression);
var ast = AstExpression.In(valueTranslation.Ast, sourceTranslation.Ast);
return new TranslatedExpression(expression, ast, BooleanSerializer.Instance);
}
}
}
| ContainsMethodToAggregationExpressionTranslator |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Content/ContentEnvironmentSettingChangedEventArgs.cs | {
"start": 295,
"end": 1230
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal ContentEnvironmentSettingChangedEventArgs()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string SettingName
{
get
{
throw new global::System.NotImplementedException("The member string ContentEnvironmentSettingChangedEventArgs.SettingName is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20ContentEnvironmentSettingChangedEventArgs.SettingName");
}
}
#endif
// Forced skipping of method Microsoft.UI.Content.ContentEnvironmentSettingChangedEventArgs.SettingName.get
}
}
| ContentEnvironmentSettingChangedEventArgs |
csharp | AutoMapper__AutoMapper | src/UnitTests/ShouldUseConstructor.cs | {
"start": 3838,
"end": 4215
} | class ____
{
public string A { get; set; }
}
protected override MapperConfiguration CreateConfiguration() =>
new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); });
[Fact]
public void Should_ignore_implicit_static_constructor() =>
Should.Throw<AutoMapperConfigurationException>(AssertConfigurationIsValid);
}
| Source |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver.Encryption/SigningRSAESPKCSCallback.cs | {
"start": 698,
"end": 2496
} | internal static class ____
{
public static bool RsaSign(
IntPtr ctx,
IntPtr key,
IntPtr inData,
IntPtr outData,
IntPtr statusPtr)
{
using (var status = new Status(StatusSafeHandle.FromIntPtr(statusPtr)))
{
try
{
var keyBinary = new Binary(BinarySafeHandle.FromIntPtr(key));
var inputBinary = new Binary(BinarySafeHandle.FromIntPtr(inData));
var outBinary = new Binary(BinarySafeHandle.FromIntPtr(outData));
byte[] inputBytes = inputBinary.ToArray();
byte[] keyBytes = keyBinary.ToArray();
// Hash and sign the data.
var signedData = HashAndSignBytes(inputBytes, keyBytes);
outBinary.WriteBytes(signedData);
return true;
}
catch (Exception e)
{
// let mongocrypt level to handle the error
status.SetStatus(1, e.Message);
return false;
}
}
}
#pragma warning disable CA1801
public static byte[] HashAndSignBytes(byte[] dataToSign, byte[] key)
{
#if !NET472
using (var rsaProvider = new RSACryptoServiceProvider())
{
rsaProvider.ImportPkcs8PrivateKey(key, out _);
return rsaProvider.SignData(dataToSign, SHA256.Create());
}
#else
throw new System.PlatformNotSupportedException("RSACryptoServiceProvider.ImportPkcs8PrivateKey is not supported on .NET framework.");
#endif
}
#pragma warning restore CA1801
}
}
| SigningRSAESPKCSCallback |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ComplexTypesTrackingTestBase.cs | {
"start": 142107,
"end": 142462
} | public record ____
{
public string Name = null!;
public decimal? CoverCharge;
public bool IsTeamBased;
public string? Description;
public string[]? Notes;
public DayOfWeek Day;
public FieldTeamRecord Champions = null!;
public FieldTeamRecord RunnersUp = null!;
}
| FieldActivityRecord |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/QueryLanguageEx.cs | {
"start": 3253,
"end": 13589
} | private sealed class ____<TSource> : ObservableBase<TSource>
{
private readonly IObservable<TSource> _source;
private readonly Func<TSource, IObservable<TSource>> _selector;
private readonly IScheduler _scheduler;
public ExpandObservable(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector, IScheduler scheduler)
{
_source = source;
_selector = selector;
_scheduler = scheduler;
}
protected override IDisposable SubscribeCore(IObserver<TSource> observer)
{
var outGate = new object();
var q = new Queue<IObservable<TSource>>();
var m = new SerialDisposable();
var d = new CompositeDisposable { m };
var activeCount = 0;
var isAcquired = false;
void ensureActive()
{
var isOwner = false;
lock (q)
{
if (q.Count > 0)
{
isOwner = !isAcquired;
isAcquired = true;
}
}
if (isOwner)
{
m.Disposable = _scheduler.Schedule(self =>
{
IObservable<TSource> work;
lock (q)
{
if (q.Count > 0)
{
work = q.Dequeue();
}
else
{
isAcquired = false;
return;
}
}
var m1 = new SingleAssignmentDisposable();
d.Add(m1);
m1.Disposable = work.Subscribe(
x =>
{
lock (outGate)
{
observer.OnNext(x);
}
IObservable<TSource> result;
try
{
result = _selector(x);
}
catch (Exception exception)
{
lock (outGate)
{
observer.OnError(exception);
}
return;
}
lock (q)
{
q.Enqueue(result);
activeCount++;
}
ensureActive();
},
exception =>
{
lock (outGate)
{
observer.OnError(exception);
}
},
() =>
{
d.Remove(m1);
var done = false;
lock (q)
{
activeCount--;
if (activeCount == 0)
{
done = true;
}
}
if (done)
{
lock (outGate)
{
observer.OnCompleted();
}
}
});
self();
});
}
}
lock (q)
{
q.Enqueue(_source);
activeCount++;
}
ensureActive();
return d;
}
}
public virtual IObservable<TSource> Expand<TSource>(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector)
{
return source.Expand(selector, SchedulerDefaults.Iteration);
}
#endregion
#region ForkJoin
public virtual IObservable<TResult> ForkJoin<TFirst, TSecond, TResult>(IObservable<TFirst> first, IObservable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
return Combine<TFirst, TSecond, TResult>(first, second, (observer, leftSubscription, rightSubscription) =>
{
var leftStopped = false;
var rightStopped = false;
var hasLeft = false;
var hasRight = false;
var lastLeft = default(TFirst);
var lastRight = default(TSecond);
return new BinaryObserver<TFirst, TSecond>(
left =>
{
switch (left.Kind)
{
case NotificationKind.OnNext:
hasLeft = true;
lastLeft = left.Value;
break;
case NotificationKind.OnError:
rightSubscription.Dispose();
observer.OnError(left.Exception!);
break;
case NotificationKind.OnCompleted:
leftStopped = true;
if (rightStopped)
{
if (!hasLeft)
{
observer.OnCompleted();
}
else if (!hasRight)
{
observer.OnCompleted();
}
else
{
TResult result;
try
{
result = resultSelector(lastLeft!, lastRight!);
}
catch (Exception exception)
{
observer.OnError(exception);
return;
}
observer.OnNext(result);
observer.OnCompleted();
}
}
break;
}
},
right =>
{
switch (right.Kind)
{
case NotificationKind.OnNext:
hasRight = true;
lastRight = right.Value;
break;
case NotificationKind.OnError:
leftSubscription.Dispose();
observer.OnError(right.Exception!);
break;
case NotificationKind.OnCompleted:
rightStopped = true;
if (leftStopped)
{
if (!hasLeft)
{
observer.OnCompleted();
}
else if (!hasRight)
{
observer.OnCompleted();
}
else
{
TResult result;
try
{
result = resultSelector(lastLeft!, lastRight!);
}
catch (Exception exception)
{
observer.OnError(exception);
return;
}
observer.OnNext(result);
observer.OnCompleted();
}
}
break;
}
});
});
}
public virtual IObservable<TSource[]> ForkJoin<TSource>(params IObservable<TSource>[] sources)
{
return sources.ForkJoin();
}
public virtual IObservable<TSource[]> ForkJoin<TSource>(IEnumerable<IObservable<TSource>> sources)
{
return new ForkJoinObservable<TSource>(sources);
}
| ExpandObservable |
csharp | atata-framework__atata | src/Atata/Attributes/Triggers/WaitForElementAttribute.cs | {
"start": 130,
"end": 2642
} | public class ____ : WaitUntilAttribute
{
private ScopeSource? _scopeSource;
/// <summary>
/// Initializes a new instance of the <see cref="WaitForElementAttribute" /> class.
/// </summary>
/// <param name="waitBy">The kind of the element selector to wait for.</param>
/// <param name="selector">The selector.</param>
/// <param name="until">The waiting condition.</param>
/// <param name="on">The trigger events.</param>
/// <param name="priority">The priority.</param>
public WaitForElementAttribute(
WaitBy waitBy,
string selector,
Until until = Until.MissingOrHidden,
TriggerEvents on = TriggerEvents.AfterClick,
TriggerPriority priority = TriggerPriority.Medium)
: base(until, on, priority)
{
WaitBy = waitBy;
Selector = selector;
}
/// <summary>
/// Gets the kind of the element selector to wait for.
/// </summary>
public WaitBy WaitBy { get; }
/// <summary>
/// Gets the selector.
/// </summary>
public string Selector { get; }
/// <summary>
/// Gets or sets the scope source.
/// The default value is <see cref="ScopeSource.Parent"/>.
/// </summary>
public ScopeSource ScopeSource
{
get => _scopeSource ?? ScopeSource.Parent;
set => _scopeSource = value;
}
protected internal override void Execute<TOwner>(TriggerContext<TOwner> context)
{
foreach (WaitUnit unit in Until.GetWaitUnits(WaitOptions))
{
context.Component.Session.Log.ExecuteSection(
new WaitForElementLogSection((UIComponent)context.Component, WaitBy, Selector, unit),
() => Wait(context.Component, unit));
}
}
protected virtual void Wait<TOwner>(IUIComponent<TOwner> scopeComponent, WaitUnit waitUnit)
where TOwner : PageObject<TOwner>
{
ScopeSource actualScopeSource = _scopeSource ?? scopeComponent.ScopeSource;
StaleSafely.Execute(
options =>
{
ISearchContext scopeContext = actualScopeSource.GetScopeContext(scopeComponent, SearchOptions.Within(options.Timeout));
By by = WaitBy.GetBy(Selector).With(options);
if (waitUnit.Method == WaitUnit.WaitMethod.Presence)
scopeContext.Exists(by);
else
scopeContext.Missing(by);
},
waitUnit.SearchOptions);
}
}
| WaitForElementAttribute |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Stores/Caching/CachingResourceStore.cs | {
"start": 483,
"end": 1115
} | public class ____<T> : IResourceStore
where T : IResourceStore
{
private const string AllKey = "__all__";
private readonly IdentityServerOptions _options;
private readonly ICache<IdentityResource> _identityCache;
private readonly ICache<ApiScope> _apiScopeCache;
private readonly ICache<ApiResource> _apiResourceCache;
private readonly ICache<Resources> _allCache;
private readonly ICache<ApiResourceNames> _apiResourceNames;
private readonly IResourceStore _inner;
/// <summary>
/// Used to cache the ApiResource names for ApiScopes requested.
/// </summary>
| CachingResourceStore |
csharp | AutoMapper__AutoMapper | src/UnitTests/MappingInheritance/ConventionMappedCollectionShouldMapBaseTypes.cs | {
"start": 525,
"end": 2999
} | public class ____
{
public ContainerDto()
{
Items = new List<ItemDto>();
}
public List<ItemDto> Items { get; private set; }
}
// Getting an exception casting from SpecificItemDto to GeneralItemDto
// because it is selecting too specific a mapping for the collection.
[Fact]
public void item_collection_should_map_by_base_type()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Container, ContainerDto>();
cfg.CreateMap<ItemBase, ItemDto>()
.Include<GeneralItem, GeneralItemDto>()
.Include<SpecificItem, SpecificItemDto>();
cfg.CreateMap<GeneralItem, GeneralItemDto>();
cfg.CreateMap<SpecificItem, SpecificItemDto>();
});
var dto = config.CreateMapper().Map<Container, ContainerDto>(new Container
{
Items =
{
new GeneralItem(),
new SpecificItem()
}
});
dto.Items[0].ShouldBeOfType<GeneralItemDto>();
dto.Items[1].ShouldBeOfType<SpecificItemDto>();
}
[Fact]
public void item_collection_should_map_by_base_type_for_map_with_one_parameter()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Container, ContainerDto>();
cfg.CreateMap<ItemBase, ItemDto>()
.Include<GeneralItem, GeneralItemDto>()
.Include<SpecificItem, SpecificItemDto>();
cfg.CreateMap<GeneralItem, GeneralItemDto>();
cfg.CreateMap<SpecificItem, SpecificItemDto>();
});
var dto = config.CreateMapper().Map<ContainerDto>(new Container
{
Items =
{
new GeneralItem(),
new SpecificItem()
}
});
dto.Items[0].ShouldBeOfType<GeneralItemDto>();
dto.Items[1].ShouldBeOfType<SpecificItemDto>();
}
}
| ContainerDto |
csharp | dotnet__efcore | test/EFCore.Tests/Metadata/Conventions/ForeignKeyIndexConventionTest.cs | {
"start": 1503,
"end": 1702
} | private class ____
{
public int PrincipalId { get; set; }
public int DependentId { get; set; }
public virtual PrincipalEntity Principal { get; set; }
}
}
| DependentEntity |
csharp | MassTransit__MassTransit | src/Transports/MassTransit.AmazonSqsTransport/AmazonSqsTransport/Topology/AmazonSqsPublishTopology.cs | {
"start": 130,
"end": 2114
} | public class ____ :
PublishTopology,
IAmazonSqsPublishTopologyConfigurator
{
readonly IMessageTopology _messageTopology;
public AmazonSqsPublishTopology(IMessageTopology messageTopology)
{
_messageTopology = messageTopology;
TopicAttributes = new Dictionary<string, object>();
TopicSubscriptionAttributes = new Dictionary<string, object>();
TopicTags = new Dictionary<string, string>();
}
public IDictionary<string, object> TopicAttributes { get; private set; }
public IDictionary<string, object> TopicSubscriptionAttributes { get; private set; }
public IDictionary<string, string> TopicTags { get; private set; }
IAmazonSqsMessagePublishTopology<T> IAmazonSqsPublishTopology.GetMessageTopology<T>()
{
return (GetMessageTopology<T>() as IAmazonSqsMessagePublishTopology<T>)!;
}
IAmazonSqsMessagePublishTopologyConfigurator IAmazonSqsPublishTopologyConfigurator.GetMessageTopology(Type messageType)
{
return (GetMessageTopology(messageType) as IAmazonSqsMessagePublishTopologyConfigurator)!;
}
public BrokerTopology GetPublishBrokerTopology()
{
var builder = new PublishEndpointBrokerTopologyBuilder();
ForEachMessageType<IAmazonSqsMessagePublishTopology>(x =>
{
x.Apply(builder);
builder.Topic = null;
});
return builder.BuildBrokerTopology();
}
IAmazonSqsMessagePublishTopologyConfigurator<T> IAmazonSqsPublishTopologyConfigurator.GetMessageTopology<T>()
{
return (GetMessageTopology<T>() as IAmazonSqsMessagePublishTopologyConfigurator<T>)!;
}
protected override IMessagePublishTopologyConfigurator CreateMessageTopology<T>()
{
var messageTopology = new AmazonSqsMessagePublishTopology<T>(this, _messageTopology.GetMessageTopology<T>());
OnMessageTopologyCreated(messageTopology);
return messageTopology;
}
}
| AmazonSqsPublishTopology |
csharp | microsoft__semantic-kernel | dotnet/src/Connectors/Connectors.AzureAIInference/Settings/AzureAIInferencePromptExecutionSettings.cs | {
"start": 6239,
"end": 10280
} | class ____ need to be assigned here, or this property needs to be casted to one of the possible derived classes.
/// The available derived classes include <see cref="ChatCompletionsToolDefinition"/>.
/// </summary>
[JsonPropertyName("tools")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IList<ChatCompletionsToolDefinition>? Tools
{
get => this._tools;
set
{
this.ThrowIfFrozen();
this._tools = value;
}
}
/// <summary>
/// If specified, the system will make a best effort to sample deterministically such that repeated requests with the
/// same seed and parameters should return the same result. Determinism is not guaranteed.
/// </summary>
[JsonPropertyName("seed")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? Seed
{
get => this._seed;
set
{
this.ThrowIfFrozen();
this._seed = value;
}
}
/// <inheritdoc/>
public override void Freeze()
{
if (this.IsFrozen)
{
return;
}
base.Freeze();
if (this._stopSequences is not null)
{
this._stopSequences = new ReadOnlyCollection<string>(this._stopSequences);
}
if (this._tools is not null)
{
this._tools = new ReadOnlyCollection<ChatCompletionsToolDefinition>(this._tools);
}
}
/// <inheritdoc/>
public override PromptExecutionSettings Clone()
{
return new AzureAIInferencePromptExecutionSettings()
{
ExtraParameters = this.ExtraParameters,
FrequencyPenalty = this.FrequencyPenalty,
PresencePenalty = this.PresencePenalty,
Temperature = this.Temperature,
NucleusSamplingFactor = this.NucleusSamplingFactor,
MaxTokens = this.MaxTokens,
ResponseFormat = this.ResponseFormat,
StopSequences = this.StopSequences is not null ? new List<string>(this.StopSequences) : null,
Tools = this.Tools is not null ? new List<ChatCompletionsToolDefinition>(this.Tools) : null,
Seed = this.Seed,
ExtensionData = this.ExtensionData is not null ? new Dictionary<string, object>(this.ExtensionData) : null,
};
}
/// <summary>
/// Create a new settings object with the values from another settings object.
/// </summary>
/// <param name="executionSettings">Template configuration</param>
/// <returns>An instance of <see cref="AzureAIInferencePromptExecutionSettings"/></returns>
public static AzureAIInferencePromptExecutionSettings FromExecutionSettings(PromptExecutionSettings? executionSettings)
{
if (executionSettings is null)
{
return new AzureAIInferencePromptExecutionSettings();
}
if (executionSettings is AzureAIInferencePromptExecutionSettings settings)
{
return settings;
}
var json = JsonSerializer.Serialize(executionSettings);
var aiInferenceSettings = JsonSerializer.Deserialize<AzureAIInferencePromptExecutionSettings>(json, JsonOptionsCache.ReadPermissive);
if (aiInferenceSettings is not null)
{
return aiInferenceSettings;
}
throw new ArgumentException($"Invalid execution settings, cannot convert to {nameof(AzureAIInferencePromptExecutionSettings)}", nameof(executionSettings));
}
#region private ================================================================================
private string? _extraParameters;
private float? _frequencyPenalty;
private float? _presencePenalty;
private float? _temperature;
private float? _nucleusSamplingFactor;
private int? _maxTokens;
private object? _responseFormat;
private IList<string>? _stopSequences;
private IList<ChatCompletionsToolDefinition>? _tools;
private long? _seed;
#endregion
}
| might |
csharp | RicoSuter__NSwag | src/NSwag.Generation.WebApi.Tests/OperationProcessors/ApiVersionProcessorWithWebApiTests.cs | {
"start": 733,
"end": 2868
} | public class ____ : ApiController
{
[HttpGet, Route("api/v{version:apiVersion}/foo")]
public void Foo()
{
}
[HttpGet, Route("api/v{version:apiVersion}/bar")]
public void Bar()
{
}
}
[TestMethod]
public async Task When_no_IncludedVersions_are_defined_then_all_routes_are_available_and_replaced()
{
// Arrange
var settings = new WebApiOpenApiDocumentGeneratorSettings();
var generator = new WebApiOpenApiDocumentGenerator(settings);
// Act
var document = await generator.GenerateForControllersAsync(new List<Type>
{
typeof(VersionedControllerV1),
typeof(VersionedControllerV2)
});
// Assert
Assert.AreEqual(4, document.Paths.Count);
Assert.IsTrue(document.Paths.ContainsKey("/api/v1/foo"));
Assert.IsTrue(document.Paths.ContainsKey("/api/v1/bar"));
Assert.IsTrue(document.Paths.ContainsKey("/api/v2/foo"));
Assert.IsTrue(document.Paths.ContainsKey("/api/v2/bar"));
}
[TestMethod]
public async Task When_IncludedVersions_are_set_then_only_these_are_available_in_document()
{
// Arrange
var settings = new WebApiOpenApiDocumentGeneratorSettings();
settings.OperationProcessors.TryGet<ApiVersionProcessor>().IncludedVersions = new[] { "1" };
var generator = new WebApiOpenApiDocumentGenerator(settings);
// Act
var document = await generator.GenerateForControllersAsync(new List<Type>
{
typeof(VersionedControllerV1),
typeof(VersionedControllerV2)
});
var json = document.ToJson();
// Assert
Assert.AreEqual(2, document.Paths.Count);
Assert.IsTrue(document.Paths.ContainsKey("/api/v1/foo"));
Assert.IsTrue(document.Paths.ContainsKey("/api/v1/bar"));
}
}
}
| VersionedControllerV2 |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 904487,
"end": 906642
} | public partial class ____ : global::System.IEquatable<UnpublishClient_UnpublishClient_Errors_ConcurrentOperationError>, IUnpublishClient_UnpublishClient_Errors_ConcurrentOperationError
{
public UnpublishClient_UnpublishClient_Errors_ConcurrentOperationError(global::System.String __typename, global::System.String message)
{
this.__typename = __typename;
Message = message;
}
/// <summary>
/// The name of the current Object type at runtime.
/// </summary>
public global::System.String __typename { get; }
public global::System.String Message { get; }
public virtual global::System.Boolean Equals(UnpublishClient_UnpublishClient_Errors_ConcurrentOperationError? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (__typename.Equals(other.__typename)) && Message.Equals(other.Message);
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((UnpublishClient_UnpublishClient_Errors_ConcurrentOperationError)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * __typename.GetHashCode();
hash ^= 397 * Message.GetHashCode();
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| UnpublishClient_UnpublishClient_Errors_ConcurrentOperationError |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.AI.Abstractions/Embeddings/Embedding.cs | {
"start": 393,
"end": 1074
} | class ____ metadata about the embedding. Derived types provide the concrete data contained in the embedding.</remarks>
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
[JsonDerivedType(typeof(BinaryEmbedding), typeDiscriminator: "binary")]
[JsonDerivedType(typeof(Embedding<byte>), typeDiscriminator: "uint8")]
[JsonDerivedType(typeof(Embedding<sbyte>), typeDiscriminator: "int8")]
#if NET
[JsonDerivedType(typeof(Embedding<Half>), typeDiscriminator: "float16")]
#endif
[JsonDerivedType(typeof(Embedding<float>), typeDiscriminator: "float32")]
[JsonDerivedType(typeof(Embedding<double>), typeDiscriminator: "float64")]
[DebuggerDisplay("Dimensions = {Dimensions}")]
| provides |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Demo/AdminMenu.cs | {
"start": 101,
"end": 2097
} | public sealed class ____ : AdminNavigationProvider
{
internal readonly IStringLocalizer S;
public AdminMenu(IStringLocalizer<AdminMenu> stringLocalizer)
{
S = stringLocalizer;
}
protected override ValueTask BuildAsync(NavigationBuilder builder)
{
builder
.Add(S["Demo"], "10", demo => demo
.AddClass("demo").Id("demo")
.Add(S["This Menu Item 1"], "0", item => item
.Add(S["This is Menu Item 1.1"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
.Add(S["This is Menu Item 1.2"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
.Add(S["This is Menu Item 1.2"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
)
.Add(S["This Menu Item 2"], "0", item => item
.Add(S["This is Menu Item 2.1"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
.Add(S["This is Menu Item 2.2"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
.Add(S["This is Menu Item 3.2"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
)
.Add(S["This Menu Item 3"], "0", item => item
.Add(S["This is Menu Item 3.1"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
.Add(S["This is Menu Item 3.2"], subItem => subItem
.Action("Index", "Admin", "OrchardCore.Demo"))
)
.Add(S["Todo (Liquid - Frontend)"], "0", item => item
.Action("Index", "Todo", "OrchardCore.Demo")
)
);
return ValueTask.CompletedTask;
}
}
| AdminMenu |
csharp | smartstore__Smartstore | src/Smartstore.Web.Common/Rendering/Menus/IMenuExtensions.cs | {
"start": 86,
"end": 979
} | public static class ____
{
/// <summary>
/// Creates a menu model.
/// </summary>
/// <param name="menu">Menu.</param>
/// <param name="actionContext">Action context to resolve current node. Can be <c>null</c>.</param>
/// <returns>Menu model.</returns>
public static async Task<MenuModel> CreateModelAsync(this IMenu menu, string template, ActionContext actionContext)
{
Guard.NotNull(menu);
var model = new MenuModel
{
Name = menu.Name,
Template = template ?? menu.Name,
Root = await menu.GetRootNodeAsync(),
SelectedNode = await menu.ResolveCurrentNodeAsync(actionContext)
};
await menu.ResolveElementCountAsync(model.SelectedNode, false);
return model;
}
}
}
| IMenuExtensions |
csharp | FastEndpoints__FastEndpoints | Src/Library/Endpoint/Processor/IPostProcessorContext.cs | {
"start": 207,
"end": 363
} | interface ____ a post-processor context, containing essential properties
/// to access request, response, and associated processing details.
/// </summary>
| for |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Controllers/CommonController.cs | {
"start": 5719,
"end": 18174
} | class
____ (HttpContext.Items["grand.RedirectFromGenericPathRoute"] == null ||
!Convert.ToBoolean(HttpContext.Items["grand.RedirectFromGenericPathRoute"]))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
//home page
if (string.IsNullOrEmpty(url))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
//prevent open redirection attack
if (!Url.IsLocalUrl(url))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
url = Flurl.Url.EncodeIllegalCharacters(url);
return permanentRedirect ? RedirectPermanent(url) : Redirect(url);
}
[DenySystemAccount]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetCurrency(
[FromServices] ICurrencyService currencyService,
[FromServices] ICustomerService customerService,
string currencyCode, string returnUrl = "")
{
var currency = await currencyService.GetCurrencyByCode(currencyCode);
if (currency != null)
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CurrencyId,
currency.Id, _contextAccessor.StoreContext.CurrentStore.Id);
//clear coupon code
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.DiscountCoupons, "");
//clear gift card
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, "");
//notification
await _mediator.Publish(new ChangeCurrencyEvent(_contextAccessor.WorkContext.CurrentCustomer, currency));
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
return Redirect(returnUrl);
}
[DenySystemAccount]
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetStore(
[FromServices] IStoreService storeService,
[FromServices] CommonSettings commonSettings,
[FromServices] ICookieOptionsFactory cookieOptionsFactory,
string shortcut, string returnUrl = "")
{
var currentstoreShortcut = _contextAccessor.StoreContext.CurrentStore.Shortcut;
if (currentstoreShortcut != shortcut)
if (commonSettings.AllowToSelectStore)
{
var selectedstore = (await storeService.GetAllStores()).FirstOrDefault(x =>
string.Equals(x.Shortcut, shortcut, StringComparison.InvariantCultureIgnoreCase));
if (selectedstore != null)
{
SetStoreCookie(selectedstore);
//notification
await _mediator.Publish(new ChangeStoreEvent(_contextAccessor.WorkContext.CurrentCustomer, selectedstore));
if (selectedstore.Url != _contextAccessor.StoreContext.CurrentStore.Url)
return Redirect(selectedstore.SslEnabled ? selectedstore.SecureUrl : selectedstore.Url);
}
}
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
return Redirect(returnUrl);
void SetStoreCookie(Store store)
{
if (store == null)
return;
//remove current cookie
HttpContext.Response.Cookies.Delete(CommonHelper.StoreCookieName);
//set new cookie value
var options = cookieOptionsFactory.Create();
HttpContext.Response.Cookies.Append(CommonHelper.StoreCookieName, store.Id, options);
}
}
[DenySystemAccount]
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetTaxType(
[FromServices] TaxSettings taxSettings,
[FromServices] ICustomerService customerService,
int customerTaxType, string returnUrl = "")
{
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
var taxDisplayType = (TaxDisplayType)Enum.ToObject(typeof(TaxDisplayType), customerTaxType);
//whether customers are allowed to select tax display type
if (!taxSettings.AllowCustomersToSelectTaxDisplayType)
return Redirect(returnUrl);
//save passed value
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TaxDisplayTypeId, (int)taxDisplayType, _contextAccessor.StoreContext.CurrentStore.Id);
//notification
await _mediator.Publish(new ChangeTaxTypeEvent(_contextAccessor.WorkContext.CurrentCustomer, taxDisplayType));
return Redirect(returnUrl);
}
[DenySystemAccount]
[HttpGet]
public virtual async Task<IActionResult> SetStoreTheme(
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] IThemeContextFactory themeContextFactory, string themeName, string returnUrl = "")
{
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
if (!storeInformationSettings.AllowCustomerToSelectTheme) return Redirect(returnUrl);
var themeContext = themeContextFactory.GetThemeContext("");
if (themeContext != null) await themeContext.SetTheme(themeName);
//notification
await _mediator.Publish(new ChangeThemeEvent(_contextAccessor.WorkContext.CurrentCustomer, themeName));
return Redirect(returnUrl);
}
//sitemap page
[HttpGet]
public virtual async Task<IActionResult> Sitemap([FromServices] CommonSettings commonSettings)
{
if (!commonSettings.SitemapEnabled)
return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetSitemap {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
return View(model);
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> CookieAccept(bool accept,
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] ICustomerService customerService,
[FromServices] ICookiePreference cookiePreference)
{
if (!storeInformationSettings.DisplayCookieInformation)
//disabled
return Json(new { stored = false });
//save consent cookies
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
_contextAccessor.StoreContext.CurrentStore.Id);
var consentCookies = cookiePreference.GetConsentCookies();
var dictionary = consentCookies.Where(x => x.AllowToDisable).ToDictionary(item => item.SystemName, item => accept);
if (dictionary.Any())
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies,
dictionary, _contextAccessor.StoreContext.CurrentStore.Id);
//save setting - CookieAccepted
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CookieAccepted,
true, _contextAccessor.StoreContext.CurrentStore.Id);
return Json(new { stored = true });
}
[ClosedStore(true)]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> PrivacyPreference([FromServices] StoreInformationSettings
storeInformationSettings)
{
if (!storeInformationSettings.DisplayPrivacyPreference)
//disabled
return Json(new { html = "" });
var model = await _mediator.Send(new GetPrivacyPreference {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Store = _contextAccessor.StoreContext.CurrentStore
});
return Json(new
{
html = await this.RenderPartialViewToString("PrivacyPreference", model, true),
model
});
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> PrivacyPreference(IDictionary<string, string> model,
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] ICustomerService customerService,
[FromServices] ICookiePreference cookiePreference)
{
if (!storeInformationSettings.DisplayPrivacyPreference)
return Json(new { success = false });
const string consent = "ConsentCookies";
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
_contextAccessor.StoreContext.CurrentStore.Id);
var selectedConsentCookies = new List<string>();
foreach (var item in model)
if (item.Key.StartsWith(consent))
selectedConsentCookies.Add(item.Value);
var dictionary = new Dictionary<string, bool>();
var consentCookies = cookiePreference.GetConsentCookies();
foreach (var item in consentCookies)
if (item.AllowToDisable)
dictionary.Add(item.SystemName, selectedConsentCookies.Contains(item.SystemName));
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, dictionary, _contextAccessor.StoreContext.CurrentStore.Id);
return Json(new { success = true });
}
//robots.txt file
[ClosedStore(true)]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> RobotsTextFile()
{
var sb = await _mediator.Send(new GetRobotsTextFile { StoreId = _contextAccessor.StoreContext.CurrentStore.Id });
return Content(sb, "text/plain");
}
[IgnoreApi]
[HttpGet]
public virtual IActionResult GenericUrl()
{
//not found
return NotFound();
}
[ClosedStore(true)]
[PublicStore(true)]
[IgnoreApi]
[HttpGet]
public virtual IActionResult StoreClosed()
{
return View();
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> SaveCurrentPosition(
LocationModel model,
[FromServices] CustomerSettings customerSettings)
{
if (!customerSettings.GeoEnabled)
return Content("");
await _mediator.Send(new CurrentPositionCommand { Customer = _contextAccessor.WorkContext.CurrentCustomer, Model = model });
return Content("");
}
[AllowAnonymous]
[IgnoreApi]
[HttpGet]
public virtual async Task<IActionResult> QueuedEmail([FromServices] IQueuedEmailService queuedEmailService, string emailId)
{
if (string.IsNullOrEmpty(emailId))
{
return GetTrackingPixel();
}
var isFromAdmin = Request.GetTypedHeaders().Referer?.ToString()?.Contains("admin/queuedemail/edit/",
StringComparison.OrdinalIgnoreCase) ?? false;
if (!isFromAdmin)
{
var queuedEmail = await queuedEmailService.GetQueuedEmailById(emailId);
if (queuedEmail != null && queuedEmail.ReadOnUtc == null)
{
queuedEmail.ReadOnUtc = DateTime.UtcNow;
await queuedEmailService.UpdateQueuedEmail(queuedEmail);
}
}
return GetTrackingPixel();
IActionResult GetTrackingPixel()
{
const string TRACKING_PIXEL = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
return File(
Convert.FromBase64String(TRACKING_PIXEL),
"image/png",
"pixel.png"
);
}
}
#endregion
} | if |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/Query/AdHocMiscellaneousQueryTestBase.cs | {
"start": 17257,
"end": 17545
} | public class ____
{
public int Id { get; set; }
public Permission Permission { get; set; }
public PermissionByte PermissionByte { get; set; }
public PermissionShort PermissionShort { get; set; }
}
[Flags]
| Entity |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.TestHelpers/JsonDrivenTests/EmbeddedResourceJsonFileReader.cs | {
"start": 856,
"end": 2693
} | public abstract class ____
{
// protected properties
protected virtual Assembly Assembly => this.GetType().GetTypeInfo().Assembly;
protected virtual string PathPrefix { get; } = null;
protected virtual string[] PathPrefixes { get; } = null;
protected virtual BsonDocument ReadJsonDocument(string path)
{
var jsonReaderSettings = new JsonReaderSettings();
using (var stream = Assembly.GetManifestResourceStream(path))
using (var streamReader = new StreamReader(stream))
using (var jsonReader = new JsonReader(streamReader, jsonReaderSettings))
{
var context = BsonDeserializationContext.CreateRoot(jsonReader);
var document = BsonDocumentSerializer.Instance.Deserialize(context);
document.InsertAt(0, new BsonElement("_path", path));
return document;
}
}
protected virtual IEnumerable<BsonDocument> ReadJsonDocuments()
{
return
Assembly.GetManifestResourceNames()
.Where(ShouldReadJsonDocument)
.Select(ReadJsonDocument);
}
protected virtual bool ShouldReadJsonDocument(string path)
{
var prefixes = GetPathPrefixes();
return prefixes.Any(path.StartsWith) && path.EndsWith(".json");
}
private string[] GetPathPrefixes()
{
var prefixes = !string.IsNullOrEmpty(PathPrefix) ? new[] { PathPrefix } : PathPrefixes;
if (prefixes == null || prefixes.Length == 0)
{
throw new NotImplementedException("At least one path prefix must be specified.");
}
return prefixes;
}
}
}
| EmbeddedResourceJsonFileReader |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Misc.Zettle/Domain/Api/OAuth/GetUserInfoRequest.cs | {
"start": 156,
"end": 469
} | public class ____ : OAuthApiRequest, IAuthorizedRequest
{
/// <summary>
/// Gets the request path
/// </summary>
public override string Path => "users/self";
/// <summary>
/// Gets the request method
/// </summary>
public override string Method => HttpMethods.Get;
} | GetUserInfoRequest |
csharp | restsharp__RestSharp | test/RestSharp.Tests.Integrated/CompressionTests.cs | {
"start": 139,
"end": 2625
} | public class ____ {
static async Task<byte[]> GetBody(Func<Stream, Stream> getStream, string value) {
using var memoryStream = new MemoryStream();
// ReSharper disable once UseAwaitUsing
using (var stream = getStream(memoryStream)) {
stream.WriteStringUtf8(value);
}
memoryStream.Seek(0, SeekOrigin.Begin);
var body = await memoryStream.ReadAsBytes(default);
return body;
}
static void ConfigureServer(WireMockServer server, byte[] body, string encoding)
=> server
.Given(Request.Create().WithPath("/").UsingGet())
.RespondWith(Response.Create().WithBody(body).WithHeader("Content-Encoding", encoding));
[Fact]
public async Task Can_Handle_Deflate_Compressed_Content() {
const string value = "This is some deflated content";
using var server = WireMockServer.Start();
var body = await GetBody(s => new DeflateStream(s, CompressionMode.Compress, true), value);
ConfigureServer(server, body, "deflate");
using var client = new RestClient(server.Url!, options => options.AutomaticDecompression = DecompressionMethods.Deflate);
var request = new RestRequest("");
var response = await client.ExecuteAsync(request);
response.Content.Should().Be(value);
}
[Fact]
public async Task Can_Handle_Gzip_Compressed_Content() {
const string value = "This is some gzipped content";
using var server = WireMockServer.Start();
var body = await GetBody(s => new GZipStream(s, CompressionMode.Compress, true), value);
ConfigureServer(server, body, "gzip");
using var client = new RestClient(server.Url!);
var request = new RestRequest("");
var response = await client.ExecuteAsync(request);
response.Content.Should().Be(value);
}
[Fact]
public async Task Can_Handle_Uncompressed_Content() {
const string value = "This is some sample content";
using var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath("/").UsingGet())
.RespondWith(Response.Create().WithBody(value));
using var client = new RestClient(server.Url!);
var request = new RestRequest("");
var response = await client.ExecuteAsync(request);
response.Content.Should().Be(value);
}
} | CompressionTests |
csharp | spectreconsole__spectre.console | docs/src/Shortcodes/EmojiTableShortcode.cs | {
"start": 171,
"end": 1821
} | public class ____ : SyncShortcode
{
public override ShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context)
{
var emojis = context.Outputs
.FromPipeline(nameof(EmojiPipeline))
.OfType<ObjectDocument<List<Emoji>>>()
.First().Object;
// Headers
var table = new XElement("table", new XAttribute("class", "table"), new XAttribute("id", "emoji-results"));
var tHead = new XElement("thead");
var header = new XElement("tr", new XAttribute("class", "emoji-row-header"));
header.Add(new XElement("th", ""));
header.Add(new XElement("th", "Markup"));
header.Add(new XElement("th", "Constant", new XAttribute("class", "hidden md:table-cell")));
tHead.Add(header);
table.Add(tHead);
var tBody = new XElement("tbody");
foreach (var emoji in emojis)
{
var icon = $"&#x{emoji.Code.Replace("U+", string.Empty)};";
var row = new XElement("tr", new XAttribute("class", "search-row"));
row.Add(new XElement("td", icon));
row.Add(new XElement("td", new XElement("code", $":{emoji.Id}:")));
row.Add(new XElement("td", new XElement("code", emoji.Name), new XAttribute("class", "hidden md:table-cell")));
tBody.Add(row);
}
table.Add(tBody);
return table.ToString()
.Replace("&#x", "&#x");
}
}
} | EmojiTableShortcode |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Contexts/Context/SendEndpointConverterCache.cs | {
"start": 2419,
"end": 3230
} | interface ____
{
Task Send(ISendEndpoint endpoint, object message, CancellationToken cancellationToken = default);
Task Send(ISendEndpoint endpoint, object message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default);
Task SendInitializer(ISendEndpoint endpoint, object values, CancellationToken cancellationToken = default);
Task SendInitializer(ISendEndpoint endpoint, object values, IPipe<SendContext> pipe, CancellationToken cancellationToken = default);
}
/// <summary>
/// Converts the object type message to the appropriate generic type and invokes the send method with that
/// generic overload.
/// </summary>
/// <typeparam name="T"></typeparam>
| ISendEndpointConverter |
csharp | dotnet__orleans | src/Orleans.Runtime/Lifecycle/ISiloLifecycle.cs | {
"start": 387,
"end": 769
} | public interface ____ : ILifecycleObservable
{
/// <summary>
/// The highest lifecycle stage which has completed starting.
/// </summary>
int HighestCompletedStage { get; }
/// <summary>
/// The lowest lifecycle stage which has completed stopping.
/// </summary>
int LowestStoppedStage { get; }
}
}
| ISiloLifecycle |
csharp | files-community__Files | src/Files.App.Controls/Omnibar/Omnibar.cs | {
"start": 255,
"end": 10150
} | public partial class ____ : Control
{
// Constants
private const string TemplatePartName_AutoSuggestBox = "PART_TextBox";
private const string TemplatePartName_ModesHostGrid = "PART_ModesHostGrid";
private const string TemplatePartName_AutoSuggestBoxSuggestionsPopup = "PART_SuggestionsPopup";
private const string TemplatePartName_AutoSuggestBoxSuggestionsContainerBorder = "PART_SuggestionsContainerBorder";
private const string TemplatePartName_SuggestionsListView = "PART_SuggestionsListView";
// Fields
private TextBox _textBox = null!;
private Grid _modesHostGrid = null!;
private Popup _textBoxSuggestionsPopup = null!;
private Border _textBoxSuggestionsContainerBorder = null!;
private ListView _textBoxSuggestionsListView = null!;
private string _userInput = string.Empty;
private OmnibarTextChangeReason _textChangeReason = OmnibarTextChangeReason.None;
private WeakReference<UIElement?> _previouslyFocusedElement = new(null);
// Events
public event TypedEventHandler<Omnibar, OmnibarQuerySubmittedEventArgs>? QuerySubmitted;
public event TypedEventHandler<Omnibar, OmnibarSuggestionChosenEventArgs>? SuggestionChosen;
public event TypedEventHandler<Omnibar, OmnibarTextChangedEventArgs>? TextChanged;
public event TypedEventHandler<Omnibar, OmnibarModeChangedEventArgs>? ModeChanged;
public event TypedEventHandler<Omnibar, OmnibarIsFocusedChangedEventArgs> IsFocusedChanged;
// Constructor
public Omnibar()
{
DefaultStyleKey = typeof(Omnibar);
Modes = [];
AutoSuggestBoxPadding = new(0, 0, 0, 0);
GlobalHelper.WriteDebugStringForOmnibar("Omnibar has been initialized.");
}
// Methods
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_textBox = GetTemplateChild(TemplatePartName_AutoSuggestBox) as TextBox
?? throw new MissingFieldException($"Could not find {TemplatePartName_AutoSuggestBox} in the given {nameof(Omnibar)}'s style.");
_modesHostGrid = GetTemplateChild(TemplatePartName_ModesHostGrid) as Grid
?? throw new MissingFieldException($"Could not find {TemplatePartName_ModesHostGrid} in the given {nameof(Omnibar)}'s style.");
_textBoxSuggestionsPopup = GetTemplateChild(TemplatePartName_AutoSuggestBoxSuggestionsPopup) as Popup
?? throw new MissingFieldException($"Could not find {TemplatePartName_AutoSuggestBoxSuggestionsPopup} in the given {nameof(Omnibar)}'s style.");
_textBoxSuggestionsContainerBorder = GetTemplateChild(TemplatePartName_AutoSuggestBoxSuggestionsContainerBorder) as Border
?? throw new MissingFieldException($"Could not find {TemplatePartName_AutoSuggestBoxSuggestionsContainerBorder} in the given {nameof(Omnibar)}'s style.");
_textBoxSuggestionsListView = GetTemplateChild(TemplatePartName_SuggestionsListView) as ListView
?? throw new MissingFieldException($"Could not find {TemplatePartName_SuggestionsListView} in the given {nameof(Omnibar)}'s style.");
PopulateModes();
SizeChanged += Omnibar_SizeChanged;
_textBox.GettingFocus += AutoSuggestBox_GettingFocus;
_textBox.GotFocus += AutoSuggestBox_GotFocus;
_textBox.LosingFocus += AutoSuggestBox_LosingFocus;
_textBox.LostFocus += AutoSuggestBox_LostFocus;
_textBox.KeyDown += AutoSuggestBox_KeyDown;
_textBox.TextChanged += AutoSuggestBox_TextChanged;
_textBoxSuggestionsPopup.GettingFocus += AutoSuggestBoxSuggestionsPopup_GettingFocus;
_textBoxSuggestionsPopup.Opened += AutoSuggestBoxSuggestionsPopup_Opened;
_textBoxSuggestionsListView.ItemClick += AutoSuggestBoxSuggestionsListView_ItemClick;
_textBoxSuggestionsListView.SelectionChanged += AutoSuggestBoxSuggestionsListView_SelectionChanged;
// Set the default width
_textBoxSuggestionsContainerBorder.Width = ActualWidth;
GlobalHelper.WriteDebugStringForOmnibar("The template and the events have been initialized.");
}
public void PopulateModes()
{
if (Modes is null || _modesHostGrid is null)
return;
// Populate the modes
foreach (var mode in Modes)
{
// Insert a divider
if (_modesHostGrid.Children.Count is not 0)
{
var divider = new OmnibarModeSeparator();
_modesHostGrid.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
Grid.SetColumn(divider, _modesHostGrid.Children.Count);
_modesHostGrid.Children.Add(divider);
}
// Insert the mode
_modesHostGrid.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
Grid.SetColumn(mode, _modesHostGrid.Children.Count);
_modesHostGrid.Children.Add(mode);
mode.SetOwner(this);
}
}
protected void ChangeMode(OmnibarMode? oldMode, OmnibarMode newMode)
{
if (_modesHostGrid is null || Modes is null || CurrentSelectedMode is null)
return;
foreach (var mode in Modes)
{
// Add the reposition transition to the all modes
mode.Transitions = [new RepositionThemeTransition()];
mode.UpdateLayout();
mode.IsTabStop = false;
}
var index = _modesHostGrid.Children.IndexOf(newMode);
if (oldMode is not null)
VisualStateManager.GoToState(oldMode, "Unfocused", true);
DispatcherQueue.TryEnqueue(() =>
{
// Reset
foreach (var column in _modesHostGrid.ColumnDefinitions)
column.Width = GridLength.Auto;
// Expand the given mode
_modesHostGrid.ColumnDefinitions[index].Width = new(1, GridUnitType.Star);
});
var itemCount = Modes.Count;
var itemIndex = Modes.IndexOf(newMode);
var modeButtonWidth = newMode.ActualWidth;
var modeSeparatorWidth = itemCount is not 0 or 1 ? _modesHostGrid.Children[1] is FrameworkElement frameworkElement ? frameworkElement.ActualWidth : 0 : 0;
var leftPadding = (itemIndex + 1) * modeButtonWidth + modeSeparatorWidth * itemIndex;
var rightPadding = (itemCount - itemIndex - 1) * modeButtonWidth + modeSeparatorWidth * (itemCount - itemIndex - 1) + 8;
// Set the correct AutoSuggestBox cursor position
AutoSuggestBoxPadding = new(leftPadding, 0, rightPadding, 0);
_textChangeReason = OmnibarTextChangeReason.ProgrammaticChange;
ChangeTextBoxText(newMode.Text ?? string.Empty);
VisualStateManager.GoToState(newMode, "Focused", true);
newMode.IsTabStop = false;
ModeChanged?.Invoke(this, new(oldMode, newMode!));
_textBox.PlaceholderText = newMode.PlaceholderText ?? string.Empty;
_textBoxSuggestionsListView.ItemTemplate = newMode.ItemTemplate;
_textBoxSuggestionsListView.ItemsSource = newMode.ItemsSource;
if (newMode.IsAutoFocusEnabled)
{
_textBox.Focus(FocusState.Pointer);
}
else
{
if (IsFocused)
{
VisualStateManager.GoToState(newMode, "Focused", true);
VisualStateManager.GoToState(_textBox, "InputAreaVisible", true);
}
else if (newMode?.ContentOnInactive is not null)
{
VisualStateManager.GoToState(newMode, "CurrentUnfocused", true);
VisualStateManager.GoToState(_textBox, "InputAreaCollapsed", true);
}
else
{
VisualStateManager.GoToState(_textBox, "InputAreaVisible", true);
}
}
TryToggleIsSuggestionsPopupOpen(true);
// Remove the reposition transition from the all modes
foreach (var mode in Modes)
{
mode.Transitions.Clear();
mode.UpdateLayout();
}
GlobalHelper.WriteDebugStringForOmnibar($"Successfully changed Mode from {oldMode} to {newMode}");
}
internal protected void FocusTextBox()
{
_textBox.Focus(FocusState.Keyboard);
}
internal protected bool TryToggleIsSuggestionsPopupOpen(bool wantToOpen)
{
if (_textBoxSuggestionsPopup is null)
return false;
if (wantToOpen && (!IsFocused || CurrentSelectedMode?.ItemsSource is null || (CurrentSelectedMode?.ItemsSource is IList collection && collection.Count is 0)))
{
_textBoxSuggestionsPopup.IsOpen = false;
GlobalHelper.WriteDebugStringForOmnibar("The suggestions pop-up closed.");
return false;
}
if (CurrentSelectedMode is not null)
{
_textBoxSuggestionsListView.ItemTemplate = CurrentSelectedMode.ItemTemplate;
_textBoxSuggestionsListView.ItemsSource = CurrentSelectedMode.ItemsSource;
}
_textBoxSuggestionsPopup.IsOpen = wantToOpen;
GlobalHelper.WriteDebugStringForOmnibar("The suggestions pop-up is open.");
return false;
}
public void ChooseSuggestionItem(object obj, bool isOriginatedFromArrowKey = false)
{
if (CurrentSelectedMode is null)
return;
if (CurrentSelectedMode.UpdateTextOnSelect ||
(isOriginatedFromArrowKey && CurrentSelectedMode.UpdateTextOnArrowKeys))
{
_textChangeReason = OmnibarTextChangeReason.SuggestionChosen;
ChangeTextBoxText(GetObjectText(obj));
}
SuggestionChosen?.Invoke(this, new(CurrentSelectedMode, obj));
}
internal protected void ChangeTextBoxText(string text)
{
_textBox.Text = text;
// Move the cursor to the end of the TextBox
if (_textChangeReason == OmnibarTextChangeReason.SuggestionChosen)
_textBox?.Select(_textBox.Text.Length, 0);
}
private void SubmitQuery(object? item)
{
if (CurrentSelectedMode is null)
return;
QuerySubmitted?.Invoke(this, new OmnibarQuerySubmittedEventArgs(CurrentSelectedMode, item, _textBox.Text));
_textBoxSuggestionsPopup.IsOpen = false;
}
private string GetObjectText(object obj)
{
if (CurrentSelectedMode is null)
return string.Empty;
// Get the text to put into the text box from the chosen suggestion item
return obj is string text
? text
: obj is IOmnibarTextMemberPathProvider textMemberPathProvider
? textMemberPathProvider.GetTextMemberPath(CurrentSelectedMode.TextMemberPath ?? string.Empty)
: obj.ToString() ?? string.Empty;
}
private void RevertTextToUserInput()
{
if (CurrentSelectedMode is null)
return;
_textBoxSuggestionsListView.SelectedIndex = -1;
_textChangeReason = OmnibarTextChangeReason.ProgrammaticChange;
ChangeTextBoxText(_userInput ?? "");
}
}
}
| Omnibar |
csharp | louthy__language-ext | LanguageExt.Core/DataTypes/Record/RecordType.cs | {
"start": 564,
"end": 743
} | record ____
/// </summary>
public static Func<A, object, bool> Equality => RecordTypeEquality<A>.Equality;
/// <summary>
/// General typed equality function for | types |
csharp | EventStore__EventStore | src/KurrentDB.Testing.ClusterVNodeApp/RestClientShim.cs | {
"start": 341,
"end": 1536
} | public sealed class ____ : IAsyncInitializer, IDisposable {
[ClassDataSource<NodeShim>(Shared = SharedType.PerTestSession)]
public required NodeShim NodeShim { get; init; }
public IRestClient Client { get; private set; } = null!;
public async Task InitializeAsync() {
var username = NodeShim.NodeShimOptions.Username;
var password = NodeShim.NodeShimOptions.Password;
Client = new RestClient(
new RestClientOptions() {
Authenticator = new HttpBasicAuthenticator(
username: username,
password: password),
BaseUrl = NodeShim.Node.Uri,
RemoteCertificateValidationCallback = (_, _, _, _) => true,
ThrowOnAnyError = true,
}).AddDefaultHeaders(new() {
{ "Content-Type", "application/json"},
});
await new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions() {
Delay = TimeSpan.FromMilliseconds(1000),
MaxRetryAttempts = 5,
})
.Build()
.ExecuteAsync(async ct => {
var response = await Client.GetAsync(new RestRequest($"health/live"), ct);
if (response.StatusCode != HttpStatusCode.NoContent)
throw new Exception("Not ready yet");
});
}
public void Dispose() {
Client?.Dispose();
}
}
| RestClientShim |
csharp | simplcommerce__SimplCommerce | src/SimplCommerce.Infrastructure/Data/IRepositoryWithTypedId.cs | {
"start": 223,
"end": 572
} | public interface ____<T, TId> where T : IEntityWithTypedId<TId>
{
IQueryable<T> Query();
void Add(T entity);
void AddRange(IEnumerable<T> entity);
IDbContextTransaction BeginTransaction();
void SaveChanges();
Task SaveChangesAsync();
void Remove(T entity);
}
}
| IRepositoryWithTypedId |
csharp | dotnet__aspire | src/Shared/CoalescingAsyncOperation.cs | {
"start": 577,
"end": 3798
} | internal abstract class ____ : IDisposable
{
private readonly SemaphoreSlim _gate = new(1, 1);
private Task? _runningTask;
private CancellationTokenSource? _cts;
/// <summary>
/// Implement the core asynchronous operation logic. Implementations should throw if they fail.
/// </summary>
/// <param name="cancellationToken">Token signaled when the initial caller's token is cancelled or the instance disposed.</param>
protected abstract Task ExecuteCoreAsync(CancellationToken cancellationToken);
/// <summary>
/// Ensures that the core operation is running. Only one execution is active at once; if already
/// running this returns a task that completes when the in-flight operation finishes. If not running
/// a new execution starts.
/// </summary>
public async Task RunAsync(CancellationToken cancellationToken = default)
{
Task current;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_runningTask is { IsCompleted: false })
{
// Already running, coalesce onto the existing task
current = _runningTask;
}
else
{
// Start a new execution
_cts?.Dispose();
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
current = _runningTask = ExecuteWrapperAsync(_cts.Token);
_ = _runningTask.ContinueWith(static (t, state) =>
{
var self = (CoalescingAsyncOperation)state!;
self.ClearCompleted(t);
}, this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
finally
{
_gate.Release();
}
await current.WaitAsync(cancellationToken).ConfigureAwait(false);
}
private async Task ExecuteWrapperAsync(CancellationToken ct) => await ExecuteCoreAsync(ct).ConfigureAwait(false);
private void ClearCompleted(Task completed)
{
// Fire-and-forget async cleanup (no need to await where called).
_ = ClearCompletedAsync(completed);
}
private async Task ClearCompletedAsync(Task completed)
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (ReferenceEquals(completed, _runningTask))
{
_runningTask = null; // Allow GC of completed task.
}
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Disposes the coalescing operation, canceling any in-progress execution and releasing resources.
/// </summary>
public virtual void Dispose()
{
_gate.Wait();
try
{
try
{
_cts?.Cancel();
}
catch
{
// ignored
}
_cts?.Dispose();
_cts = null;
_runningTask = null;
}
finally
{
_gate.Release();
_gate.Dispose();
}
}
}
| CoalescingAsyncOperation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.