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 | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/ModelBuilding101SqlServerTest.cs | {
"start": 199,
"end": 429
} | public class ____ : ModelBuilding101RelationalTestBase
{
protected override DbContextOptionsBuilder ConfigureContext(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer();
}
| ModelBuilding101SqlServerTest |
csharp | AvaloniaUI__Avalonia | samples/SampleControls/HamburgerMenu/HamburgerMenu.cs | {
"start": 132,
"end": 2869
} | public class ____ : TabControl
{
private SplitView? _splitView;
public static readonly StyledProperty<IBrush?> PaneBackgroundProperty =
SplitView.PaneBackgroundProperty.AddOwner<HamburgerMenu>();
public IBrush? PaneBackground
{
get => GetValue(PaneBackgroundProperty);
set => SetValue(PaneBackgroundProperty, value);
}
public static readonly StyledProperty<IBrush?> ContentBackgroundProperty =
AvaloniaProperty.Register<HamburgerMenu, IBrush?>(nameof(ContentBackground));
public IBrush? ContentBackground
{
get => GetValue(ContentBackgroundProperty);
set => SetValue(ContentBackgroundProperty, value);
}
public static readonly StyledProperty<int> ExpandedModeThresholdWidthProperty =
AvaloniaProperty.Register<HamburgerMenu, int>(nameof(ExpandedModeThresholdWidth), 1008);
public int ExpandedModeThresholdWidth
{
get => GetValue(ExpandedModeThresholdWidthProperty);
set => SetValue(ExpandedModeThresholdWidthProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_splitView = e.NameScope.Find<SplitView>("PART_NavigationPane");
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == BoundsProperty && _splitView is not null)
{
var (oldBounds, newBounds) = change.GetOldAndNewValue<Rect>();
EnsureSplitViewMode(oldBounds, newBounds);
}
if (change.Property == SelectedItemProperty)
{
if (_splitView is not null && _splitView.DisplayMode == SplitViewDisplayMode.Overlay)
{
_splitView.SetCurrentValue(SplitView.IsPaneOpenProperty, false);
}
}
}
private void EnsureSplitViewMode(Rect oldBounds, Rect newBounds)
{
if (_splitView is not null)
{
var threshold = ExpandedModeThresholdWidth;
if (newBounds.Width >= threshold)
{
_splitView.DisplayMode = SplitViewDisplayMode.Inline;
_splitView.IsPaneOpen = true;
}
else if (newBounds.Width < threshold)
{
_splitView.DisplayMode = SplitViewDisplayMode.Overlay;
_splitView.IsPaneOpen = false;
}
}
}
}
}
| HamburgerMenu |
csharp | dotnet__tye | src/Microsoft.Tye.Core/KubernetesManifestInfo.cs | {
"start": 235,
"end": 625
} | public sealed class ____
{
public KubernetesManifestInfo()
{
// Create deployment and service by default
Deployment = new DeploymentManifestInfo();
Service = new ServiceManifestInfo();
}
public DeploymentManifestInfo? Deployment { get; }
public ServiceManifestInfo Service { get; }
}
}
| KubernetesManifestInfo |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Caching/test/Caching.Tests/CacheControlDirectiveTypeTests.cs | {
"start": 15321,
"end": 15406
} | public class ____
{
public IUnionType? GetField() => null;
}
}
| UnionQuery |
csharp | dotnet__aspnetcore | src/Hosting/Hosting/test/GenericWebHostBuilderTests.cs | {
"start": 656,
"end": 6599
} | public class ____
{
[Fact]
public void ReadsAspNetCoreEnvironmentVariables()
{
var randomEnvKey = Guid.NewGuid().ToString();
Environment.SetEnvironmentVariable("ASPNETCORE_" + randomEnvKey, "true");
using var host = new HostBuilder()
.ConfigureWebHost(_ => { })
.Build();
var config = host.Services.GetRequiredService<IConfiguration>();
Assert.Equal("true", config[randomEnvKey]);
Environment.SetEnvironmentVariable("ASPNETCORE_" + randomEnvKey, null);
}
[Fact]
public void CanSuppressAspNetCoreEnvironmentVariables()
{
var randomEnvKey = Guid.NewGuid().ToString();
Environment.SetEnvironmentVariable("ASPNETCORE_" + randomEnvKey, "true");
using var host = new HostBuilder()
.ConfigureWebHost(_ => { }, webHostBulderOptions => { webHostBulderOptions.SuppressEnvironmentConfiguration = true; })
.Build();
var config = host.Services.GetRequiredService<IConfiguration>();
Assert.Null(config[randomEnvKey]);
Environment.SetEnvironmentVariable("ASPNETCORE_" + randomEnvKey, null);
}
[Fact]
public void UseUrlsWorksAfterAppConfigurationSourcesAreCleared()
{
var server = new TestServer();
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseServer(server)
.UseUrls("TEST_URL")
.Configure(_ => { });
})
.ConfigureAppConfiguration(configBuilder =>
{
configBuilder.Sources.Clear();
})
.Build();
host.Start();
Assert.Equal("TEST_URL", server.Addresses.Single());
}
[Fact]
public void UseUrlsWorksAfterHostConfigurationSourcesAreCleared()
{
var server = new TestServer();
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseServer(server)
.UseUrls("TEST_URL")
.Configure(_ => { });
})
.ConfigureHostConfiguration(configBuilder =>
{
configBuilder.Sources.Clear();
})
.Build();
host.Start();
Assert.Equal("TEST_URL", server.Addresses.Single());
}
[Theory]
[InlineData(null, null, null, "")]
[InlineData("", "", "", "")]
[InlineData("http://urls", "", "", "http://urls")]
[InlineData("http://urls", "5000", "", "http://urls")]
[InlineData("http://urls", "", "5001", "http://urls")]
[InlineData("http://urls", "5000", "5001", "http://urls")]
[InlineData("", "5000", "", "http://*:5000")]
[InlineData("", "5000;5002;5004", "", "http://*:5000;http://*:5002;http://*:5004")]
[InlineData("", "", "5001", "https://*:5001")]
[InlineData("", "", "5001;5003;5005", "https://*:5001;https://*:5003;https://*:5005")]
[InlineData("", "5000", "5001", "http://*:5000;https://*:5001")]
[InlineData("", "5000;5002", "5001;5003", "http://*:5000;http://*:5002;https://*:5001;https://*:5003")]
public void ReadsUrlsOrPorts(string urls, string httpPorts, string httpsPorts, string expected)
{
var server = new TestServer();
using var host = new HostBuilder()
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("urls", urls),
new KeyValuePair<string, string>("http_ports", httpPorts),
new KeyValuePair<string, string>("https_ports", httpsPorts),
});
})
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseServer(server)
.Configure(_ => { });
})
.Build();
host.Start();
Assert.Equal(expected, string.Join(';', server.Addresses));
}
[Fact]
public async Task MultipleConfigureWebHostCallsWithUseStartupLastWins()
{
var server = new TestServer();
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseServer(server)
.UseStartup<FirstStartup>();
})
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseStartup<SecondStartup>();
})
.Build();
await host.StartAsync();
await AssertResponseContains(server.RequestDelegate, "SecondStartup");
}
[Fact]
public async Task MultipleConfigureWebHostCallsWithSameUseStartupOnlyRunsOne()
{
var server = new TestServer();
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseServer(server)
.UseStartup<FirstStartup>();
})
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseStartup<FirstStartup>();
})
.Build();
await host.StartAsync();
Assert.Single(host.Services.GetRequiredService<IEnumerable<FirstStartup>>());
}
private async Task AssertResponseContains(RequestDelegate app, string expectedText)
{
var httpContext = new DefaultHttpContext();
httpContext.Response.Body = new MemoryStream();
await app(httpContext);
httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
var bodyText = new StreamReader(httpContext.Response.Body).ReadToEnd();
Assert.Contains(expectedText, bodyText);
}
| GenericWebHostBuilderTests |
csharp | dotnet__aspnetcore | src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Shared/SharedTypes.Polymorphism.cs | {
"start": 511,
"end": 590
} | internal class ____ : Shape
{
public double Hypotenuse { get; set; }
}
| Triangle |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Dto/ClientCapabilitiesDto.cs | {
"start": 301,
"end": 2220
} | public class ____
{
/// <summary>
/// Gets or sets the list of playable media types.
/// </summary>
[JsonConverter(typeof(JsonCommaDelimitedCollectionConverterFactory))]
public IReadOnlyList<MediaType> PlayableMediaTypes { get; set; } = [];
/// <summary>
/// Gets or sets the list of supported commands.
/// </summary>
[JsonConverter(typeof(JsonCommaDelimitedCollectionConverterFactory))]
public IReadOnlyList<GeneralCommandType> SupportedCommands { get; set; } = [];
/// <summary>
/// Gets or sets a value indicating whether session supports media control.
/// </summary>
public bool SupportsMediaControl { get; set; }
/// <summary>
/// Gets or sets a value indicating whether session supports a persistent identifier.
/// </summary>
public bool SupportsPersistentIdentifier { get; set; }
/// <summary>
/// Gets or sets the device profile.
/// </summary>
public DeviceProfile? DeviceProfile { get; set; }
/// <summary>
/// Gets or sets the app store url.
/// </summary>
public string? AppStoreUrl { get; set; }
/// <summary>
/// Gets or sets the icon url.
/// </summary>
public string? IconUrl { get; set; }
/// <summary>
/// Convert the dto to the full <see cref="ClientCapabilities"/> model.
/// </summary>
/// <returns>The converted <see cref="ClientCapabilities"/> model.</returns>
public ClientCapabilities ToClientCapabilities()
{
return new ClientCapabilities
{
PlayableMediaTypes = PlayableMediaTypes,
SupportedCommands = SupportedCommands,
SupportsMediaControl = SupportsMediaControl,
SupportsPersistentIdentifier = SupportsPersistentIdentifier,
DeviceProfile = DeviceProfile,
AppStoreUrl = AppStoreUrl,
IconUrl = IconUrl
};
}
}
| ClientCapabilitiesDto |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Remote.Protocol/MetsysBson.cs | {
"start": 2657,
"end": 14291
} | internal class ____
{
private static readonly IDictionary<Type, Types> _typeMap = new Dictionary<Type, Types>
{
{typeof (int), Types.Int32},
{typeof (long), Types.Int64},
{typeof (bool), Types.Boolean},
{typeof (string), Types.String},
{typeof (double), Types.Double},
{typeof (Guid), Types.Binary},
{typeof (Regex), Types.Regex},
{typeof (DateTime), Types.DateTime},
{typeof (float), Types.Double},
{typeof (byte[]), Types.Binary},
{typeof (ObjectId), Types.ObjectId},
{typeof (ScopedCode), Types.ScopedCode}
};
private readonly BinaryWriter _writer;
private Document _current;
public static byte[] Serialize<T>(T document)
{
var type = document.GetType();
if (type.IsValueType ||
(typeof(IEnumerable).IsAssignableFrom(type) && typeof(IDictionary).IsAssignableFrom(type) == false)
)
{
throw new BsonException("Root type must be an object");
}
using (var ms = new MemoryStream(250))
using (var writer = new BinaryWriter(ms))
{
new Serializer(writer).WriteDocument(document);
return ms.ToArray();
}
}
public static byte[] Serialize(object document)
{
var type = document.GetType();
if (type.IsValueType ||
(typeof(IEnumerable).IsAssignableFrom(type) && typeof(IDictionary).IsAssignableFrom(type) == false)
)
{
throw new BsonException("Root type must be an object");
}
using (var ms = new MemoryStream(250))
using (var writer = new BinaryWriter(ms))
{
new Serializer(writer).WriteDocument(document);
return ms.ToArray();
}
}
private Serializer(BinaryWriter writer)
{
_writer = writer;
}
private void NewDocument()
{
var old = _current;
_current = new Document { Parent = old, Length = (int)_writer.BaseStream.Position, Digested = 4 };
_writer.Write(0); // length placeholder
}
private void EndDocument(bool includeEeo)
{
var old = _current;
if (includeEeo)
{
Written(1);
_writer.Write((byte)0);
}
_writer.Seek(_current.Length, SeekOrigin.Begin);
_writer.Write(_current.Digested); // override the document length placeholder
_writer.Seek(0, SeekOrigin.End); // back to the end
_current = _current.Parent;
if (_current != null)
{
Written(old.Digested);
}
}
private void Written(int length)
{
_current.Digested += length;
}
private void WriteDocument(object document)
{
NewDocument();
WriteObject(document);
EndDocument(true);
}
private void WriteObject(object document)
{
var asDictionary = document as IDictionary;
if (asDictionary != null)
{
Write(asDictionary);
return;
}
var typeHelper = TypeHelper.GetHelperForType(document.GetType());
foreach (var property in typeHelper.GetProperties())
{
if (property.Ignored) { continue; }
var name = property.Name;
var value = property.Getter(document);
if (value == null && property.IgnoredIfNull)
{
continue;
}
SerializeMember(name, value);
}
}
private void SerializeMember(string name, object value)
{
if (value == null)
{
Write(Types.Null);
WriteName(name);
return;
}
var type = value.GetType();
if (type.IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
Types storageType;
if (!_typeMap.TryGetValue(type, out storageType))
{
// this isn't a simple type;
Write(name, value);
return;
}
Write(storageType);
WriteName(name);
switch (storageType)
{
case Types.Int32:
Written(4);
_writer.Write((int)value);
return;
case Types.Int64:
Written(8);
_writer.Write((long)value);
return;
case Types.String:
Write((string)value);
return;
case Types.Double:
Written(8);
if (value is float)
{
_writer.Write(Convert.ToDouble((float)value));
}
else
{
_writer.Write((double)value);
}
return;
case Types.Boolean:
Written(1);
_writer.Write((bool)value ? (byte)1 : (byte)0);
return;
case Types.DateTime:
Written(8);
_writer.Write((long)((DateTime)value).ToUniversalTime().Subtract(Helper.Epoch).TotalMilliseconds);
return;
case Types.Binary:
WriteBinary(value);
return;
case Types.ScopedCode:
Write((ScopedCode)value);
return;
case Types.ObjectId:
Written(((ObjectId)value).Value.Length);
_writer.Write(((ObjectId)value).Value);
return;
case Types.Regex:
Write((Regex)value);
break;
}
}
private void Write(string name, object value)
{
if (value is IDictionary)
{
Write(Types.Object);
WriteName(name);
NewDocument();
Write((IDictionary)value);
EndDocument(true);
}
else if (value is IEnumerable)
{
Write(Types.Array);
WriteName(name);
NewDocument();
Write((IEnumerable)value);
EndDocument(true);
}
else
{
Write(Types.Object);
WriteName(name);
WriteDocument(value); // Write manages new/end document
}
}
private void Write(IEnumerable enumerable)
{
var index = 0;
foreach (var value in enumerable)
{
SerializeMember((index++).ToString(), value);
}
}
private void Write(IDictionary dictionary)
{
foreach (var key in dictionary.Keys)
{
SerializeMember((string)key, dictionary[key]);
}
}
private void WriteBinary(object value)
{
if (value is byte[])
{
var bytes = (byte[])value;
var length = bytes.Length;
_writer.Write(length + 4);
_writer.Write((byte)2);
_writer.Write(length);
_writer.Write(bytes);
Written(9 + length);
}
else if (value is Guid)
{
var guid = (Guid)value;
var bytes = guid.ToByteArray();
_writer.Write(bytes.Length);
_writer.Write((byte)3);
_writer.Write(bytes);
Written(5 + bytes.Length);
}
}
private void Write(Types type)
{
_writer.Write((byte)type);
Written(1);
}
private void WriteName(string name)
{
var bytes = Encoding.UTF8.GetBytes(name);
_writer.Write(bytes);
_writer.Write((byte)0);
Written(bytes.Length + 1);
}
private void Write(string name)
{
var bytes = Encoding.UTF8.GetBytes(name);
_writer.Write(bytes.Length + 1);
_writer.Write(bytes);
_writer.Write((byte)0);
Written(bytes.Length + 5); // stringLength + length + null byte
}
private void Write(Regex regex)
{
WriteName(regex.ToString());
var options = string.Empty;
if ((regex.Options & RegexOptions.ECMAScript) == RegexOptions.ECMAScript)
{
options = string.Concat(options, 'e');
}
if ((regex.Options & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
{
options = string.Concat(options, 'i');
}
if ((regex.Options & RegexOptions.CultureInvariant) == RegexOptions.CultureInvariant)
{
options = string.Concat(options, 'l');
}
if ((regex.Options & RegexOptions.Multiline) == RegexOptions.Multiline)
{
options = string.Concat(options, 'm');
}
if ((regex.Options & RegexOptions.Singleline) == RegexOptions.Singleline)
{
options = string.Concat(options, 's');
}
options = string.Concat(options, 'u'); // all .net regex are unicode regex, therefore:
if ((regex.Options & RegexOptions.IgnorePatternWhitespace) == RegexOptions.IgnorePatternWhitespace)
{
options = string.Concat(options, 'w');
}
if ((regex.Options & RegexOptions.ExplicitCapture) == RegexOptions.ExplicitCapture)
{
options = string.Concat(options, 'x');
}
WriteName(options);
}
private void Write(ScopedCode value)
{
NewDocument();
Write(value.CodeString);
WriteDocument(value.Scope);
EndDocument(false);
}
}
}
namespace Metsys.Bson
{
| Serializer |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Search/IMongoSearchIndexManager.cs | {
"start": 756,
"end": 861
} | interface ____ methods used to create, delete and modify search indexes.
/// </summary>
| representing |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Transforms/SetProperty_Specs.cs | {
"start": 1506,
"end": 2554
} | public class ____ :
InMemoryTestFixture
{
[Test]
public async Task Should_have_the_message_property()
{
await InputQueueSendEndpoint.Send(new A { First = "Hello" });
ConsumeContext<A> result = await _received;
Assert.Multiple(() =>
{
Assert.That(result.Message.First, Is.EqualTo("Hello"));
Assert.That(result.Message.Second, Is.EqualTo("World"));
});
}
#pragma warning disable NUnit1032
Task<ConsumeContext<A>> _received;
#pragma warning restore NUnit1032
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
base.ConfigureInMemoryReceiveEndpoint(configurator);
configurator.UseTransform<A>(t =>
{
t.Set(x => x.Second, context => "World");
});
_received = Handled<A>(configurator);
}
| Setting_a_property_on_a_new_message |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 372257,
"end": 372477
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1706 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1708> ChildEntities { get; set; }
}
| RelatedEntity1707 |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/MUX/Utilities/RunOnUIThread.cs | {
"start": 676,
"end": 4797
} | public class ____
{
public static void Execute(Action action)
{
Execute(CoreApplication.MainView, action);
}
public static void Execute(CoreApplicationView whichView, Action action)
{
Exception exception = null;
var dispatcher = whichView.Dispatcher;
if (dispatcher.HasThreadAccess)
{
action();
}
else
{
// We're not on the UI thread, queue the work. Make sure that the action is not run until
// the splash screen is dismissed (i.e. that the window content is present).
var workComplete = new AutoResetEvent(false);
#if MUX
App.RunAfterSplashScreenDismissed(() =>
#endif
{
// If the Splash screen dismissal happens on the UI thread, run the action right now.
if (dispatcher.HasThreadAccess)
{
try
{
action();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
}
else
{
// Otherwise queue the work to the UI thread and then set the completion event on that thread.
var ignore = dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
try
{
action();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
});
}
}
#if MUX
);
#endif
workComplete.WaitOne();
if (exception != null)
{
Verify.Fail("Exception thrown by action on the UI thread: " + exception.ToString());
}
}
}
public static async Task ExecuteAsync(Action action) =>
await ExecuteAsync(CoreApplication.MainView, () =>
{
action();
return Task.CompletedTask;
});
public static async Task ExecuteAsync(Func<Task> task) =>
await ExecuteAsync(CoreApplication.MainView, task);
public static async Task ExecuteAsync(CoreApplicationView whichView, Action action) =>
await ExecuteAsync(whichView, () =>
{
action();
return Task.CompletedTask;
});
public static async Task ExecuteAsync(CoreApplicationView whichView, Func<Task> task)
{
Exception exception = null;
var dispatcher = whichView.Dispatcher;
if (dispatcher.HasThreadAccess)
{
await task();
}
else
{
// We're not on the UI thread, queue the work. Make sure that the action is not run until
// the splash screen is dismissed (i.e. that the window content is present).
var workComplete = new AutoResetEvent(false);
#if MUX
App.RunAfterSplashScreenDismissed(() =>
#endif
{
// If the Splash screen dismissal happens on the UI thread, run the action right now.
if (dispatcher.HasThreadAccess)
{
try
{
await task();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
}
else
{
// Otherwise queue the work to the UI thread and then set the completion event on that thread.
await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
try
{
await task();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
});
}
}
#if MUX
);
#endif
workComplete.WaitOne();
if (exception != null)
{
Verify.Fail("Exception thrown by action on the UI thread: " + exception.ToString());
}
}
}
public async Task WaitForTick()
{
var renderingEventFired = new TaskCompletionSource<object>();
EventHandler<object> renderingCallback = (sender, arg) =>
{
renderingEventFired.TrySetResult(null);
};
CompositionTarget.Rendering += renderingCallback;
await renderingEventFired.Task;
CompositionTarget.Rendering -= renderingCallback;
}
}
}
| RunOnUIThread |
csharp | microsoft__semantic-kernel | dotnet/src/Agents/UnitTests/Core/ChatCompletionAgentExtensionsTests.cs | {
"start": 238,
"end": 4535
} | public sealed class ____
{
[Fact]
public void AsAIAgent_WithValidChatCompletionAgent_ReturnsSemanticKernelAIAgent()
{
// Arrange
var chatCompletionAgent = new ChatCompletionAgent()
{
Name = "TestAgent",
Instructions = "Test instructions"
};
// Act
var result = chatCompletionAgent.AsAIAgent();
// Assert
Assert.NotNull(result);
Assert.IsType<SemanticKernelAIAgent>(result);
}
[Fact]
public void AsAIAgent_WithNullChatCompletionAgent_ThrowsArgumentNullException()
{
// Arrange
ChatCompletionAgent nullAgent = null!;
// Act & Assert
Assert.Throws<ArgumentNullException>(() => nullAgent.AsAIAgent());
}
[Fact]
public void AsAIAgent_CreatesWorkingThreadFactory()
{
// Arrange
var chatCompletionAgent = new ChatCompletionAgent()
{
Name = "TestAgent",
Instructions = "Test instructions"
};
// Act
var result = chatCompletionAgent.AsAIAgent();
var thread = result.GetNewThread();
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithNullChatHistory_CreatesNewThread()
{
// Arrange
var chatCompletionAgent = new ChatCompletionAgent()
{
Name = "TestAgent",
Instructions = "Test instructions"
};
var jsonElement = JsonSerializer.SerializeToElement((ChatHistory?)null);
// Act
var result = chatCompletionAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
}
[Fact]
public void AsAIAgent_ThreadDeserializationFactory_WithValidChatHistory_CreatesThreadWithHistory()
{
// Arrange
var chatCompletionAgent = new ChatCompletionAgent()
{
Name = "TestAgent",
Instructions = "Test instructions"
};
var chatHistory = new ChatHistory();
chatHistory.AddSystemMessage("System message");
chatHistory.AddUserMessage("User message");
var jsonElement = JsonSerializer.SerializeToElement(chatHistory);
// Act
var result = chatCompletionAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Assert
Assert.NotNull(thread);
Assert.IsType<SemanticKernelAIAgentThread>(thread);
var threadAdapter = (SemanticKernelAIAgentThread)thread;
Assert.IsType<ChatHistoryAgentThread>(threadAdapter.InnerThread);
var chatHistoryThread = (ChatHistoryAgentThread)threadAdapter.InnerThread;
Assert.Equal(2, chatHistoryThread.ChatHistory.Count);
}
[Fact]
public void AsAIAgent_ThreadSerializer_SerializesChatHistory()
{
// Arrange
var chatCompletionAgent = new ChatCompletionAgent()
{
Name = "TestAgent",
Instructions = "Test instructions"
};
var chatHistory = new ChatHistory();
chatHistory.AddSystemMessage("System message");
chatHistory.AddUserMessage("User message");
var chatHistoryThread = new ChatHistoryAgentThread(chatHistory);
var jsonElement = JsonSerializer.SerializeToElement(chatHistory);
var result = chatCompletionAgent.AsAIAgent();
var thread = result.DeserializeThread(jsonElement);
// Act
var serializedElement = thread.Serialize();
// Assert
Assert.Equal(JsonValueKind.Array, serializedElement.ValueKind);
var deserializedChatHistory = JsonSerializer.Deserialize<ChatHistory>(serializedElement.GetRawText());
Assert.NotNull(deserializedChatHistory);
Assert.Equal(2, deserializedChatHistory.Count);
}
}
| ChatCompletionAgentExtensionsTests |
csharp | dotnet__orleans | test/DefaultCluster.Tests/ConcreteStateClassTests.cs | {
"start": 600,
"end": 2412
} | public class ____ : HostedTestClusterEnsureDefaultStarted
{
private readonly Random rand = new Random();
public StateClassTests(DefaultClusterFixture fixture) : base(fixture)
{
}
/// <summary>
/// Tests basic state persistence functionality.
/// Verifies that grain state persists across deactivation/reactivation cycles.
/// The test:
/// 1. Sets a value in grain state
/// 2. Deactivates the grain
/// 3. Reactivates the grain (gets new version/activation)
/// 4. Verifies the state value was preserved
/// </summary>
[Fact, TestCategory("BVT")]
public async Task StateClassTests_StateClass()
{
await StateClassTests_Test("UnitTests.Grains.SimplePersistentGrain");
}
/// <summary>
/// Helper method that performs the actual state persistence test.
/// Demonstrates that:
/// - Each grain activation gets a unique version identifier
/// - State changes survive grain deactivation
/// - New activations load the previously persisted state
/// </summary>
private async Task StateClassTests_Test(string grainClass)
{
var grain = this.GrainFactory.GetGrain<ISimplePersistentGrain>(GetRandomGrainId(), grainClass);
var originalVersion = await grain.GetVersion();
await grain.SetA(98, true); // deactivate grain after setting A
var newVersion = await grain.GetVersion(); // get a new version from the new activation
Assert.NotEqual(originalVersion, newVersion);
var a = await grain.GetA();
Assert.Equal(98, a); // value of A survive deactivation and reactivation of the grain
}
}
}
| StateClassTests |
csharp | dotnet__efcore | src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs | {
"start": 716,
"end": 3192
} | public class ____ : IMigrationsIdGenerator
{
private const string Format = "yyyyMMddHHmmss";
private DateTime _lastTimestamp = DateTime.MinValue;
private readonly object _lock = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual string GetName(string id)
=> id[(Format.Length + 1)..];
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool IsValidId(string value)
=> Regex.IsMatch(
value,
string.Format(CultureInfo.InvariantCulture, "^[0-9]{{{0}}}_.+", Format.Length),
default,
TimeSpan.FromMilliseconds(1000.0));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual string GenerateId(string name)
{
var now = DateTime.UtcNow;
var timestamp = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
lock (_lock)
{
if (timestamp <= _lastTimestamp)
{
timestamp = _lastTimestamp.AddSeconds(1);
}
_lastTimestamp = timestamp;
}
return timestamp.ToString(Format, CultureInfo.InvariantCulture) + "_" + name;
}
}
| MigrationsIdGenerator |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs | {
"start": 1556,
"end": 1637
} | class ____<TypeParameters> : BaseTypes where Constraints;
/// </summary>
| Name |
csharp | dotnet__machinelearning | src/Microsoft.ML.TimeSeries/SsaSpikeDetector.cs | {
"start": 3709,
"end": 9975
} | private sealed class ____ : SsaOptions
{
public BaseArguments(Options options)
{
Source = options.Source;
Name = options.Name;
Side = options.Side;
WindowSize = options.PvalueHistoryLength;
InitialWindowSize = options.TrainingWindowSize;
SeasonalWindowSize = options.SeasonalWindowSize;
AlertThreshold = 1 - options.Confidence / 100;
AlertOn = AlertingScore.PValueScore;
DiscountFactor = 1;
IsAdaptive = false;
ErrorFunction = options.ErrorFunction;
Martingale = MartingaleType.None;
}
}
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "SSPKTRNS",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(SsaSpikeDetector).Assembly.FullName);
}
internal SsaSpikeDetector(IHostEnvironment env, Options options, IDataView input)
: base(new BaseArguments(options), LoaderSignature, env)
{
InternalTransform.Model.Train(new RoleMappedData(input, null, InternalTransform.InputColumnName));
}
// Factory method for SignatureDataTransform.
private static IDataTransform Create(IHostEnvironment env, Options options, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(options, nameof(options));
env.CheckValue(input, nameof(input));
return new SsaSpikeDetector(env, options, input).MakeDataTransform(input);
}
internal SsaSpikeDetector(IHostEnvironment env, Options options)
: base(new BaseArguments(options), LoaderSignature, env)
{
// This constructor is empty.
}
// Factory method for SignatureLoadDataTransform.
private static IDataTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(ctx, nameof(ctx));
env.CheckValue(input, nameof(input));
return new SsaSpikeDetector(env, ctx).MakeDataTransform(input);
}
IStatefulTransformer IStatefulTransformer.Clone()
{
var clone = (SsaSpikeDetector)MemberwiseClone();
clone.InternalTransform.Model = clone.InternalTransform.Model.Clone();
clone.InternalTransform.StateRef = (SsaAnomalyDetectionBase.State)clone.InternalTransform.StateRef.Clone();
clone.InternalTransform.StateRef.InitState(clone.InternalTransform, InternalTransform.Host);
return clone;
}
// Factory method for SignatureLoadModel.
internal static SsaSpikeDetector Create(IHostEnvironment env, ModelLoadContext ctx)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel(GetVersionInfo());
return new SsaSpikeDetector(env, ctx);
}
private SsaSpikeDetector(IHostEnvironment env, ModelLoadContext ctx)
: base(env, ctx, LoaderSignature)
{
// *** Binary format ***
// <base>
InternalTransform.Host.CheckDecode(InternalTransform.ThresholdScore == AlertingScore.PValueScore);
InternalTransform.Host.CheckDecode(InternalTransform.DiscountFactor == 1);
InternalTransform.Host.CheckDecode(InternalTransform.IsAdaptive == false);
}
private protected override void SaveModel(ModelSaveContext ctx)
{
InternalTransform.Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
InternalTransform.Host.Assert(InternalTransform.ThresholdScore == AlertingScore.PValueScore);
InternalTransform.Host.Assert(InternalTransform.DiscountFactor == 1);
InternalTransform.Host.Assert(InternalTransform.IsAdaptive == false);
// *** Binary format ***
// <base>
base.SaveModel(ctx);
}
// Factory method for SignatureLoadRowMapper.
private static IRowMapper Create(IHostEnvironment env, ModelLoadContext ctx, DataViewSchema inputSchema)
=> Create(env, ctx).MakeRowMapper(inputSchema);
}
/// <summary>
/// Detect spikes in time series using Singular Spectrum Analysis.
/// </summary>
/// <remarks>
/// <format type="text/markdown"><)
///
/// [!include[io](~/../docs/samples/docs/api-reference/io-time-series-spike.md)]
///
/// ### Estimator Characteristics
/// | | |
/// | -- | -- |
/// | Does this estimator need to look at the data to train its parameters? | Yes |
/// | Input column data type | <xref:System.Single> |
/// | Output column data type | 3-element vector of <xref:System.Double> |
/// | Exportable to ONNX | No |
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-props.md)]
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-ssa.md)]
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-pvalue.md)]
///
/// Check the See Also section for links to usage examples.
/// ]]>
/// </format>
/// </remarks>
/// <seealso cref="Microsoft.ML.TimeSeriesCatalog.DetectSpikeBySsa(Microsoft.ML.TransformsCatalog,System.String,System.String,System.Double,System.Int32,System.Int32,System.Int32,Microsoft.ML.Transforms.TimeSeries.AnomalySide,Microsoft.ML.Transforms.TimeSeries.ErrorFunction)" />
| BaseArguments |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System.Profile/AppApplicability.cs | {
"start": 310,
"end": 1242
} | partial class ____
{
#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 static global::System.Collections.Generic.IReadOnlyList<global::Windows.System.Profile.UnsupportedAppRequirement> GetUnsupportedAppRequirements(global::System.Collections.Generic.IEnumerable<string> capabilities)
{
throw new global::System.NotImplementedException("The member IReadOnlyList<UnsupportedAppRequirement> AppApplicability.GetUnsupportedAppRequirements(IEnumerable<string> capabilities) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3CUnsupportedAppRequirement%3E%20AppApplicability.GetUnsupportedAppRequirements%28IEnumerable%3Cstring%3E%20capabilities%29");
}
#endif
}
}
| AppApplicability |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests.Benchmarks/LargeColumnBenchmark.cs | {
"start": 273,
"end": 2549
} | public class ____
{
private OrmLiteConnectionFactory dbFactory;
private int id;
private int size = 1000000;
private int iterations = 5;
[ParamsSource(nameof(DatabaseNames))]
public string DbName { get; set; }
public IEnumerable<string> DatabaseNames => ["pgsql", "mssql", "mysql"];
[GlobalSetup]
public void Setup()
{
dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
dbFactory.RegisterConnection("pgsql",
"Server=localhost;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
PostgreSqlDialect.Provider);
dbFactory.RegisterConnection("mssql",
"Server=localhost;Database=test;User Id=sa;Password=p@55wOrd;MultipleActiveResultSets=True;TrustServerCertificate=True;",
SqlServer2012Dialect.Provider);
dbFactory.RegisterConnection("mysql",
"Server=localhost;Database=test;UID=root;Password=p@55wOrd;SslMode=none;AllowLoadLocalInfile=true;Convert Zero Datetime=True;AllowPublicKeyRetrieval=true;",
MySqlDialect.Provider);
var text = new string('x', size);
foreach (var dbName in DatabaseNames)
{
using var db = dbFactory.OpenDbConnection(dbName);
db.DropAndCreateTable<TextContents>();
id = (int) db.Insert(new TextContents { Contents = text }, selectIdentity: true);
}
}
[Benchmark]
public void TextContents_Sync()
{
using var db = dbFactory.OpenDbConnection(DbName);
for (var i = 0; i < iterations; i++)
{
var result = db.Single<TextContents>(x => x.Id == id);
if (result.Contents.Length != size)
Console.WriteLine($"ERROR: {result.Contents.Length} != {size}");
}
}
[Benchmark]
public async Task TextContents_Async()
{
using var db = await dbFactory.OpenDbConnectionAsync(DbName);
for (var i = 0; i < iterations; i++)
{
var result = await db.SingleAsync<TextContents>(x => x.Id == id);
if (result.Contents.Length != size)
Console.WriteLine($"ERROR: {result.Contents.Length} != {size}");
}
}
}
| LargeColumnBenchmark |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Scaffolding/Baselines/Custom_provider_value_comparer/MyEntityEntityType.cs | {
"start": 592,
"end": 7942
} | public partial class ____
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"MyEntity",
typeof(Dictionary<string, object>),
baseEntityType,
sharedClrType: true,
indexerPropertyInfo: RuntimeEntityType.FindIndexerProperty(typeof(Dictionary<string, object>)),
propertyBag: true,
propertyCount: 1,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(int),
propertyInfo: runtimeEntityType.FindIndexerPropertyInfo(),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
providerPropertyType: typeof(int));
id.SetGetter(
int (Dictionary<string, object> instance) => ((((IDictionary<string, object>)instance).ContainsKey("Id") ? instance["Id"] : null) == null ? 0 : ((int)((((IDictionary<string, object>)instance).ContainsKey("Id") ? instance["Id"] : null)))),
bool (Dictionary<string, object> instance) => (((IDictionary<string, object>)instance).ContainsKey("Id") ? instance["Id"] : null) == null);
id.SetSetter(
Dictionary<string, object> (Dictionary<string, object> instance, int value) =>
{
instance["Id"] = ((object)value);
return instance;
});
id.SetMaterializationSetter(
Dictionary<string, object> (Dictionary<string, object> instance, int value) =>
{
instance["Id"] = ((object)value);
return instance;
});
id.SetAccessors(
int (IInternalEntry entry) =>
{
if (entry.FlaggedAsStoreGenerated(0))
{
return entry.ReadStoreGeneratedValue<int>(0);
}
else
{
{
if (entry.FlaggedAsTemporary(0) && (((IDictionary<string, object>)((Dictionary<string, object>)(entry.Entity))).ContainsKey("Id") ? ((Dictionary<string, object>)(entry.Entity))["Id"] : null) == null)
{
return entry.ReadTemporaryValue<int>(0);
}
else
{
var nullableValue = (((IDictionary<string, object>)((Dictionary<string, object>)(entry.Entity))).ContainsKey("Id") ? ((Dictionary<string, object>)(entry.Entity))["Id"] : null);
return (nullableValue == null ? default(int) : ((int)nullableValue));
}
}
}
},
int (IInternalEntry entry) =>
{
var nullableValue = (((IDictionary<string, object>)((Dictionary<string, object>)(entry.Entity))).ContainsKey("Id") ? ((Dictionary<string, object>)(entry.Entity))["Id"] : null);
return (nullableValue == null ? default(int) : ((int)nullableValue));
},
int (IInternalEntry entry) => entry.ReadOriginalValue<int>(id, 0),
int (IInternalEntry entry) => ((InternalEntityEntry)entry).ReadRelationshipSnapshotValue<int>(id, 0));
id.SetPropertyIndexes(
index: 0,
originalValueIndex: 0,
shadowIndex: -1,
relationshipIndex: 0,
storeGenerationIndex: 0);
id.TypeMapping = InMemoryTypeMapping.Default.Clone(
comparer: new ValueComparer<int>(
bool (int v1, int v2) => v1 == v2,
int (int v) => v,
int (int v) => v),
keyComparer: new ValueComparer<int>(
bool (int v1, int v2) => v1 == v2,
int (int v) => v,
int (int v) => v),
providerValueComparer: new ValueComparer<int>(
bool (int v1, int v2) => v1 == v2,
int (int v) => v,
int (int v) => v),
clrType: typeof(int),
jsonValueReaderWriter: JsonInt32ReaderWriter.Instance);
id.SetCurrentValueComparer(new EntryCurrentValueComparer<int>(id));
id.SetProviderValueComparer(new ValueComparer<int>(
bool (int l, int r) => false,
int (int v) => 0,
int (int v) => 1));
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
var id = runtimeEntityType.FindProperty("Id");
var key = runtimeEntityType.FindKey(new[] { id });
key.SetPrincipalKeyValueFactory(KeyValueFactoryFactory.CreateSimpleNonNullableFactory<int>(key));
key.SetIdentityMapFactory(IdentityMapFactoryFactory.CreateFactory<int>(key));
runtimeEntityType.SetOriginalValuesFactory(
ISnapshot (IInternalEntry source) =>
{
var structuralType = ((Dictionary<string, object>)(source.Entity));
return ((ISnapshot)(new Snapshot<int>(((ValueComparer<int>)(((IProperty)id).GetValueComparer())).Snapshot(source.GetCurrentValue<int>(id)))));
});
runtimeEntityType.SetStoreGeneratedValuesFactory(
ISnapshot () => ((ISnapshot)(new Snapshot<int>(((ValueComparer<int>)(((IProperty)id).GetValueComparer())).Snapshot(default(int))))));
runtimeEntityType.SetTemporaryValuesFactory(
ISnapshot (IInternalEntry source) => ((ISnapshot)(new Snapshot<int>(default(int)))));
runtimeEntityType.SetShadowValuesFactory(
ISnapshot (IDictionary<string, object> source) => Snapshot.Empty);
runtimeEntityType.SetEmptyShadowValuesFactory(
ISnapshot () => Snapshot.Empty);
runtimeEntityType.SetRelationshipSnapshotFactory(
ISnapshot (IInternalEntry source) =>
{
var structuralType = ((Dictionary<string, object>)(source.Entity));
return ((ISnapshot)(new Snapshot<int>(((ValueComparer<int>)(((IProperty)id).GetKeyValueComparer())).Snapshot(source.GetCurrentValue<int>(id)))));
});
runtimeEntityType.SetCounts(new PropertyCounts(
propertyCount: 1,
navigationCount: 0,
complexPropertyCount: 0,
complexCollectionCount: 0,
originalValueCount: 1,
shadowCount: 0,
relationshipCount: 1,
storeGeneratedCount: 1));
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
| MyEntityEntityType |
csharp | atata-framework__atata | src/Atata/PopupBoxes/ConfirmBox`1.cs | {
"start": 167,
"end": 718
} | public sealed class ____<TOwner> : PopupBox<ConfirmBox<TOwner>, TOwner>
where TOwner : PageObject<TOwner>
{
internal ConfirmBox(TOwner owner)
: base(owner)
{
}
private protected override string KindName => "confirm box";
/// <summary>
/// Cancels the popup box.
/// </summary>
/// <returns>The owner page object.</returns>
public TOwner Cancel()
{
Owner.Log.ExecuteSection(
new LogSection($"Cancel {KindName}"),
Alert.Dismiss);
return Owner;
}
}
| ConfirmBox |
csharp | SixLabors__ImageSharp | src/ImageSharp/Formats/IImageFormatDetector.cs | {
"start": 242,
"end": 874
} | public interface ____
{
/// <summary>
/// Gets the size of the header for this image type.
/// </summary>
/// <value>The size of the header.</value>
int HeaderSize { get; }
/// <summary>
/// Detect mimetype
/// </summary>
/// <param name="header">The <see cref="T:byte[]"/> containing the file header.</param>
/// <param name="format">The mime type of detected otherwise returns null</param>
/// <returns>returns true when format was detected otherwise false.</returns>
bool TryDetectFormat(ReadOnlySpan<byte> header, [NotNullWhen(true)] out IImageFormat? format);
}
| IImageFormatDetector |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/ExceptionFactory.cs | {
"start": 182,
"end": 22665
} | partial class ____
{
private const string
DataCommandKey = "redis-command",
DataSentStatusKey = "request-sent-status",
DataServerKey = "redis-server",
TimeoutHelpLink = "https://stackexchange.github.io/StackExchange.Redis/Timeouts";
internal static Exception AdminModeNotEnabled(bool includeDetail, RedisCommand command, Message? message, ServerEndPoint? server)
{
string s = GetLabel(includeDetail, command, message);
var ex = new RedisCommandException("This operation is not available unless admin mode is enabled: " + s);
if (includeDetail) AddExceptionDetail(ex, message, server, s);
return ex;
}
internal static Exception CommandDisabled(RedisCommand command) => CommandDisabled(command.ToString());
internal static Exception CommandDisabled(string command)
=> new RedisCommandException("This operation has been disabled in the command-map and cannot be used: " + command);
internal static Exception TooManyArgs(string command, int argCount)
=> new RedisCommandException($"This operation would involve too many arguments ({argCount + 1} vs the redis limit of {PhysicalConnection.REDIS_MAX_ARGS}): {command}");
internal static Exception ConnectionFailure(bool includeDetail, ConnectionFailureType failureType, string message, ServerEndPoint? server)
{
var ex = new RedisConnectionException(failureType, message);
if (includeDetail) AddExceptionDetail(ex, null, server, null);
return ex;
}
internal static Exception DatabaseNotRequired(bool includeDetail, RedisCommand command)
{
string s = command.ToString();
var ex = new RedisCommandException("A target database is not required for " + s);
if (includeDetail) AddExceptionDetail(ex, null, null, s);
return ex;
}
internal static Exception DatabaseOutfRange(bool includeDetail, int targetDatabase, Message message, ServerEndPoint server)
{
var ex = new RedisCommandException("The database does not exist on the server: " + targetDatabase);
if (includeDetail) AddExceptionDetail(ex, message, server, null);
return ex;
}
internal static Exception DatabaseRequired(bool includeDetail, RedisCommand command)
{
string s = command.ToString();
var ex = new RedisCommandException("A target database is required for " + s);
if (includeDetail) AddExceptionDetail(ex, null, null, s);
return ex;
}
internal static Exception PrimaryOnly(bool includeDetail, RedisCommand command, Message? message, ServerEndPoint? server)
{
string s = GetLabel(includeDetail, command, message);
var ex = new RedisCommandException("Command cannot be issued to a replica: " + s);
if (includeDetail) AddExceptionDetail(ex, message, server, s);
return ex;
}
internal static Exception MultiSlot(bool includeDetail, Message message)
{
var ex = new RedisCommandException("Multi-key operations must involve a single slot; keys can use 'hash tags' to help this, i.e. '{/users/12345}/account' and '{/users/12345}/contacts' will always be in the same slot");
if (includeDetail) AddExceptionDetail(ex, message, null, null);
return ex;
}
internal static string GetInnerMostExceptionMessage(Exception? e)
{
if (e == null)
{
return "";
}
else
{
while (e.InnerException != null)
{
e = e.InnerException;
}
return e.Message;
}
}
internal static Exception NoConnectionAvailable(
ConnectionMultiplexer multiplexer,
Message? message,
ServerEndPoint? server,
ReadOnlySpan<ServerEndPoint> serverSnapshot = default,
RedisCommand command = default)
{
string commandLabel = GetLabel(multiplexer.RawConfig.IncludeDetailInExceptions, message?.Command ?? command, message);
if (server != null)
{
// If we already have the serverEndpoint for connection failure use that,
// otherwise it would output state of all the endpoints.
serverSnapshot = new ServerEndPoint[] { server };
}
var innerException = PopulateInnerExceptions(serverSnapshot == default ? multiplexer.GetServerSnapshot() : serverSnapshot);
// Try to get a useful error message for the user.
long attempts = multiplexer._connectAttemptCount, completions = multiplexer._connectCompletedCount;
string initialMessage;
// We only need to customize the connection if we're aborting on connect fail
// The "never" case would have thrown, if this was true
if (!multiplexer.RawConfig.AbortOnConnectFail && attempts <= multiplexer.RawConfig.ConnectRetry && completions == 0)
{
// Initial attempt, attempted use before an async connection completes
initialMessage = $"Connection to Redis never succeeded (attempts: {attempts} - connection likely in-progress), unable to service operation: ";
}
else if (!multiplexer.RawConfig.AbortOnConnectFail && attempts > multiplexer.RawConfig.ConnectRetry && completions == 0)
{
// Attempted use after a full initial retry connect count # of failures
// This can happen in cloud environments often, where user disables abort and has the wrong config
initialMessage = $"Connection to Redis never succeeded (attempts: {attempts} - check your config), unable to service operation: ";
}
else if (message is not null && message.IsPrimaryOnly() && multiplexer.IsConnected)
{
// If we know it's a primary-only command, indicate that in the error message
initialMessage = "No connection (requires writable - not eligible for replica) is active/available to service this operation: ";
}
else
{
// Default if we don't have a more useful error message here based on circumstances
initialMessage = "No connection is active/available to service this operation: ";
}
StringBuilder sb = new StringBuilder(initialMessage);
sb.Append(commandLabel);
string innermostExceptionstring = GetInnerMostExceptionMessage(innerException);
if (!string.IsNullOrEmpty(innermostExceptionstring))
{
sb.Append("; ").Append(innermostExceptionstring);
}
// Add counters and exception data if we have it
List<Tuple<string, string>>? data = null;
if (multiplexer.RawConfig.IncludeDetailInExceptions)
{
data = new List<Tuple<string, string>>();
AddCommonDetail(data, sb, message, multiplexer, server);
}
var ex = new RedisConnectionException(ConnectionFailureType.UnableToResolvePhysicalConnection, sb.ToString(), innerException, message?.Status ?? CommandStatus.Unknown);
if (multiplexer.RawConfig.IncludeDetailInExceptions)
{
CopyDataToException(data, ex);
sb.Append("; ").Append(PerfCounterHelper.GetThreadPoolAndCPUSummary());
AddExceptionDetail(ex, message, server, commandLabel);
}
return ex;
}
internal static Exception? PopulateInnerExceptions(ReadOnlySpan<ServerEndPoint> serverSnapshot)
{
var innerExceptions = new List<Exception>();
if (serverSnapshot.Length > 0 && serverSnapshot[0].Multiplexer.LastException is Exception ex)
{
innerExceptions.Add(ex);
}
for (int i = 0; i < serverSnapshot.Length; i++)
{
if (serverSnapshot[i].LastException is Exception lastException)
{
innerExceptions.Add(lastException);
}
}
if (innerExceptions.Count == 1)
{
return innerExceptions[0];
}
else if (innerExceptions.Count > 1)
{
return new AggregateException(innerExceptions);
}
return null;
}
internal static Exception NotSupported(bool includeDetail, RedisCommand command)
{
string s = GetLabel(includeDetail, command, null);
var ex = new RedisCommandException("Command is not available on your server: " + s);
if (includeDetail) AddExceptionDetail(ex, null, null, s);
return ex;
}
internal static Exception NoCursor(RedisCommand command)
{
string s = GetLabel(false, command, null);
return new RedisCommandException("Command cannot be used with a cursor: " + s);
}
private static void Add(List<Tuple<string, string>> data, StringBuilder sb, string? lk, string? sk, string? v)
{
if (v != null)
{
if (lk != null) data.Add(Tuple.Create(lk, v));
if (sk != null) sb.Append(", ").Append(sk).Append(": ").Append(v);
}
}
internal static Exception Timeout(ConnectionMultiplexer multiplexer, string? baseErrorMessage, Message message, ServerEndPoint? server, WriteResult? result = null, PhysicalBridge? bridge = null)
{
List<Tuple<string, string>> data = new List<Tuple<string, string>> { Tuple.Create("Message", message.CommandAndKey) };
var sb = new StringBuilder();
// We timeout writing messages in quite different ways sync/async - so centralize messaging here.
if (string.IsNullOrEmpty(baseErrorMessage) && result == WriteResult.TimeoutBeforeWrite)
{
baseErrorMessage = message.IsBacklogged
? "The message timed out in the backlog attempting to send because no connection became available"
: "The timeout was reached before the message could be written to the output buffer, and it was not sent";
}
var lastConnectionException = bridge?.LastException as RedisConnectionException;
var logConnectionException = message.IsBacklogged && lastConnectionException is not null;
if (!string.IsNullOrEmpty(baseErrorMessage))
{
sb.Append(baseErrorMessage);
// If we're in the situation where we've never connected
if (logConnectionException && lastConnectionException is not null)
{
sb.Append(" (").Append(Format.ToString(multiplexer.TimeoutMilliseconds)).Append("ms)");
sb.Append(" - Last Connection Exception: ").Append(lastConnectionException.Message);
}
if (message != null)
{
sb.Append(", command=").Append(message.CommandString); // no key here, note
}
}
else
{
sb.Append("Timeout performing ").Append(message.CommandString).Append(" (").Append(Format.ToString(multiplexer.TimeoutMilliseconds)).Append("ms)");
}
// Add timeout data, if we have it
if (result == WriteResult.TimeoutBeforeWrite)
{
Add(data, sb, "Timeout", "timeout", Format.ToString(multiplexer.TimeoutMilliseconds));
try
{
if (message != null && message.TryGetPhysicalState(out var ws, out var rs, out var sentDelta, out var receivedDelta))
{
Add(data, sb, "Write-State", null, ws.ToString());
Add(data, sb, "Read-State", null, rs.ToString());
// these might not always be available
if (sentDelta >= 0)
{
Add(data, sb, "OutboundDeltaKB", "outbound", $"{sentDelta >> 10}KiB");
}
if (receivedDelta >= 0)
{
Add(data, sb, "InboundDeltaKB", "inbound", $"{receivedDelta >> 10}KiB");
}
}
}
catch { }
}
AddCommonDetail(data, sb, message, multiplexer, server);
sb.Append(" (Please take a look at this article for some common client-side issues that can cause timeouts: ")
.Append(TimeoutHelpLink)
.Append(')');
// If we're from a backlog timeout scenario, we log a more intuitive connection exception for the timeout...because the timeout was a symptom
// and we have a more direct cause: we had no connection to send it on.
Exception ex = logConnectionException && lastConnectionException is not null
? new RedisConnectionException(lastConnectionException.FailureType, sb.ToString(), lastConnectionException, message?.Status ?? CommandStatus.Unknown)
{
HelpLink = TimeoutHelpLink,
}
: new RedisTimeoutException(sb.ToString(), message?.Status ?? CommandStatus.Unknown)
{
HelpLink = TimeoutHelpLink,
};
CopyDataToException(data, ex);
if (multiplexer.RawConfig.IncludeDetailInExceptions) AddExceptionDetail(ex, message, server, null);
return ex;
}
private static void CopyDataToException(List<Tuple<string, string>>? data, Exception ex)
{
if (data != null)
{
var exData = ex.Data;
foreach (var kv in data)
{
exData["Redis-" + kv.Item1] = kv.Item2;
}
}
}
private static void AddCommonDetail(
List<Tuple<string, string>> data,
StringBuilder sb,
Message? message,
ConnectionMultiplexer multiplexer,
ServerEndPoint? server)
{
if (message != null)
{
message.TryGetHeadMessages(out var now, out var next);
if (now != null) Add(data, sb, "Message-Current", "active", multiplexer.RawConfig.IncludeDetailInExceptions ? now.CommandAndKey : now.CommandString);
if (next != null) Add(data, sb, "Message-Next", "next", multiplexer.RawConfig.IncludeDetailInExceptions ? next.CommandAndKey : next.CommandString);
}
// Add server data, if we have it
if (server != null && message != null)
{
var bs = server.GetBridgeStatus(message.IsForSubscriptionBridge ? ConnectionType.Subscription : ConnectionType.Interactive);
switch (bs.Connection.ReadStatus)
{
case PhysicalConnection.ReadStatus.CompletePendingMessageAsync:
case PhysicalConnection.ReadStatus.CompletePendingMessageSync:
sb.Append(" ** possible thread-theft indicated; see https://stackexchange.github.io/StackExchange.Redis/ThreadTheft ** ");
break;
}
Add(data, sb, "OpsSinceLastHeartbeat", "inst", bs.MessagesSinceLastHeartbeat.ToString());
Add(data, sb, "Queue-Awaiting-Write", "qu", bs.BacklogMessagesPending.ToString());
Add(data, sb, "Queue-Awaiting-Response", "qs", bs.Connection.MessagesSentAwaitingResponse.ToString());
Add(data, sb, "Active-Writer", "aw", bs.IsWriterActive.ToString());
Add(data, sb, "Backlog-Writer", "bw", bs.BacklogStatus.ToString());
if (bs.Connection.ReadStatus != PhysicalConnection.ReadStatus.NA) Add(data, sb, "Read-State", "rs", bs.Connection.ReadStatus.ToString());
if (bs.Connection.WriteStatus != PhysicalConnection.WriteStatus.NA) Add(data, sb, "Write-State", "ws", bs.Connection.WriteStatus.ToString());
if (bs.Connection.BytesAvailableOnSocket >= 0) Add(data, sb, "Inbound-Bytes", "in", bs.Connection.BytesAvailableOnSocket.ToString());
if (bs.Connection.BytesInReadPipe >= 0) Add(data, sb, "Inbound-Pipe-Bytes", "in-pipe", bs.Connection.BytesInReadPipe.ToString());
if (bs.Connection.BytesInWritePipe >= 0) Add(data, sb, "Outbound-Pipe-Bytes", "out-pipe", bs.Connection.BytesInWritePipe.ToString());
Add(data, sb, "Last-Result-Bytes", "last-in", bs.Connection.BytesLastResult.ToString());
Add(data, sb, "Inbound-Buffer-Bytes", "cur-in", bs.Connection.BytesInBuffer.ToString());
Add(data, sb, "Sync-Ops", "sync-ops", multiplexer.syncOps.ToString());
Add(data, sb, "Async-Ops", "async-ops", multiplexer.asyncOps.ToString());
if (multiplexer.StormLogThreshold >= 0 && bs.Connection.MessagesSentAwaitingResponse >= multiplexer.StormLogThreshold && Interlocked.CompareExchange(ref multiplexer.haveStormLog, 1, 0) == 0)
{
var log = server.GetStormLog(message);
if (string.IsNullOrWhiteSpace(log)) Interlocked.Exchange(ref multiplexer.haveStormLog, 0);
else Interlocked.Exchange(ref multiplexer.stormLogSnapshot, log);
}
Add(data, sb, "Server-Endpoint", "serverEndpoint", (server.EndPoint.ToString() ?? "Unknown").Replace("Unspecified/", ""));
Add(data, sb, "Server-Connected-Seconds", "conn-sec", bs.ConnectedAt is DateTime dt ? (DateTime.UtcNow - dt).TotalSeconds.ToString("0.##") : "n/a");
Add(data, sb, "Abort-On-Connect", "aoc", multiplexer.RawConfig.AbortOnConnectFail ? "1" : "0");
}
Add(data, sb, "Multiplexer-Connects", "mc", $"{multiplexer._connectAttemptCount}/{multiplexer._connectCompletedCount}/{multiplexer._connectionCloseCount}");
Add(data, sb, "Manager", "mgr", multiplexer.SocketManager?.GetState());
Add(data, sb, "Client-Name", "clientName", multiplexer.ClientName);
if (message != null)
{
var hashSlot = message.GetHashSlot(multiplexer.ServerSelectionStrategy);
// only add keyslot if its a valid cluster key slot
if (hashSlot != ServerSelectionStrategy.NoSlot)
{
Add(data, sb, "Key-HashSlot", "PerfCounterHelperkeyHashSlot", message.GetHashSlot(multiplexer.ServerSelectionStrategy).ToString());
}
}
int busyWorkerCount = PerfCounterHelper.GetThreadPoolStats(out string iocp, out string worker, out string? workItems);
Add(data, sb, "ThreadPool-IO-Completion", "IOCP", iocp);
Add(data, sb, "ThreadPool-Workers", "WORKER", worker);
if (workItems != null)
{
Add(data, sb, "ThreadPool-Items", "POOL", workItems);
}
data.Add(Tuple.Create("Busy-Workers", busyWorkerCount.ToString()));
Add(data, sb, "Version", "v", Utils.GetLibVersion());
}
private static void AddExceptionDetail(Exception? exception, Message? message, ServerEndPoint? server, string? label)
{
if (exception != null)
{
if (message != null)
{
exception.Data.Add(DataCommandKey, message.CommandAndKey);
exception.Data.Add(DataSentStatusKey, message.Status);
}
else if (label != null)
{
exception.Data.Add(DataCommandKey, label);
}
if (server != null) exception.Data.Add(DataServerKey, Format.ToString(server.EndPoint));
}
}
private static string GetLabel(bool includeDetail, RedisCommand command, Message? message)
{
return message == null ? command.ToString() : (includeDetail ? message.CommandAndKey : message.CommandString);
}
internal static Exception UnableToConnect(ConnectionMultiplexer muxer, string? failureMessage = null, string? connectionName = null)
{
var sb = new StringBuilder("It was not possible to connect to the redis server(s)");
if (connectionName is not null)
{
sb.Append(' ').Append(connectionName);
}
sb.Append('.');
Exception? inner = null;
var failureType = ConnectionFailureType.UnableToConnect;
if (muxer is not null)
{
if (muxer.AuthException is Exception aex)
{
failureType = ConnectionFailureType.AuthenticationFailure;
sb.Append(" There was an authentication failure; check that passwords (or client certificates) are configured correctly: (").Append(aex.GetType().Name).Append(") ").Append(aex.Message);
inner = aex;
if (aex is AuthenticationException && aex.InnerException is Exception iaex)
{
sb.Append(" (Inner - ").Append(iaex.GetType().Name).Append(") ").Append(iaex.Message);
}
}
else if (muxer.RawConfig.AbortOnConnectFail)
{
sb.Append(" Error connecting right now. To allow this multiplexer to continue retrying until it's able to connect, use abortConnect=false in your connection string or AbortOnConnectFail=false; in your code.");
}
}
if (!failureMessage.IsNullOrWhiteSpace())
{
sb.Append(' ').Append(failureMessage.Trim());
}
return new RedisConnectionException(failureType, sb.ToString(), inner);
}
}
}
| ExceptionFactory |
csharp | dotnet__aspnetcore | src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.Recursion.cs | {
"start": 231,
"end": 835
} | public partial class ____ : ValidationsGeneratorTestBase
{
[Fact]
public async Task CanValidateRecursiveTypes()
{
var source = """
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder();
builder.Services.AddValidation(options =>
{
options.MaxDepth = 8;
});
var app = builder.Build();
app.MapPost("/recursive-type", (RecursiveType model) => Results.Ok());
app.Run();
| ValidationsGeneratorTests |
csharp | dotnet__aspnetcore | src/Http/Http.Extensions/test/MetadataTest.cs | {
"start": 213,
"end": 1104
} | public class ____
{
[Fact]
public void EndpointDescriptionAttribute_ToString()
{
// Arrange
var metadata = new EndpointDescriptionAttribute("A description");
// Act
var value = metadata.ToString();
// Assert
Assert.Equal("Description: A description", value);
}
[Fact]
public void EndpointSummaryAttribute_ToString()
{
// Arrange
var metadata = new EndpointSummaryAttribute("A summary");
// Act
var value = metadata.ToString();
// Assert
Assert.Equal("Summary: A summary", value);
}
[Fact]
public void HostAttribute_ToString()
{
// Arrange
var metadata = new TagsAttribute("Tag1", "Tag2");
// Act
var value = metadata.ToString();
// Assert
Assert.Equal("Tags: Tag1,Tag2", value);
}
}
| MetadataTest |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Introspection/ISchemaComparer.cs | {
"start": 1327,
"end": 1808
} | enum ____ belong.</param>
IComparer<EnumValueDefinition>? EnumValueComparer(EnumerationGraphType parent);
/// <summary>
/// Returns a comparer for GraphQL directives.
/// If this returns <see langword="null"/> then the original directive ordering is preserved.
/// </summary>
IComparer<Directive>? DirectiveComparer { get; }
}
/// <summary>
/// Default schema comparer. By default all elements are returned as is, no sorting is applied.
/// </summary>
| values |
csharp | dotnet__aspire | src/Tools/ConfigurationSchemaGenerator/RuntimeSource/Configuration.Binder/ConfigurationBindingGenerator.Parser.cs | {
"start": 510,
"end": 608
} | partial class ____ : IIncrementalGenerator
{
internal sealed | ConfigurationBindingGenerator |
csharp | dotnet__aspnetcore | src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/ExampleJsInterop.cs | {
"start": 274,
"end": 374
} | class ____ be registered as scoped DI service and then injected into Blazor
// components for use.
| can |
csharp | atata-framework__atata | src/Atata/Components/INavigable`2.cs | {
"start": 19,
"end": 177
} | public interface ____<TNavigateTo, TOwner> : IControl<TOwner>
where TNavigateTo : PageObject<TNavigateTo>
where TOwner : PageObject<TOwner>
{
}
| INavigable |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System/DispatcherQueue.cs | {
"start": 249,
"end": 3514
} | public partial class ____
{
// Skipping already declared property HasThreadAccess
// Skipping already declared method Windows.System.DispatcherQueue.CreateTimer()
// Skipping already declared method Windows.System.DispatcherQueue.TryEnqueue(Windows.System.DispatcherQueueHandler)
// Skipping already declared method Windows.System.DispatcherQueue.TryEnqueue(Windows.System.DispatcherQueuePriority, Windows.System.DispatcherQueueHandler)
// Forced skipping of method Windows.System.DispatcherQueue.ShutdownStarting.add
// Forced skipping of method Windows.System.DispatcherQueue.ShutdownStarting.remove
// Forced skipping of method Windows.System.DispatcherQueue.ShutdownCompleted.add
// Forced skipping of method Windows.System.DispatcherQueue.ShutdownCompleted.remove
// Forced skipping of method Windows.System.DispatcherQueue.HasThreadAccess.get
// Skipping already declared method Windows.System.DispatcherQueue.GetForCurrentThread()
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.System.DispatcherQueue, object> ShutdownCompleted
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.DispatcherQueue", "event TypedEventHandler<DispatcherQueue, object> DispatcherQueue.ShutdownCompleted");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.DispatcherQueue", "event TypedEventHandler<DispatcherQueue, object> DispatcherQueue.ShutdownCompleted");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.System.DispatcherQueue, global::Windows.System.DispatcherQueueShutdownStartingEventArgs> ShutdownStarting
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.DispatcherQueue", "event TypedEventHandler<DispatcherQueue, DispatcherQueueShutdownStartingEventArgs> DispatcherQueue.ShutdownStarting");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.DispatcherQueue", "event TypedEventHandler<DispatcherQueue, DispatcherQueueShutdownStartingEventArgs> DispatcherQueue.ShutdownStarting");
}
}
#endif
}
}
| DispatcherQueue |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/DataTemplate.cs | {
"start": 347,
"end": 1516
} | public partial class ____ : FrameworkTemplate
{
public DataTemplate() : base(null) { }
public DataTemplate(Func<View?>? factory)
: base(factory)
{
}
/// <summary>
/// Build a DataTemplate with an optional <paramref name="owner"/> to be provided during the call of <paramref name="factory"/>
/// </summary>
/// <param name="owner">The owner of the DataTemplate</param>
/// <param name="factory">The factory to be called to build the template content</param>
public DataTemplate(object? owner, NewFrameworkTemplateBuilder? factory)
: base(owner, factory)
{
}
#if ENABLE_LEGACY_TEMPLATED_PARENT_SUPPORT
public DataTemplate(object? owner, FrameworkTemplateBuilder? factory)
: base(owner, factory)
{
}
#endif
public View? LoadContent() => ((IFrameworkTemplateInternal)this).LoadContent(templatedParent: null);
[EditorBrowsable(EditorBrowsableState.Never)]
public View? LoadContent(DependencyObject templatedParent) => ((IFrameworkTemplateInternal)this).LoadContent(templatedParent);
internal View? LoadContentCached(DependencyObject? templatedParent = null) => base.LoadContentCachedCore(templatedParent);
}
}
| DataTemplate |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring/Windows/WindowsContainerSnapshotProvider.cs | {
"start": 526,
"end": 11436
} | internal sealed class ____ : ISnapshotProvider
{
private const double One = 1.0d;
private const double Hundred = 100.0d;
private const double TicksPerSecondDouble = TimeSpan.TicksPerSecond;
/// <summary>
/// This represents a factory method for creating the JobHandle.
/// </summary>
private readonly Func<IJobHandle> _createJobHandleObject;
private readonly object _cpuLocker = new();
private readonly object _memoryLocker = new();
private readonly object _processMemoryLocker = new();
private readonly TimeProvider _timeProvider;
private readonly IProcessInfo _processInfo;
private readonly ILogger<WindowsContainerSnapshotProvider> _logger;
private readonly TimeSpan _cpuRefreshInterval;
private readonly TimeSpan _memoryRefreshInterval;
private readonly double _metricValueMultiplier;
private double _memoryLimit;
private double _cpuLimit;
#pragma warning disable S1450 // Private fields only used as local variables in methods should become local variables. Those will be used once we bring relevant meters.
private double _memoryRequest;
private double _cpuRequest;
#pragma warning restore S1450 // Private fields only used as local variables in methods should become local variables
private long _oldCpuUsageTicks;
private long _oldCpuTimeTicks;
private DateTimeOffset _refreshAfterCpu;
private DateTimeOffset _refreshAfterMemory;
private DateTimeOffset _refreshAfterProcessMemory;
private long _cachedUsageTickDelta;
private long _cachedTimeTickDelta;
private double _processMemoryPercentage;
private ulong _memoryUsage;
public SystemResources Resources { get; }
/// <summary>
/// Initializes a new instance of the <see cref="WindowsContainerSnapshotProvider"/> class.
/// </summary>
public WindowsContainerSnapshotProvider(
ILogger<WindowsContainerSnapshotProvider>? logger,
IMeterFactory meterFactory,
IOptions<ResourceMonitoringOptions> options,
ResourceQuotaProvider resourceQuotaProvider)
: this(new ProcessInfo(), logger, meterFactory,
static () => new JobHandleWrapper(), TimeProvider.System, options.Value, resourceQuotaProvider)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WindowsContainerSnapshotProvider"/> class.
/// </summary>
/// <remarks>This constructor enables the mocking of <see cref="WindowsContainerSnapshotProvider"/> dependencies for the purpose of Unit Testing only.</remarks>
internal WindowsContainerSnapshotProvider(
IProcessInfo processInfo,
ILogger<WindowsContainerSnapshotProvider>? logger,
IMeterFactory meterFactory,
Func<IJobHandle> createJobHandleObject,
TimeProvider timeProvider,
ResourceMonitoringOptions options,
ResourceQuotaProvider resourceQuotaProvider)
{
_logger = logger ?? NullLogger<WindowsContainerSnapshotProvider>.Instance;
_logger.RunningInsideJobObject();
_metricValueMultiplier = options.UseZeroToOneRangeForMetrics ? One : Hundred;
_createJobHandleObject = createJobHandleObject;
_processInfo = processInfo;
_timeProvider = timeProvider;
using IJobHandle jobHandle = _createJobHandleObject();
var quota = resourceQuotaProvider.GetResourceQuota();
_cpuLimit = quota.MaxCpuInCores;
_memoryLimit = quota.MaxMemoryInBytes;
_cpuRequest = quota.BaselineCpuInCores;
_memoryRequest = quota.BaselineMemoryInBytes;
Resources = new SystemResources(_cpuRequest, _cpuLimit, quota.BaselineMemoryInBytes, quota.MaxMemoryInBytes);
_logger.SystemResourcesInfo(_cpuLimit, _cpuRequest, quota.MaxMemoryInBytes, quota.BaselineMemoryInBytes);
var basicAccountingInfo = jobHandle.GetBasicAccountingInfo();
_oldCpuUsageTicks = basicAccountingInfo.TotalKernelTime + basicAccountingInfo.TotalUserTime;
_oldCpuTimeTicks = _timeProvider.GetUtcNow().Ticks;
_cpuRefreshInterval = options.CpuConsumptionRefreshInterval;
_memoryRefreshInterval = options.MemoryConsumptionRefreshInterval;
_refreshAfterCpu = _timeProvider.GetUtcNow();
_refreshAfterMemory = _timeProvider.GetUtcNow();
_refreshAfterProcessMemory = _timeProvider.GetUtcNow();
#pragma warning disable CA2000 // Dispose objects before losing scope
// We don't dispose the meter because IMeterFactory handles that
// An issue on analyzer side: https://github.com/dotnet/roslyn-analyzers/issues/6912
// Related documentation: https://github.com/dotnet/docs/pull/37170
Meter meter = meterFactory.Create(ResourceUtilizationInstruments.MeterName);
#pragma warning restore CA2000 // Dispose objects before losing scope
_ = meter.CreateObservableCounter(
name: ResourceUtilizationInstruments.ContainerCpuTime,
observeValues: GetCpuTime,
unit: "s",
description: "CPU time used by the container.");
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ContainerCpuLimitUtilization,
observeValue: () => CpuPercentage(_cpuLimit));
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ContainerMemoryLimitUtilization,
observeValue: () => Math.Min(_metricValueMultiplier, MemoryUsage() / _memoryLimit * _metricValueMultiplier));
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ContainerCpuRequestUtilization,
observeValue: () => CpuPercentage(_cpuRequest));
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ContainerMemoryRequestUtilization,
observeValue: () => Math.Min(_metricValueMultiplier, MemoryUsage() / _memoryRequest * _metricValueMultiplier));
_ = meter.CreateObservableUpDownCounter(
name: ResourceUtilizationInstruments.ContainerMemoryUsage,
observeValue: () => (long)MemoryUsage(),
unit: "By",
description: "Memory usage of the container.");
// Process based metrics:
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ProcessCpuUtilization,
observeValue: () => CpuPercentage(_cpuLimit));
_ = meter.CreateObservableGauge(
name: ResourceUtilizationInstruments.ProcessMemoryUtilization,
observeValue: ProcessMemoryPercentage);
}
public Snapshot GetSnapshot()
{
// Gather the information
// Cpu kernel and user ticks
using var jobHandle = _createJobHandleObject();
var basicAccountingInfo = jobHandle.GetBasicAccountingInfo();
return new Snapshot(
TimeSpan.FromTicks(_timeProvider.GetUtcNow().Ticks),
TimeSpan.FromTicks(basicAccountingInfo.TotalKernelTime),
TimeSpan.FromTicks(basicAccountingInfo.TotalUserTime),
_processInfo.GetCurrentProcessMemoryUsage());
}
private double ProcessMemoryPercentage()
{
DateTimeOffset now = _timeProvider.GetUtcNow();
lock (_processMemoryLocker)
{
if (now < _refreshAfterProcessMemory)
{
return _processMemoryPercentage;
}
}
ulong processMemoryUsage = _processInfo.GetCurrentProcessMemoryUsage();
lock (_processMemoryLocker)
{
if (now >= _refreshAfterProcessMemory)
{
_processMemoryPercentage = Math.Min(_metricValueMultiplier, processMemoryUsage / _memoryLimit * _metricValueMultiplier);
_refreshAfterProcessMemory = now.Add(_memoryRefreshInterval);
_logger.ProcessMemoryPercentageData(processMemoryUsage, _memoryLimit, _processMemoryPercentage);
}
return _processMemoryPercentage;
}
}
private ulong MemoryUsage()
{
DateTimeOffset now = _timeProvider.GetUtcNow();
lock (_memoryLocker)
{
if (now < _refreshAfterMemory)
{
return _memoryUsage;
}
}
ulong memoryUsage = _processInfo.GetMemoryUsage();
lock (_memoryLocker)
{
if (now >= _refreshAfterMemory)
{
_memoryUsage = memoryUsage;
_refreshAfterMemory = now.Add(_memoryRefreshInterval);
_logger.ContainerMemoryUsageData(_memoryUsage, _memoryLimit, _memoryRequest);
}
return _memoryUsage;
}
}
private IEnumerable<Measurement<double>> GetCpuTime()
{
using IJobHandle jobHandle = _createJobHandleObject();
var basicAccountingInfo = jobHandle.GetBasicAccountingInfo();
yield return new Measurement<double>(basicAccountingInfo.TotalUserTime / TicksPerSecondDouble,
[new KeyValuePair<string, object?>("cpu.mode", "user")]);
yield return new Measurement<double>(basicAccountingInfo.TotalKernelTime / TicksPerSecondDouble,
[new KeyValuePair<string, object?>("cpu.mode", "system")]);
}
private double CpuPercentage(double denominator)
{
var now = _timeProvider.GetUtcNow();
lock (_cpuLocker)
{
if (now >= _refreshAfterCpu)
{
using var jobHandle = _createJobHandleObject();
var basicAccountingInfo = jobHandle.GetBasicAccountingInfo();
var currentCpuTicks = basicAccountingInfo.TotalKernelTime + basicAccountingInfo.TotalUserTime;
var usageTickDelta = currentCpuTicks - _oldCpuUsageTicks;
var timeTickDelta = now.Ticks - _oldCpuTimeTicks;
if (usageTickDelta > 0 && timeTickDelta > 0)
{
_cachedUsageTickDelta = usageTickDelta;
_cachedTimeTickDelta = timeTickDelta;
_logger.CpuContainerUsageData(
basicAccountingInfo.TotalKernelTime, basicAccountingInfo.TotalUserTime, _oldCpuUsageTicks, timeTickDelta, denominator, double.NaN);
_oldCpuUsageTicks = currentCpuTicks;
_oldCpuTimeTicks = now.Ticks;
_refreshAfterCpu = now.Add(_cpuRefreshInterval);
}
}
if (_cachedUsageTickDelta > 0 && _cachedTimeTickDelta > 0)
{
var timeTickDeltaWithDenominator = _cachedTimeTickDelta * denominator;
// Don't change calculation order, otherwise precision is lost:
return Math.Min(_metricValueMultiplier, _cachedUsageTickDelta / timeTickDeltaWithDenominator * _metricValueMultiplier);
}
return double.NaN;
}
}
}
| WindowsContainerSnapshotProvider |
csharp | grandnode__grandnode2 | src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs | {
"start": 74,
"end": 3549
} | public static class ____
{
/// <summary>
/// Round price or order total for the currency
/// </summary>
/// <param name="value">Value to round</param>
/// <param name="currency">Currency</param>
/// <returns>Rounded value</returns>
public static double RoundPrice(double value, Currency currency)
{
return currency != null
? value.Round(currency.NumberDecimal, currency.RoundingTypeId, currency.MidpointRoundId)
: value;
}
/// <summary>
/// Round
/// </summary>
/// <param name="value">Value to round</param>
/// <param name="doubles">Doubles</param>
/// <param name="roundingType">The rounding type</param>
/// <param name="midpointRounding">Mid point rounding</param>
/// <returns>Rounded value</returns>
private static double Round(this double value, int doubles, RoundingType roundingType,
MidpointRounding midpointRounding)
{
//default round (Rounding001)
var rez = Math.Round(value, doubles, midpointRounding);
var fractionPart = (rez - Math.Truncate(rez)) * 10;
//cash rounding not needed
if (fractionPart == 0)
return rez;
//Cash rounding (details: https://en.wikipedia.org/wiki/Cash_rounding)
switch (roundingType)
{
//rounding with 0.05 or 5 intervals
case RoundingType.Rounding005Up:
case RoundingType.Rounding005Down:
fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10;
if (fractionPart is 5 or 0)
break;
if (roundingType == RoundingType.Rounding005Down)
fractionPart = fractionPart > 5 ? 5 - fractionPart : fractionPart * -1;
else
fractionPart = fractionPart > 5 ? 10 - fractionPart : 5 - fractionPart;
rez += fractionPart / 100;
break;
//rounding with 0.10 intervals
case RoundingType.Rounding01Up:
case RoundingType.Rounding01Down:
fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10;
if (fractionPart == 0)
break;
if (roundingType == RoundingType.Rounding01Down && fractionPart == 5)
fractionPart = -5;
else
fractionPart = fractionPart < 5 ? fractionPart * -1 : 10 - fractionPart;
rez += fractionPart / 100;
break;
//rounding with 0.50 intervals
case RoundingType.Rounding05:
fractionPart *= 10;
fractionPart = fractionPart < 25 ? fractionPart * -1 :
fractionPart < 50 || fractionPart < 75 ? 50 - fractionPart : 100 - fractionPart;
rez += fractionPart / 100;
break;
//rounding with 1.00 intervals
case RoundingType.Rounding1:
case RoundingType.Rounding1Up:
fractionPart *= 10;
if (roundingType == RoundingType.Rounding1Up && fractionPart > 0)
rez = Math.Truncate(rez) + 1;
else
rez = fractionPart < 50 ? Math.Truncate(rez) : Math.Truncate(rez) + 1;
break;
case RoundingType.Rounding001:
default:
break;
}
return rez;
}
} | RoundingHelper |
csharp | dotnet__orleans | test/Extensions/TesterAzureUtils/CollectionFixtures.cs | {
"start": 404,
"end": 786
} | public class ____ : ICollectionFixture<DefaultClusterFixture> { }
/// <summary>
/// Defines a test collection for tests that require shared test environment configuration.
/// Provides Azure Storage and related services specific test environment setup.
/// </summary>
[CollectionDefinition(TestEnvironmentFixture.DefaultCollection)]
| DefaultClusterTestCollection |
csharp | dotnet__orleans | src/Orleans.Serialization/ISerializableSerializer/ExceptionCodec.cs | {
"start": 18157,
"end": 20139
} | internal sealed class ____ : GeneralizedReferenceTypeSurrogateCodec<AggregateException, AggregateExceptionSurrogate>
{
private readonly ExceptionCodec _baseCodec;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateExceptionCodec"/> class.
/// </summary>
/// <param name="baseCodec">The base codec.</param>
/// <param name="surrogateSerializer">The surrogate serializer.</param>
public AggregateExceptionCodec(ExceptionCodec baseCodec, IValueSerializer<AggregateExceptionSurrogate> surrogateSerializer) : base(surrogateSerializer)
{
_baseCodec = baseCodec;
}
/// <inheritdoc/>
public override AggregateException ConvertFromSurrogate(ref AggregateExceptionSurrogate surrogate)
{
var result = new AggregateException(surrogate.InnerExceptions);
var innerException = surrogate.InnerExceptions is { Count: > 0 } innerExceptions ? innerExceptions[0] : null;
_baseCodec.SetBaseProperties(result, surrogate.Message, surrogate.StackTrace, innerException, surrogate.HResult, surrogate.Data);
return result;
}
/// <inheritdoc/>
public override void ConvertToSurrogate(AggregateException value, ref AggregateExceptionSurrogate surrogate)
{
var info = _baseCodec.GetObjectData(value);
surrogate.Message = info.GetString("Message");
surrogate.StackTrace = value.StackTrace;
surrogate.HResult = value.HResult;
var data = info.GetValue("Data", typeof(IDictionary));
if (data is { })
{
surrogate.Data = _baseCodec.GetDataProperty(value);
}
surrogate.InnerExceptions = value.InnerExceptions;
}
}
/// <summary>
/// Surrogate type for <see cref="AggregateExceptionCodec"/>.
/// </summary>
[GenerateSerializer]
| AggregateExceptionCodec |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs | {
"start": 639,
"end": 6403
} | partial class ____ : IActionResultExecutor<JsonResult>
{
private static readonly string DefaultContentType = new MediaTypeHeaderValue("application/json")
{
Encoding = Encoding.UTF8
}.ToString();
private readonly IHttpResponseStreamWriterFactory _writerFactory;
private readonly ILogger _logger;
private readonly MvcOptions _mvcOptions;
private readonly MvcNewtonsoftJsonOptions _jsonOptions;
private readonly IArrayPool<char> _charPool;
private readonly AsyncEnumerableReader _asyncEnumerableReaderFactory;
/// <summary>
/// Creates a new <see cref="NewtonsoftJsonResultExecutor"/>.
/// </summary>
/// <param name="writerFactory">The <see cref="IHttpResponseStreamWriterFactory"/>.</param>
/// <param name="logger">The <see cref="ILogger{NewtonsoftJsonResultExecutor}"/>.</param>
/// <param name="mvcOptions">Accessor to <see cref="MvcOptions"/>.</param>
/// <param name="jsonOptions">Accessor to <see cref="MvcNewtonsoftJsonOptions"/>.</param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/> for creating <see cref="T:char[]"/> buffers.</param>
public NewtonsoftJsonResultExecutor(
IHttpResponseStreamWriterFactory writerFactory,
ILogger<NewtonsoftJsonResultExecutor> logger,
IOptions<MvcOptions> mvcOptions,
IOptions<MvcNewtonsoftJsonOptions> jsonOptions,
ArrayPool<char> charPool)
{
ArgumentNullException.ThrowIfNull(writerFactory);
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(jsonOptions);
ArgumentNullException.ThrowIfNull(charPool);
_writerFactory = writerFactory;
_logger = logger;
_mvcOptions = mvcOptions?.Value ?? throw new ArgumentNullException(nameof(mvcOptions));
_jsonOptions = jsonOptions.Value;
_charPool = new JsonArrayPool<char>(charPool);
_asyncEnumerableReaderFactory = new AsyncEnumerableReader(_mvcOptions);
}
/// <summary>
/// Executes the <see cref="JsonResult"/> and writes the response.
/// </summary>
/// <param name="context">The <see cref="ActionContext"/>.</param>
/// <param name="result">The <see cref="JsonResult"/>.</param>
/// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns>
public async Task ExecuteAsync(ActionContext context, JsonResult result)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(result);
var jsonSerializerSettings = GetSerializerSettings(result);
var response = context.HttpContext.Response;
ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
result.ContentType,
response.ContentType,
(DefaultContentType, Encoding.UTF8),
MediaType.GetEncoding,
out var resolvedContentType,
out var resolvedContentTypeEncoding);
response.ContentType = resolvedContentType;
if (result.StatusCode != null)
{
response.StatusCode = result.StatusCode.Value;
}
Log.JsonResultExecuting(_logger, result.Value);
var responseStream = response.Body;
FileBufferingWriteStream? fileBufferingWriteStream = null;
if (!_mvcOptions.SuppressOutputFormatterBuffering)
{
fileBufferingWriteStream = new FileBufferingWriteStream();
responseStream = fileBufferingWriteStream;
}
try
{
var value = result.Value;
if (value != null && _asyncEnumerableReaderFactory.TryGetReader(value.GetType(), out var reader))
{
Log.BufferingAsyncEnumerable(_logger, value);
try
{
value = await reader(value, context.HttpContext.RequestAborted);
}
catch (OperationCanceledException) when (context.HttpContext.RequestAborted.IsCancellationRequested) { }
if (context.HttpContext.RequestAborted.IsCancellationRequested)
{
return;
}
}
await using (var writer = _writerFactory.CreateWriter(responseStream, resolvedContentTypeEncoding))
{
using var jsonWriter = new JsonTextWriter(writer);
jsonWriter.ArrayPool = _charPool;
jsonWriter.CloseOutput = false;
jsonWriter.AutoCompleteOnClose = false;
var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
jsonSerializer.Serialize(jsonWriter, value);
}
if (fileBufferingWriteStream != null)
{
await fileBufferingWriteStream.DrainBufferAsync(response.Body);
}
}
finally
{
if (fileBufferingWriteStream != null)
{
await fileBufferingWriteStream.DisposeAsync();
}
}
}
private JsonSerializerSettings GetSerializerSettings(JsonResult result)
{
var serializerSettings = result.SerializerSettings;
if (serializerSettings == null)
{
return _jsonOptions.SerializerSettings;
}
else
{
if (!(serializerSettings is JsonSerializerSettings settingsFromResult))
{
throw new InvalidOperationException(Resources.FormatProperty_MustBeInstanceOfType(
nameof(JsonResult),
nameof(JsonResult.SerializerSettings),
typeof(JsonSerializerSettings)));
}
return settingsFromResult;
}
}
private static | NewtonsoftJsonResultExecutor |
csharp | AutoMapper__AutoMapper | src/UnitTests/MemberResolution.cs | {
"start": 1506,
"end": 1619
} | public class ____ : AutoMapperSpecBase
{
private DtoObject[] _result;
| When_mapping_derived_classes_in_arrays |
csharp | bitwarden__server | test/Core.Test/AdminConsole/Entities/OrganizationTests.cs | {
"start": 3150,
"end": 3603
} | enum ____ we will validate that we can read
// from that just incase some organizations have it saved that way.
organization.TwoFactorProviders = JsonSerializer.Serialize(_testConfig);
// Preliminary Asserts to make sure we are testing what we want to be testing
using var jsonDocument = JsonDocument.Parse(organization.TwoFactorProviders);
var root = jsonDocument.RootElement;
// This means it saved the | and |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/Extensions/DoubleCollectionExtensions.cs | {
"start": 189,
"end": 616
} | public static class ____
{
public static nfloat[] ToArray(this DoubleCollection doubleCollection)
{
if (doubleCollection == null || doubleCollection.Count == 0)
return Array.Empty<nfloat>();
else
{
nfloat[] array = new nfloat[doubleCollection.Count];
for (int i = 0; i < doubleCollection.Count; i++)
array[i] = (nfloat)doubleCollection[i];
return array;
}
}
}
} | DoubleCollectionExtensions |
csharp | abpframework__abp | templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs | {
"start": 193,
"end": 538
} | public class ____ : ITransientDependency
{
public ILogger<HelloWorldService> Logger { get; set; }
public HelloWorldService()
{
Logger = NullLogger<HelloWorldService>.Instance;
}
public Task SayHelloAsync()
{
Logger.LogInformation("Hello World!");
return Task.CompletedTask;
}
}
| HelloWorldService |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs | {
"start": 34377,
"end": 35028
} | public partial class ____
{
[NotifyPropertyChangedFor("")]
public int {|MVVMTK0020:number|};
}
}
""";
await VerifyAnalyzerDiagnosticsAndSuccessfulGeneration<FieldWithOrphanedDependentObservablePropertyAttributesAnalyzer>(source, LanguageVersion.CSharp8);
}
[TestMethod]
public async Task FieldWithOrphanedDependentObservablePropertyAttributesError_NotifyCanExecuteChangedFor()
{
string source = """
using CommunityToolkit.Mvvm.ComponentModel;
namespace MyApp
{
| MyViewModel |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAny.cs | {
"start": 4442,
"end": 8623
} | public class ____
{
[Fact]
public void When_exclusion_of_any_string_in_null_collection_is_asserted_it_should_throw_an_argument_exception()
{
// Act
Action act = () => "a".Should().NotContainAny(null);
// Assert
act.Should().Throw<ArgumentNullException>()
.WithMessage("Cannot*containment*null*")
.WithParameterName("values");
}
[Fact]
public void When_exclusion_of_any_string_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception()
{
// Act
Action act = () => "a".Should().NotContainAny();
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("Cannot*containment*empty*")
.WithParameterName("values");
}
[Fact]
public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_all_of_the_strings_are_present_it_should_throw()
{
// Arrange
const string red = "red";
const string green = "green";
const string yellow = "yellow";
var testString = $"{red} {green} {yellow}";
// Act
Action act = () => testString.Should().NotContainAny(red, green, yellow);
// Assert
act
.Should().Throw<XunitException>()
.WithMessage($"*not*{testString}*contain any*{red}*{green}*{yellow}*");
}
[Fact]
public void
When_exclusion_of_any_string_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_throw()
{
// Arrange
const string red = "red";
const string green = "green";
const string yellow = "yellow";
const string purple = "purple";
var testString = $"{red} {green} {yellow}";
// Act
Action act = () => testString.Should().NotContainAny(red, purple, green);
// Assert
act
.Should().Throw<XunitException>()
.WithMessage($"*not*{testString}*contain any*{red}*{green}*");
}
[Fact]
public void When_exclusion_of_any_strings_is_asserted_with_reason_and_assertion_fails_then_error_message_contains_reason()
{
// Arrange
const string red = "red";
const string green = "green";
const string yellow = "yellow";
var testString = $"{red} {green} {yellow}";
// Act
Action act = () => testString.Should().NotContainAny([red], "some {0} reason", "special");
// Assert
act
.Should().Throw<XunitException>()
.WithMessage($"*not*{testString}*contain any*{red}*because*some special reason*");
}
[Fact]
public void
When_exclusion_of_any_string_in_a_collection_is_asserted_and_there_are_equivalent_but_not_exact_matches_it_should_succeed()
{
// Arrange
const string redLowerCase = "red";
const string redUpperCase = "RED";
const string greenWithoutWhitespace = "green";
const string greenWithWhitespace = " green ";
var testString = $"{redLowerCase} {greenWithoutWhitespace}";
// Act
Action act = () => testString.Should().NotContainAny(redUpperCase, greenWithWhitespace);
// Assert
act.Should().NotThrow();
}
[Fact]
public void
When_exclusion_of_any_string_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_succeed()
{
// Arrange
const string red = "red";
const string green = "green";
const string yellow = "yellow";
const string purple = "purple";
var testString = $"{red} {green}";
// Act
Action act = () => testString.Should().NotContainAny(yellow, purple);
// Assert
act.Should().NotThrow();
}
}
}
| NotContainAny |
csharp | MassTransit__MassTransit | src/MassTransit.SignalR/Utils/SerializedHubMessageExtensions.cs | {
"start": 213,
"end": 1186
} | public static class ____
{
public static SerializedHubMessage ToSerializedHubMessage(this IReadOnlyDictionary<string, byte[]> protocolMessages)
{
return new SerializedHubMessage(protocolMessages.Select(message => new SerializedMessage(message.Key, message.Value)).ToList());
}
public static IReadOnlyDictionary<string, byte[]> ToProtocolDictionary(this IEnumerable<IHubProtocol> protocols, string methodName, object[] args)
{
var serializedMessageHub = new SerializedHubMessage(new InvocationMessage(methodName, args));
var messages = new Dictionary<string, byte[]>();
foreach (var protocol in protocols)
{
ReadOnlyMemory<byte> serialized = serializedMessageHub.GetSerializedMessage(protocol);
messages.Add(protocol.Name, serialized.ToArray());
}
return messages;
}
}
}
| SerializedHubMessageExtensions |
csharp | dotnet__maui | src/Essentials/src/Connectivity/Connectivity.Native.windows.cs | {
"start": 1630,
"end": 1803
} | internal interface ____ : IEnumerable
{
}
[ComImport]
[Guid("DCB00006-570F-4A9B-8D69-199FDBA5723B")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
| IEnumNetworks |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml/xBindTests/xBind_Functions.xaml.cs | {
"start": 1190,
"end": 1422
} | public static class ____
{
public static int PropertyIntValue { get; } = 42;
public static string PropertyStringValue { get; } = "value 43";
public static string Add(double a, double b)
=> (a + b).ToString();
}
| StaticType |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3676542,
"end": 3679574
} | public partial class ____ : global::StrawberryShake.IDocument
{
private DeleteClientByIdCommandMutationMutationDocument()
{
}
public static DeleteClientByIdCommandMutationMutationDocument Instance { get; } = new DeleteClientByIdCommandMutationMutationDocument();
public global::StrawberryShake.OperationKind Kind => global::StrawberryShake.OperationKind.Mutation;
public global::System.ReadOnlySpan<global::System.Byte> Body => new global::System.Byte[0];
public global::StrawberryShake.DocumentHash Hash { get; } = new global::StrawberryShake.DocumentHash("md5Hash", "f450cfe13d84ae3c3768bac9c9fbf8b4");
public override global::System.String ToString()
{
#if NETCOREAPP3_1_OR_GREATER
return global::System.Text.Encoding.UTF8.GetString(Body);
#else
return global::System.Text.Encoding.UTF8.GetString(Body.ToArray());
#endif
}
}
/// <summary>
/// Represents the operation service of the DeleteClientByIdCommandMutation GraphQL operation
/// <code>
/// mutation DeleteClientByIdCommandMutation($input: DeleteClientByIdInput!) {
/// deleteClientById(input: $input) {
/// __typename
/// client {
/// __typename
/// ... DeleteClientByIdCommandMutation_Client
/// }
/// errors {
/// __typename
/// ... Error
/// ... ClientNotFoundError
/// ... UnauthorizedOperation
/// }
/// }
/// }
///
/// fragment DeleteClientByIdCommandMutation_Client on Client {
/// name
/// id
/// ... ClientDetailPrompt_Client
/// }
///
/// fragment ClientDetailPrompt_Client on Client {
/// id
/// name
/// api {
/// __typename
/// name
/// path
/// }
/// versions {
/// __typename
/// edges {
/// __typename
/// ... ClientDetailPrompt_ClientVersionEdge
/// }
/// pageInfo {
/// __typename
/// hasNextPage
/// endCursor
/// }
/// }
/// }
///
/// fragment ClientDetailPrompt_ClientVersionEdge on ClientVersionEdge {
/// cursor
/// node {
/// __typename
/// id
/// createdAt
/// tag
/// publishedTo {
/// __typename
/// stage {
/// __typename
/// name
/// }
/// }
/// }
/// }
///
/// fragment Error on Error {
/// message
/// }
///
/// fragment ClientNotFoundError on ClientNotFoundError {
/// message
/// clientId
/// ... Error
/// }
///
/// fragment UnauthorizedOperation on UnauthorizedOperation {
/// __typename
/// message
/// ... Error
/// }
/// </code>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| DeleteClientByIdCommandMutationMutationDocument |
csharp | EventStore__EventStore | src/KurrentDB.Core/Messages/ReplicationMessage.cs | {
"start": 15121,
"end": 16119
} | public class ____ {
public Guid SubscriptionId { get; private set; }
public Guid ConnectionId { get; private set; }
public string SubscriptionEndpoint { get; private set; }
public long TotalBytesSent { get; private set; }
public long TotalBytesReceived { get; private set; }
public int PendingSendBytes { get; private set; }
public int PendingReceivedBytes { get; private set; }
public int SendQueueSize { get; private set; }
public ReplicationStats(Guid subscriptionId, Guid connectionId, string subscriptionEndpoint,
int sendQueueSize,
long totalBytesSent, long totalBytesReceived, int pendingSendBytes, int pendingReceivedBytes) {
SubscriptionId = subscriptionId;
ConnectionId = connectionId;
SubscriptionEndpoint = subscriptionEndpoint;
SendQueueSize = sendQueueSize;
TotalBytesSent = totalBytesSent;
TotalBytesReceived = totalBytesReceived;
PendingSendBytes = pendingSendBytes;
PendingReceivedBytes = pendingReceivedBytes;
}
}
}
| ReplicationStats |
csharp | NLog__NLog | tests/NLog.UnitTests/GetLoggerTests.cs | {
"start": 1710,
"end": 4648
} | public class ____ : NLogTestBase
{
[Fact]
public void GetCurrentClassLoggerTest()
{
var logger = new LogFactory().GetCurrentClassLogger();
Assert.Equal("NLog.UnitTests.GetLoggerTests", logger.Name);
}
[Fact]
public void GetCurrentClassLoggerLambdaTest()
{
System.Linq.Expressions.Expression<Func<Logger>> sum = () => new LogFactory().GetCurrentClassLogger();
var logger = sum.Compile().Invoke();
Assert.Equal("NLog.UnitTests.GetLoggerTests", logger.Name);
}
[Fact]
[Obsolete("Replaced by GetLogger<T>(). Marked obsolete on NLog 5.2")]
public void TypedGetLoggerTest()
{
LogFactory lf = new LogFactory();
MyLogger l1 = (MyLogger)lf.GetLogger("AAA", typeof(MyLogger));
MyLogger l2 = lf.GetLogger<MyLogger>("AAA");
Logger l3 = lf.GetLogger("AAA", typeof(Logger));
Logger l5 = lf.GetLogger("AAA");
Logger l6 = lf.GetLogger("AAA");
Assert.Same(l1, l2);
Assert.Same(l5, l6);
Assert.Same(l3, l5);
Assert.NotSame(l1, l3);
Assert.Equal("AAA", l1.Name);
Assert.Equal("AAA", l3.Name);
}
[Fact]
[Obsolete("Replaced by GetCurrentClassLogger<T>(). Marked obsolete on NLog 5.2")]
public void TypedGetCurrentClassLoggerTest()
{
LogFactory lf = new LogFactory();
MyLogger l1 = (MyLogger)lf.GetCurrentClassLogger(typeof(MyLogger));
MyLogger l2 = lf.GetCurrentClassLogger<MyLogger>();
Logger l3 = lf.GetCurrentClassLogger(typeof(Logger));
Logger l5 = lf.GetCurrentClassLogger();
Logger l6 = lf.GetCurrentClassLogger();
Assert.Same(l1, l2);
Assert.Same(l5, l6);
Assert.Same(l3, l5);
Assert.NotSame(l1, l3);
Assert.Equal("NLog.UnitTests.GetLoggerTests", l1.Name);
Assert.Equal("NLog.UnitTests.GetLoggerTests", l3.Name);
}
[Fact]
public void GenericGetLoggerTest()
{
LogFactory<MyLogger> lf = new LogFactory<MyLogger>();
MyLogger l1 = lf.GetLogger("AAA");
MyLogger l2 = lf.GetLogger("AAA");
MyLogger l3 = lf.GetLogger("BBB");
Assert.Same(l1, l2);
Assert.NotSame(l1, l3);
Assert.Equal("AAA", l1.Name);
Assert.Equal("BBB", l3.Name);
}
[Fact]
public void GenericGetCurrentClassLoggerTest()
{
LogFactory<MyLogger> lf = new LogFactory<MyLogger>();
MyLogger l1 = lf.GetCurrentClassLogger();
MyLogger l2 = lf.GetCurrentClassLogger();
Assert.Same(l1, l2);
Assert.Equal("NLog.UnitTests.GetLoggerTests", l1.Name);
}
| GetLoggerTests |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Net/MimeTypes.cs | {
"start": 749,
"end": 6957
} | public static class ____
{
/// <summary>
/// Any extension in this list is considered a video file.
/// </summary>
private static readonly FrozenSet<string> _videoFileExtensions = new[]
{
".3gp",
".asf",
".avi",
".divx",
".dvr-ms",
".f4v",
".flv",
".img",
".iso",
".m2t",
".m2ts",
".m2v",
".m4v",
".mk3d",
".mkv",
".mov",
".mp4",
".mpg",
".mpeg",
".mts",
".ogg",
".ogm",
".ogv",
".rec",
".ts",
".rmvb",
".vob",
".webm",
".wmv",
".wtv",
}.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Used for extensions not in <see cref="Model.MimeTypes"/> or to override them.
/// </summary>
private static readonly FrozenDictionary<string, string> _mimeTypeLookup = new KeyValuePair<string, string>[]
{
// Type application
new(".azw3", "application/vnd.amazon.ebook"),
new(".cb7", "application/x-cb7"),
new(".cba", "application/x-cba"),
new(".cbr", "application/vnd.comicbook-rar"),
new(".cbt", "application/x-cbt"),
new(".cbz", "application/vnd.comicbook+zip"),
// Type image
new(".tbn", "image/jpeg"),
// Type text
new(".ass", "text/x-ssa"),
new(".ssa", "text/x-ssa"),
new(".edl", "text/plain"),
new(".html", "text/html; charset=UTF-8"),
new(".htm", "text/html; charset=UTF-8"),
// Type video
new(".mpegts", "video/mp2t"),
// Type audio
new(".aac", "audio/aac"),
new(".ac3", "audio/ac3"),
new(".ape", "audio/x-ape"),
new(".dsf", "audio/dsf"),
new(".dsp", "audio/dsp"),
new(".flac", "audio/flac"),
new(".m4b", "audio/mp4"),
new(".mp3", "audio/mpeg"),
new(".vorbis", "audio/vorbis"),
new(".webma", "audio/webm"),
new(".wv", "audio/x-wavpack"),
new(".xsp", "audio/xsp"),
}.ToFrozenDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
private static readonly FrozenDictionary<string, string> _extensionLookup = new KeyValuePair<string, string>[]
{
// Type application
new("application/vnd.comicbook-rar", ".cbr"),
new("application/vnd.comicbook+zip", ".cbz"),
new("application/x-cb7", ".cb7"),
new("application/x-cba", ".cba"),
new("application/x-cbr", ".cbr"),
new("application/x-cbt", ".cbt"),
new("application/x-cbz", ".cbz"),
new("application/x-javascript", ".js"),
new("application/xml", ".xml"),
new("application/x-mpegURL", ".m3u8"),
// Type audio
new("audio/aac", ".aac"),
new("audio/ac3", ".ac3"),
new("audio/dsf", ".dsf"),
new("audio/dsp", ".dsp"),
new("audio/flac", ".flac"),
new("audio/m4b", ".m4b"),
new("audio/vorbis", ".vorbis"),
new("audio/x-ape", ".ape"),
new("audio/xsp", ".xsp"),
new("audio/x-aac", ".aac"),
new("audio/x-wavpack", ".wv"),
// Type image
new("image/jpeg", ".jpg"),
new("image/tiff", ".tiff"),
new("image/x-png", ".png"),
new("image/x-icon", ".ico"),
// Type text
new("text/plain", ".txt"),
new("text/rtf", ".rtf"),
new("text/x-ssa", ".ssa"),
// Type video
new("video/vnd.mpeg.dash.mpd", ".mpd"),
new("video/x-matroska", ".mkv"),
}.ToFrozenDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
public static string GetMimeType(string path) => GetMimeType(path, MediaTypeNames.Application.Octet);
/// <summary>
/// Gets the type of the MIME.
/// </summary>
/// <param name="filename">The filename to find the MIME type of.</param>
/// <param name="defaultValue">The default value to return if no fitting MIME type is found.</param>
/// <returns>The correct MIME type for the given filename, or <paramref name="defaultValue"/> if it wasn't found.</returns>
[return: NotNullIfNotNull("defaultValue")]
public static string? GetMimeType(string filename, string? defaultValue = null)
{
ArgumentException.ThrowIfNullOrEmpty(filename);
var ext = Path.GetExtension(filename);
if (_mimeTypeLookup.TryGetValue(ext, out string? result))
{
return result;
}
if (Model.MimeTypes.TryGetMimeType(filename, out var mimeType))
{
return mimeType;
}
// Catch-all for all video types that don't require specific mime types
if (_videoFileExtensions.Contains(ext))
{
return string.Concat("video/", ext.AsSpan(1));
}
return defaultValue;
}
public static string? ToExtension(string mimeType)
{
ArgumentException.ThrowIfNullOrEmpty(mimeType);
// handle text/html; charset=UTF-8
mimeType = mimeType.AsSpan().LeftPart(';').ToString();
if (_extensionLookup.TryGetValue(mimeType, out string? result))
{
return result;
}
var extension = Model.MimeTypes.GetMimeTypeExtensions(mimeType).FirstOrDefault();
return string.IsNullOrEmpty(extension) ? null : "." + extension;
}
public static bool IsImage(ReadOnlySpan<char> mimeType)
=> mimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase);
}
}
| MimeTypes |
csharp | dotnet__aspnetcore | src/Identity/test/Identity.Test/UserManagerTest.cs | {
"start": 14251,
"end": 52039
} | private class ____ : ILookupNormalizer
{
public string NormalizeName(string key) => "#" + key;
public string NormalizeEmail(string key) => "@" + key;
}
[Fact]
public async Task FindByEmailCallsStoreWithCustomNormalizedEmail()
{
// Setup
var store = new Mock<IUserEmailStore<PocoUser>>();
var user = new PocoUser { Email = "Foo" };
store.Setup(s => s.FindByEmailAsync("@Foo", CancellationToken.None)).Returns(Task.FromResult(user)).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object);
userManager.KeyNormalizer = new CustomNormalizer();
// Act
var result = await userManager.FindByEmailAsync(user.Email);
// Assert
Assert.Equal(user, result);
store.VerifyAll();
}
[Fact]
public async Task FindByNameCallsStoreWithCustomNormalizedName()
{
// Setup
var store = new Mock<IUserEmailStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo", Email = "Bar" };
store.Setup(s => s.FindByNameAsync("#Foo", CancellationToken.None)).Returns(Task.FromResult(user)).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object);
userManager.KeyNormalizer = new CustomNormalizer();
// Act
var result = await userManager.FindByNameAsync(user.UserName);
// Assert
Assert.Equal(user, result);
store.VerifyAll();
}
[Fact]
public async Task AddToRolesCallsStore()
{
// Setup
var normalizer = MockHelpers.MockLookupNormalizer();
var store = new Mock<IUserRoleStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var roles = new string[] { "A", "B", "C", "C" };
store.Setup(s => s.AddToRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.AddToRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.AddToRoleAsync(user, normalizer.NormalizeName("C"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("C"), CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.AddToRolesAsync(user, roles);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
store.Verify(s => s.AddToRoleAsync(user, normalizer.NormalizeName("C"), CancellationToken.None), Times.Once());
}
[Fact]
public async Task AddToRolesCallsStoreWithCustomNameNormalizer()
{
// Setup
var store = new Mock<IUserRoleStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var roles = new string[] { "A", "B", "C", "C" };
store.Setup(s => s.AddToRoleAsync(user, "#A", CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.AddToRoleAsync(user, "#B", CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.AddToRoleAsync(user, "#C", CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
store.Setup(s => s.IsInRoleAsync(user, "#A", CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, "#B", CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, "#C", CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
userManager.KeyNormalizer = new CustomNormalizer();
// Act
var result = await userManager.AddToRolesAsync(user, roles);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
store.Verify(s => s.AddToRoleAsync(user, "#C", CancellationToken.None), Times.Once());
}
[Fact]
public async Task AddToRolesFailsIfUserInRole()
{
// Setup
var normalizer = MockHelpers.MockLookupNormalizer();
var store = new Mock<IUserRoleStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var roles = new[] { "A", "B", "C" };
store.Setup(s => s.AddToRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(true))
.Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object);
// Act
var result = await userManager.AddToRolesAsync(user, roles);
// Assert
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().UserAlreadyInRole("B"));
store.VerifyAll();
}
[Fact]
public async Task RemoveFromRolesCallsStore()
{
// Setup
var normalizer = MockHelpers.MockLookupNormalizer();
var store = new Mock<IUserRoleStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var roles = new[] { "A", "B", "C" };
store.Setup(s => s.RemoveFromRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.RemoveFromRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.RemoveFromRoleAsync(user, normalizer.NormalizeName("C"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(true))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(true))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("C"), CancellationToken.None))
.Returns(Task.FromResult(true))
.Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.RemoveFromRolesAsync(user, roles);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
}
[Fact]
public async Task RemoveFromRolesFailsIfNotInRole()
{
// Setup
var normalizer = MockHelpers.MockLookupNormalizer();
var store = new Mock<IUserRoleStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var roles = new string[] { "A", "B", "C" };
store.Setup(s => s.RemoveFromRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("A"), CancellationToken.None))
.Returns(Task.FromResult(true))
.Verifiable();
store.Setup(s => s.IsInRoleAsync(user, normalizer.NormalizeName("B"), CancellationToken.None))
.Returns(Task.FromResult(false))
.Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.RemoveFromRolesAsync(user, roles);
// Assert
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().UserNotInRole("B"));
store.VerifyAll();
}
[Fact]
public async Task AddClaimsCallsStore()
{
// Setup
var store = new Mock<IUserClaimStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var claims = new Claim[] { new Claim("1", "1"), new Claim("2", "2"), new Claim("3", "3") };
store.Setup(s => s.AddClaimsAsync(user, claims, CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object);
// Act
var result = await userManager.AddClaimsAsync(user, claims);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
}
[Fact]
public async Task AddClaimCallsStore()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var store = new Mock<IUserClaimStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var claim = new Claim("1", "1");
store.Setup(s => s.AddClaimsAsync(user, It.IsAny<IEnumerable<Claim>>(), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
// Act
var result = await userManager.AddClaimAsync(user, claim);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "add_claims"),
KeyValuePair.Create<string, object>("aspnetcore.identity.result", "success")
]));
}
[Fact]
public async Task UpdateClaimCallsStore()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var store = new Mock<IUserClaimStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var claim = new Claim("1", "1");
var newClaim = new Claim("1", "2");
store.Setup(s => s.ReplaceClaimAsync(user, It.IsAny<Claim>(), It.IsAny<Claim>(), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
// Act
var result = await userManager.ReplaceClaimAsync(user, claim, newClaim);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "replace_claim"),
KeyValuePair.Create<string, object>("aspnetcore.identity.result", "success")
]));
}
[Fact]
public async Task CheckPasswordWillRehashPasswordWhenNeeded()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
using var checkPassword = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.CheckPasswordAttemptsCounterName);
var store = new Mock<IUserPasswordStore<PocoUser>>();
var hasher = new Mock<IPasswordHasher<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var pwd = "password";
var hashed = "hashed";
var rehashed = "rehashed";
store.Setup(s => s.GetPasswordHashAsync(user, CancellationToken.None))
.ReturnsAsync(hashed)
.Verifiable();
store.Setup(s => s.SetPasswordHashAsync(user, It.IsAny<string>(), CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable();
store.Setup(x => x.UpdateAsync(It.IsAny<PocoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success));
hasher.Setup(s => s.VerifyHashedPassword(user, hashed, pwd)).Returns(PasswordVerificationResult.SuccessRehashNeeded).Verifiable();
hasher.Setup(s => s.HashPassword(user, pwd)).Returns(rehashed).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
userManager.PasswordHasher = hasher.Object;
// Act
var result = await userManager.CheckPasswordAsync(user, pwd);
// Assert
Assert.True(result);
store.VerifyAll();
hasher.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "password_rehash"),
KeyValuePair.Create<string, object>("aspnetcore.identity.result", "success")
]));
Assert.Collection(checkPassword.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.password_check_result", "success_rehash_needed")
]));
}
[Fact]
public async Task CreateFailsWithNullSecurityStamp()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var createUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.CreateDurationName);
var store = new Mock<IUserSecurityStampStore<PocoUser>>();
var manager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
var user = new PocoUser { UserName = "nulldude" };
store.Setup(s => s.GetSecurityStampAsync(user, It.IsAny<CancellationToken>())).ReturnsAsync(default(string)).Verifiable();
// Act
// Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => manager.CreateAsync(user));
Assert.Contains(Extensions.Identity.Core.Resources.NullSecurityStamp, ex.Message);
store.VerifyAll();
Assert.Collection(createUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user_type", "Microsoft.AspNetCore.Identity.Test.PocoUser"),
KeyValuePair.Create<string, object>("error.type", "System.InvalidOperationException")
]));
}
[Fact]
public async Task UpdateFailsWithNullSecurityStamp()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var store = new Mock<IUserSecurityStampStore<PocoUser>>();
var manager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
var user = new PocoUser { UserName = "nulldude" };
store.Setup(s => s.GetSecurityStampAsync(user, It.IsAny<CancellationToken>())).ReturnsAsync(default(string)).Verifiable();
// Act
// Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => manager.UpdateAsync(user));
Assert.Contains(Extensions.Identity.Core.Resources.NullSecurityStamp, ex.Message);
store.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "update"),
KeyValuePair.Create<string, object>("error.type", "System.InvalidOperationException")
]));
}
[Fact]
public async Task RemoveClaimsCallsStore()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var store = new Mock<IUserClaimStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var claims = new Claim[] { new Claim("1", "1"), new Claim("2", "2"), new Claim("3", "3") };
store.Setup(s => s.RemoveClaimsAsync(user, claims, CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
// Act
var result = await userManager.RemoveClaimsAsync(user, claims);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "remove_claims"),
KeyValuePair.Create<string, object>("aspnetcore.identity.result", "success")
]));
}
[Fact]
public async Task RemoveClaimCallsStore()
{
// Setup
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var store = new Mock<IUserClaimStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var claim = new Claim("1", "1");
store.Setup(s => s.RemoveClaimsAsync(user, It.IsAny<IEnumerable<Claim>>(), CancellationToken.None))
.Returns(Task.FromResult(0))
.Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object, meterFactory: testMeterFactory);
// Act
var result = await userManager.RemoveClaimAsync(user, claim);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "remove_claims"),
KeyValuePair.Create<string, object>("aspnetcore.identity.result", "success")
]));
}
[Fact]
public async Task AddOrUpdatePasskeyAsyncCallsStore()
{
// Setup
var store = new Mock<IUserPasskeyStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var passkey = new UserPasskeyInfo(null, null, default, 0, null, false, false, false, null, null);
store.Setup(s => s.AddOrUpdatePasskeyAsync(user, passkey, CancellationToken.None)).Returns(Task.CompletedTask).Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.AddOrUpdatePasskeyAsync(user, passkey);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
}
[Fact]
public async Task GetPasskeysAsyncCallsStore()
{
// Setup
var store = new Mock<IUserPasskeyStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var passkey = new UserPasskeyInfo(null, null, default, 0, null, false, false, false, null, null);
var passkeys = (IList<UserPasskeyInfo>)[passkey];
store.Setup(s => s.GetPasskeysAsync(user, CancellationToken.None)).Returns(Task.FromResult(passkeys)).Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.GetPasskeysAsync(user);
// Assert
Assert.Same(passkeys, result);
store.VerifyAll();
}
[Fact]
public async Task FindByPasskeyIdCallsStore()
{
// Setup
var store = new Mock<IUserPasskeyStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var credentialId = (byte[])[1, 2, 3, 4, 5, 6, 7, 8];
store.Setup(s => s.FindByPasskeyIdAsync(credentialId, CancellationToken.None)).Returns(Task.FromResult(user)).Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.FindByPasskeyIdAsync(credentialId);
// Assert
Assert.Equal(user, result);
store.VerifyAll();
}
[Fact]
public async Task RemovePasskeyAsyncCallsStore()
{
// Setup
var store = new Mock<IUserPasskeyStore<PocoUser>>();
var user = new PocoUser { UserName = "Foo" };
var credentialId = (byte[])[1, 2, 3, 4, 5, 6, 7, 8];
store.Setup(s => s.RemovePasskeyAsync(user, credentialId, CancellationToken.None)).Returns(Task.CompletedTask).Verifiable();
store.Setup(s => s.UpdateAsync(user, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
var userManager = MockHelpers.TestUserManager<PocoUser>(store.Object);
// Act
var result = await userManager.RemovePasskeyAsync(user, credentialId);
// Assert
Assert.True(result.Succeeded);
store.VerifyAll();
}
[Fact]
public async Task CheckPasswordWithNullUserReturnsFalse()
{
var testMeterFactory = new TestMeterFactory();
using var checkPassword = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.CheckPasswordAttemptsCounterName);
var manager = MockHelpers.TestUserManager(new EmptyStore(), meterFactory: testMeterFactory);
Assert.False(await manager.CheckPasswordAsync(null, "whatevs"));
Assert.Collection(checkPassword.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.password_check_result", "user_missing")
]));
}
[Fact]
public void UsersQueryableFailWhenStoreNotImplemented()
{
var manager = MockHelpers.TestUserManager(new NoopUserStore());
Assert.False(manager.SupportsQueryableUsers);
Assert.Throws<NotSupportedException>(() => manager.Users.Count());
}
[Fact]
public async Task UsersEmailMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserEmail);
await Assert.ThrowsAsync<NotSupportedException>(() => manager.FindByEmailAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.SetEmailAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.GetEmailAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.IsEmailConfirmedAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.ConfirmEmailAsync(null, null));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "set_email"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "confirm_email"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task UsersPhoneNumberMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserPhoneNumber);
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.SetPhoneNumberAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.ChangePhoneNumberAsync(null, null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.GetPhoneNumberAsync(null));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "set_phone_number"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "change_phone_number"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task TokenMethodsThrowWithNoTokenProvider()
{
var testMeterFactory = new TestMeterFactory();
using var generateToken = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.GenerateTokensCounterName);
using var verifyToken = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.VerifyTokenAttemptsCounterName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
var user = new PocoUser();
await Assert.ThrowsAsync<NotSupportedException>(
async () => await manager.GenerateUserTokenAsync(user, "bogus", "test-purpose"));
await Assert.ThrowsAsync<NotSupportedException>(
async () => await manager.VerifyUserTokenAsync(user, "bogus", "test-purpose", null));
Assert.Collection(generateToken.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.token_purpose", "_OTHER"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
Assert.Collection(verifyToken.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.token_purpose", "_OTHER"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task PasswordMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var createUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.CreateDurationName);
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
using var checkPassword = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.CheckPasswordAttemptsCounterName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserPassword);
await Assert.ThrowsAsync<NotSupportedException>(() => manager.CreateAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.ChangePasswordAsync(null, null, null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.AddPasswordAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.RemovePasswordAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.CheckPasswordAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.HasPasswordAsync(null));
Assert.Collection(createUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "change_password"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "add_password"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "remove_password"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
Assert.Collection(checkPassword.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task SecurityStampMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
using var generateToken = new MetricCollector<long>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.GenerateTokensCounterName);
var store = new Mock<IUserStore<PocoUser>>();
store.Setup(x => x.GetUserIdAsync(It.IsAny<PocoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(Guid.NewGuid().ToString()));
var manager = MockHelpers.TestUserManager(store.Object, meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserSecurityStamp);
await Assert.ThrowsAsync<NotSupportedException>(() => manager.UpdateSecurityStampAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(() => manager.GetSecurityStampAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(
() => manager.VerifyChangePhoneNumberTokenAsync(new PocoUser(), "1", "111-111-1111"));
await Assert.ThrowsAsync<NotSupportedException>(
() => manager.GenerateChangePhoneNumberTokenAsync(new PocoUser(), "111-111-1111"));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "update_security_stamp"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
Assert.Collection(generateToken.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertContainsTags(m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.token_purpose", "change_phone_number"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task LoginMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserLogin);
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.AddLoginAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.RemoveLoginAsync(null, null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.GetLoginsAsync(null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.FindByLoginAsync(null, null));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "add_login"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "remove_login"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
[Fact]
public async Task ClaimMethodsFailWhenStoreNotImplemented()
{
var testMeterFactory = new TestMeterFactory();
using var updateUser = new MetricCollector<double>(testMeterFactory, "Microsoft.AspNetCore.Identity", UserManagerMetrics.UpdateDurationName);
var manager = MockHelpers.TestUserManager(new NoopUserStore(), meterFactory: testMeterFactory);
Assert.False(manager.SupportsUserClaim);
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.AddClaimAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.ReplaceClaimAsync(null, null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.RemoveClaimAsync(null, null));
await Assert.ThrowsAsync<NotSupportedException>(async () => await manager.GetClaimsAsync(null));
Assert.Collection(updateUser.GetMeasurementSnapshot(),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "add_claims"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "replace_claim"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]),
m => MetricsHelpers.AssertHasDurationAndContainsTags(m.Value, m.Tags,
[
KeyValuePair.Create<string, object>("aspnetcore.identity.user.update_type", "remove_claims"),
KeyValuePair.Create<string, object>("error.type", "System.NotSupportedException"),
]));
}
| CustomNormalizer |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ModelBinding/ParameterBinderTest.cs | {
"start": 32208,
"end": 32333
} | private class ____ : Person
{
[Required]
public string DerivedProperty { get; set; }
}
| DerivedPerson |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.Core/Areas/Core/Controllers/UserAddressController.cs | {
"start": 528,
"end": 11248
} | public class ____ : Controller
{
private readonly IRepository<UserAddress> _userAddressRepository;
private readonly IRepositoryWithTypedId<Country, string> _countryRepository;
private readonly IRepository<StateOrProvince> _stateOrProvinceRepository;
private readonly IRepository<District> _districtRepository;
private readonly IRepository<User> _userRepository;
private readonly IWorkContext _workContext;
public UserAddressController(IRepository<UserAddress> userAddressRepository, IRepositoryWithTypedId<Country, string> countryRepository, IRepository<StateOrProvince> stateOrProvinceRepository,
IRepository<District> districtRepository, IRepository<User> userRepository, IWorkContext workContext)
{
_userAddressRepository = userAddressRepository;
_countryRepository = countryRepository;
_stateOrProvinceRepository = stateOrProvinceRepository;
_districtRepository = districtRepository;
_userRepository = userRepository;
_workContext = workContext;
}
[Route("user/address")]
public async Task<IActionResult> List()
{
var currentUser = await _workContext.GetCurrentUser();
var model = _userAddressRepository
.Query()
.Where(x => x.AddressType == AddressType.Shipping && x.UserId == currentUser.Id)
.Select(x => new UserAddressListItem
{
AddressId = x.AddressId,
UserAddressId = x.Id,
ContactName = x.Address.ContactName,
Phone = x.Address.Phone,
AddressLine1 = x.Address.AddressLine1,
AddressLine2 = x.Address.AddressLine2,
DistrictName = x.Address.District.Name,
StateOrProvinceName = x.Address.StateOrProvince.Name,
CountryName = x.Address.Country.Name,
DisplayCity = x.Address.Country.IsCityEnabled,
DisplayZipCode = x.Address.Country.IsZipCodeEnabled,
DisplayDistrict = x.Address.Country.IsDistrictEnabled
}).ToList();
foreach (var item in model)
{
item.IsDefaultShippingAddress = item.UserAddressId == currentUser.DefaultShippingAddressId;
}
return View(model);
}
[HttpGet("api/country-states-provinces/{countryId}")]
public async Task<IActionResult> Get(string countryId)
{
var country = await _countryRepository.Query().Include(x => x.StatesOrProvinces).FirstOrDefaultAsync(x => x.Id == countryId);
if (country == null)
{
return NotFound();
}
var model = new
{
CountryId = country.Id,
CountryName = country.Name,
country.IsBillingEnabled,
country.IsShippingEnabled,
country.IsCityEnabled,
country.IsZipCodeEnabled,
country.IsDistrictEnabled,
StatesOrProvinces = country.StatesOrProvinces.Select(x => new { x.Id, x.Name })
};
return Json(model);
}
[Route("user/address/create")]
public IActionResult Create()
{
var model = new UserAddressFormViewModel();
PopulateAddressFormData(model);
return View(model);
}
[Route("user/address/create")]
[HttpPost]
public async Task<IActionResult> Create(UserAddressFormViewModel model)
{
if (ModelState.IsValid)
{
var currentUser = await _workContext.GetCurrentUser();
var address = new Address
{
AddressLine1 = model.AddressLine1,
AddressLine2 = model.AddressLine2,
ContactName = model.ContactName,
CountryId = model.CountryId,
StateOrProvinceId = model.StateOrProvinceId,
DistrictId = model.DistrictId,
City = model.City,
ZipCode = model.ZipCode,
Phone = model.Phone
};
var userAddress = new UserAddress
{
Address = address,
AddressType = AddressType.Shipping,
UserId = currentUser.Id
};
_userAddressRepository.Add(userAddress);
_userAddressRepository.SaveChanges();
return RedirectToAction("List");
}
PopulateAddressFormData(model);
return View(model);
}
[Route("user/address/edit/{id}")]
public async Task<IActionResult> Edit(long id)
{
var currentUser = await _workContext.GetCurrentUser();
var userAddress = _userAddressRepository.Query()
.Include(x => x.Address)
.FirstOrDefault(x => x.Id == id && x.UserId == currentUser.Id);
if (userAddress == null)
{
return NotFound();
}
var model = new UserAddressFormViewModel
{
Id = userAddress.Id,
ContactName = userAddress.Address.ContactName,
Phone = userAddress.Address.Phone,
AddressLine1 = userAddress.Address.AddressLine1,
AddressLine2 = userAddress.Address.AddressLine2,
CountryId = userAddress.Address.CountryId,
DistrictId = userAddress.Address.DistrictId,
StateOrProvinceId = userAddress.Address.StateOrProvinceId,
City = userAddress.Address.City,
ZipCode = userAddress.Address.ZipCode
};
PopulateAddressFormData(model);
return View(model);
}
[Route("user/address/edit/{id}")]
[HttpPost]
public async Task<IActionResult> Edit(long id, UserAddressFormViewModel model)
{
if (ModelState.IsValid)
{
var currentUser = await _workContext.GetCurrentUser();
var userAddress = _userAddressRepository.Query()
.Include(x => x.Address)
.FirstOrDefault(x => x.Id == id && x.UserId == currentUser.Id);
if (userAddress == null)
{
return NotFound();
}
userAddress.Address.AddressLine1 = model.AddressLine1;
userAddress.Address.AddressLine2 = model.AddressLine2;
userAddress.Address.ContactName = model.ContactName;
userAddress.Address.CountryId = model.CountryId;
userAddress.Address.StateOrProvinceId = model.StateOrProvinceId;
userAddress.Address.DistrictId = model.DistrictId;
userAddress.Address.City = model.City;
userAddress.Address.ZipCode = model.ZipCode;
userAddress.Address.Phone = model.Phone;
_userAddressRepository.SaveChanges();
return RedirectToAction("List");
}
PopulateAddressFormData(model);
return View(model);
}
[HttpPost]
public async Task<IActionResult> SetAsDefault(long id)
{
var currentUser = await _workContext.GetCurrentUser();
var userAddress = _userAddressRepository.Query()
.FirstOrDefault(x => x.Id == id && x.UserId == currentUser.Id);
if (userAddress == null)
{
return NotFound();
}
currentUser.DefaultShippingAddressId = userAddress.Id;
_userRepository.SaveChanges();
return RedirectToAction("List");
}
[HttpPost]
public async Task<IActionResult> Delete(long id)
{
var currentUser = await _workContext.GetCurrentUser();
var userAddress = _userAddressRepository.Query()
.FirstOrDefault(x => x.Id == id && x.UserId == currentUser.Id);
if (userAddress == null)
{
return NotFound();
}
if (currentUser.DefaultShippingAddressId == userAddress.Id)
{
currentUser.DefaultShippingAddressId = null;
}
_userAddressRepository.Remove(userAddress);
_userAddressRepository.SaveChanges();
return RedirectToAction("List");
}
private void PopulateAddressFormData(UserAddressFormViewModel model)
{
var shippableCountries = _countryRepository.Query()
.Where(x => x.IsShippingEnabled)
.OrderBy(x => x.Name);
if (!shippableCountries.Any())
{
return;
}
model.Countries = shippableCountries
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
var selectedShipableCountryId = !string.IsNullOrEmpty(model.CountryId) ? model.CountryId : model.Countries.First().Value;
var selectedCountry = shippableCountries.FirstOrDefault(c => c.Id == selectedShipableCountryId);
if (selectedCountry != null)
{
model.DisplayCity = selectedCountry.IsCityEnabled;
model.DisplayDistrict = selectedCountry.IsDistrictEnabled;
model.DisplayZipCode = selectedCountry.IsZipCodeEnabled;
}
model.StateOrProvinces = _stateOrProvinceRepository
.Query()
.Where(x => x.CountryId == selectedShipableCountryId)
.OrderBy(x => x.Name)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
if (model.StateOrProvinceId > 0)
{
model.Districts = _districtRepository
.Query()
.Where(x => x.StateOrProvinceId == model.StateOrProvinceId)
.OrderBy(x => x.Name)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
}
}
}
}
| UserAddressController |
csharp | AutoFixture__AutoFixture | Src/AutoFixture/Kernel/NoSpecimenOutputGuard.cs | {
"start": 3994,
"end": 5544
} | interface ____ abstract class; if this is the case, register an ISpecimenBuilder that can create specimens based on the request. If this happens in a strongly typed Build<T> expression, try supplying a factory using one of the IFactoryComposer<T> methods.", request));
}
return result;
}
/// <summary>Composes the supplied builders.</summary>
/// <param name="builders">The builders to compose.</param>
/// <returns>
/// A new <see cref="ISpecimenBuilderNode" /> instance containing
/// <paramref name="builders" /> as child nodes.
/// </returns>
public ISpecimenBuilderNode Compose(IEnumerable<ISpecimenBuilder> builders)
{
if (builders == null) throw new ArgumentNullException(nameof(builders));
var composedBuilder = CompositeSpecimenBuilder.ComposeIfMultiple(builders);
return new NoSpecimenOutputGuard(composedBuilder, this.Specification);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{ISpecimenBuilder}" /> that can be used to
/// iterate through the collection.
/// </returns>
public IEnumerator<ISpecimenBuilder> GetEnumerator()
{
yield return this.Builder;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| or |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Api.Analyzers/test/TestFiles/MvcFactsTest/IsControllerTests.cs | {
"start": 299,
"end": 368
} | public class ____ : AbstractController { }
| DerivedAbstractController |
csharp | AvaloniaUI__Avalonia | src/Avalonia.X11/XIStructs.cs | {
"start": 7433,
"end": 7602
} | internal enum ____ : int
{
None = 0,
XIPointerEmulated = (1 << 16)
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe | XiDeviceEventFlags |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Correctness/MiniJSON.cs | {
"start": 8572,
"end": 12005
} | sealed class ____
{
StringBuilder builder;
Serializer()
{
builder = new StringBuilder();
}
public static string Serialize(object obj)
{
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value)
{
IList asList;
IDictionary asDict;
string asStr;
if (value == null)
{
builder.Append("null");
}
else if ((asStr = value as string) != null)
{
SerializeString(asStr);
}
else if (value is bool)
{
builder.Append((bool)value ? "true" : "false");
}
else if ((asList = value as IList) != null)
{
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null)
{
SerializeObject(asDict);
}
else if (value is char)
{
SerializeString(new string((char)value, 1));
}
else
{
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj)
{
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys)
{
if (!first)
{
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray)
{
builder.Append('[');
bool first = true;
for (int i = 0; i < anArray.Count; i++)
{
object obj = anArray[i];
if (!first)
{
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str)
{
builder.Append('\"');
char[] charArray = str.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
switch (c)
{
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126))
{
builder.Append(c);
}
else
{
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value)
{
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float)
{
builder.Append(((float)value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong)
{
builder.Append(value);
}
else if (value is double
|| value is decimal)
{
builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
else
{
SerializeString(value.ToString());
}
}
}
}
}
| Serializer |
csharp | dotnet__orleans | src/api/Orleans.Core.Abstractions/Orleans.Core.Abstractions.cs | {
"start": 66372,
"end": 66709
} | public partial class ____ : IGrainTypeProvider
{
public AttributeGrainTypeProvider(System.IServiceProvider serviceProvider) { }
public bool TryGetGrainType(System.Type grainClass, out Runtime.GrainType grainType) { throw null; }
}
[GenerateSerializer]
[Immutable]
public sealed | AttributeGrainTypeProvider |
csharp | ServiceStack__ServiceStack | ServiceStack.Redis/tests/ServiceStack.Redis.Tests/Generic/RedisClientHashTestsModels.Async.cs | {
"start": 1917,
"end": 2242
} | public class ____
// : RedisClientHashTestsBaseAsync<DateTime>
//{
// private readonly IModelFactory<DateTime> factory = new DateTimeFactory();
// protected override IModelFactory<DateTime> Factory
// {
// get { return factory; }
// }
//}
} | RedisClientHashTestsDateTimeAsync |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.IntegrationTests.Appium/WindowTests.cs | {
"start": 359,
"end": 23898
} | public class ____ : TestBase
{
public WindowTests(DefaultAppFixture fixture)
: base(fixture, "Window")
{
}
[Theory]
[MemberData(nameof(StartupLocationData))]
public void StartupLocation(Size? size, ShowWindowMode mode, WindowStartupLocation location, bool canResize)
{
using var window = OpenWindow(size, mode, location, canResize: canResize);
var info = GetWindowInfo();
if (size.HasValue)
Assert.Equal(size.Value, info.ClientSize);
Assert.True(info.FrameSize.Width >= info.ClientSize.Width, "Expected frame width >= client width.");
Assert.True(info.FrameSize.Height > info.ClientSize.Height, "Expected frame height > client height.");
var frameRect = new PixelRect(info.Position, PixelSize.FromSize(info.FrameSize, info.Scaling));
switch (location)
{
case WindowStartupLocation.CenterScreen:
{
var expected = info.ScreenRect.CenterRect(frameRect);
AssertCloseEnough(expected.Position, frameRect.Position);
break;
}
case WindowStartupLocation.CenterOwner:
{
Assert.NotNull(info.OwnerRect);
var expected = info.OwnerRect!.Value.CenterRect(frameRect);
AssertCloseEnough(expected.Position, frameRect.Position);
break;
}
}
}
[Theory]
[MemberData(nameof(WindowStateData))]
public void WindowState(Size? size, ShowWindowMode mode, WindowState state, bool canResize)
{
using var window = OpenWindow(size, mode, state: state, canResize: canResize);
try
{
var info = GetWindowInfo();
Assert.Equal(state, info.WindowState);
switch (state)
{
case Controls.WindowState.Normal:
Assert.True(info.FrameSize.Width * info.Scaling < info.ScreenRect.Size.Width);
Assert.True(info.FrameSize.Height * info.Scaling < info.ScreenRect.Size.Height);
break;
case Controls.WindowState.Maximized:
case Controls.WindowState.FullScreen:
Assert.True(info.FrameSize.Width * info.Scaling >= info.ScreenRect.Size.Width);
Assert.True(info.FrameSize.Height * info.Scaling >= info.ScreenRect.Size.Height);
break;
}
}
finally
{
if (state == Controls.WindowState.FullScreen)
{
try
{
Session.FindElementByAccessibilityId("CurrentWindowState").SendClick();
Session.FindElementByAccessibilityId("WindowStateNormal").SendClick();
// Wait for animations to run.
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
Thread.Sleep(1000);
}
catch
{
/* Ignore errors in cleanup */
}
}
}
}
[PlatformFact(TestPlatforms.Windows)]
public void OnWindows_Docked_Windows_Retain_Size_Position_When_Restored()
{
using (OpenWindow(new Size(400, 400), ShowWindowMode.NonOwned, WindowStartupLocation.Manual))
{
var windowState = Session.FindElementByAccessibilityId("CurrentWindowState");
Assert.Equal("Normal", windowState.GetComboBoxValue());
var window = Session.FindElements(By.XPath("//Window")).First();
new Actions(Session)
.KeyDown(Keys.Meta)
.SendKeys(Keys.Left)
.KeyUp(Keys.Meta)
.Perform();
var original = GetWindowInfo();
windowState.Click();
Session.FindElementByName("Minimized").SendClick();
new Actions(Session)
.KeyDown(Keys.Alt)
.SendKeys(Keys.Tab)
.KeyUp(Keys.Alt)
.Perform();
var current = GetWindowInfo();
Assert.Equal(original.Position, current.Position);
Assert.Equal(original.FrameSize, current.FrameSize);
}
}
[Fact]
public void Showing_Window_With_Size_Larger_Than_Screen_Measures_Content_With_Working_Area()
{
using (OpenWindow(new Size(4000, 2200), ShowWindowMode.NonOwned, WindowStartupLocation.Manual))
{
var screenRectTextBox = Session.FindElementByAccessibilityId("CurrentClientSize");
var measuredWithTextBlock = Session.FindElementByAccessibilityId("CurrentMeasuredWithText");
var measuredWithString = measuredWithTextBlock.Text;
var workingAreaString = screenRectTextBox.Text;
var workingArea = Size.Parse(workingAreaString);
var measuredWith = Size.Parse(measuredWithString);
Assert.Equal(workingArea, measuredWith);
}
}
[Theory]
[InlineData(ShowWindowMode.NonOwned)]
[InlineData(ShowWindowMode.Owned)]
[InlineData(ShowWindowMode.Modal)]
public void ShowMode(ShowWindowMode mode)
{
using var window = OpenWindow(null, mode, WindowStartupLocation.Manual);
var windowState = Session.FindElementByAccessibilityId("CurrentWindowState");
var original = GetWindowInfo();
Assert.Equal("Normal", windowState.GetComboBoxValue());
windowState.Click();
Session.FindElementByAccessibilityId("WindowStateMaximized").SendClick();
Assert.Equal("Maximized", windowState.GetComboBoxValue());
windowState.Click();
Session.FindElementByAccessibilityId("WindowStateNormal").SendClick();
var current = GetWindowInfo();
Assert.Equal(original.Position, current.Position);
Assert.Equal(original.FrameSize, current.FrameSize);
// On macOS, only non-owned windows can go fullscreen.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || mode == ShowWindowMode.NonOwned)
{
windowState.Click();
Session.FindElementByAccessibilityId("WindowStateFullScreen").SendClick();
Assert.Equal("FullScreen", windowState.GetComboBoxValue());
current = GetWindowInfo();
var clientSize = PixelSize.FromSize(current.ClientSize, current.Scaling);
Assert.True(clientSize.Width >= current.ScreenRect.Width);
Assert.True(clientSize.Height >= current.ScreenRect.Height);
windowState.SendClick();
Session.FindElementByAccessibilityId("WindowStateNormal").SendClick();
current = GetWindowInfo();
Assert.Equal(original.Position, current.Position);
Assert.Equal(original.FrameSize, current.FrameSize);
}
}
[Fact]
public void Extended_Client_Window_Shows_With_Requested_Size()
{
var clientSize = new Size(400, 400);
using var window = OpenWindow(clientSize, ShowWindowMode.NonOwned, WindowStartupLocation.CenterScreen, extendClientArea: true);
var windowState = Session.FindElementByAccessibilityId("CurrentWindowState");
var current = GetWindowInfo();
Assert.Equal(current.ClientSize, clientSize);
}
[Fact]
public void TransparentWindow()
{
var showTransparentWindow = Session.FindElementByAccessibilityId("ShowTransparentWindow");
showTransparentWindow.Click();
Thread.Sleep(1000);
var window = Session.FindElementByAccessibilityId("TransparentWindow");
var screenshot = window.GetScreenshot();
window.Click();
var img = SixLabors.ImageSharp.Image.Load<Rgba32>(screenshot.AsByteArray);
var topLeftColor = img[10, 10];
var centerColor = img[img.Width / 2, img.Height / 2];
Assert.Equal(new Rgba32(0, 128, 0), topLeftColor);
Assert.Equal(new Rgba32(255, 0, 0), centerColor);
}
[Fact]
public void TransparentPopup()
{
var showTransparentWindow = Session.FindElementByAccessibilityId("ShowTransparentPopup");
showTransparentWindow.Click();
Thread.Sleep(1000);
var window = Session.FindElementByAccessibilityId("TransparentPopupBackground");
var container = window.FindElementByAccessibilityId("PopupContainer");
var screenshot = container.GetScreenshot();
window.Click();
var img = SixLabors.ImageSharp.Image.Load<Rgba32>(screenshot.AsByteArray);
var topLeftColor = img[10, 10];
var centerColor = img[img.Width / 2, img.Height / 2];
Assert.Equal(new Rgba32(0, 128, 0), topLeftColor);
Assert.Equal(new Rgba32(255, 0, 0), centerColor);
}
[PlatformFact(TestPlatforms.Windows)]
public void Owned_Window_Should_Appear_Above_Topmost_Owner()
{
var showTopmostWindow = Session.FindElementByAccessibilityId("ShowTopmostWindow");
using var window = showTopmostWindow.OpenWindowWithClick();
Thread.Sleep(1000);
var ownerWindow = Session.GetWindowById("OwnerWindow");
var ownedWindow = Session.GetWindowById("OwnedWindow");
Assert.NotNull(ownerWindow);
Assert.NotNull(ownedWindow);
var ownerPosition = GetPosition(ownerWindow);
var ownedPosition = GetPosition(ownedWindow);
// Owned Window moves
var moveButton = ownedWindow.FindElementByAccessibilityId("MoveButton");
moveButton.Click();
Thread.Sleep(1000);
Assert.Equal(GetPosition(ownerWindow), ownerPosition);
Assert.NotEqual(GetPosition(ownedWindow), ownedPosition);
PixelPoint GetPosition(AppiumWebElement window)
{
return PixelPoint.Parse(window.FindElementByAccessibilityId("CurrentPosition").Text);
}
}
[Theory]
[InlineData(ShowWindowMode.NonOwned, true)]
[InlineData(ShowWindowMode.Owned, true)]
[InlineData(ShowWindowMode.Modal, true)]
[InlineData(ShowWindowMode.NonOwned, false)]
[InlineData(ShowWindowMode.Owned, false)]
[InlineData(ShowWindowMode.Modal, false)]
public void Window_Has_Disabled_Maximize_Button_When_CanResize_Is_False(ShowWindowMode mode, bool extendClientArea)
{
using (OpenWindow(null, mode, WindowStartupLocation.Manual, canResize: false, extendClientArea: extendClientArea))
{
var secondaryWindow = Session.GetWindowById("SecondaryWindow");
AppiumWebElement? maximizeButton;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
maximizeButton = extendClientArea ?
secondaryWindow.FindElementByXPath("//Button[@Name='Maximize']") :
secondaryWindow.FindElementByXPath("//TitleBar/Button[2]");
}
else
{
maximizeButton = mode == ShowWindowMode.NonOwned ?
secondaryWindow.FindElementByAccessibilityId("_XCUI:FullScreenWindow") :
secondaryWindow.FindElementByAccessibilityId("_XCUI:ZoomWindow");
}
Assert.False(maximizeButton.Enabled);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Window_Minimize_Button_Enabled_Matches_CanMinimize(bool canMinimize)
{
using (OpenWindow(canMinimize: canMinimize))
{
var secondaryWindow = Session.GetWindowById("SecondaryWindow");
var windowChrome = secondaryWindow.GetSystemChromeButtons();
Assert.NotNull(windowChrome.Minimize);
Assert.Equal(canMinimize, windowChrome.Minimize!.Enabled);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Window_Maximize_Button_Enabled_Matches_CanMaximize(bool canMaximize)
{
using (OpenWindow(canMaximize: canMaximize))
{
var secondaryWindow = Session.GetWindowById("SecondaryWindow");
var windowChrome = secondaryWindow.GetSystemChromeButtons();
var maximizeButton = windowChrome.FullScreen ?? windowChrome.Maximize;
Assert.NotNull(maximizeButton);
Assert.Equal(canMaximize, maximizeButton.Enabled);
}
}
[Fact]
public void Changing_SystemDecorations_Should_Not_Change_Frame_Size_And_Position()
{
using (OpenWindow(null, ShowWindowMode.NonOwned, WindowStartupLocation.Manual))
{
var info = GetWindowInfo();
Session.FindElementByAccessibilityId("CurrentSystemDecorations").Click();
Session.FindElementByAccessibilityId("SystemDecorationsNone").SendClick();
var updatedInfo = GetWindowInfo();
Assert.Equal(info.FrameSize, updatedInfo.FrameSize);
Assert.Equal(info.Position, updatedInfo.Position);
Session.FindElementByAccessibilityId("CurrentSystemDecorations").Click();
Session.FindElementByAccessibilityId("SystemDecorationsFull").SendClick();
updatedInfo = GetWindowInfo();
Assert.Equal(info.FrameSize, updatedInfo.FrameSize);
Assert.Equal(info.Position, updatedInfo.Position);
}
}
[Fact]
public void Changing_WindowState_Should_Not_Change_Frame_Size_And_Position()
{
using (OpenWindow())
{
var info = GetWindowInfo();
Session.FindElementByAccessibilityId("CurrentWindowState").SendClick();
Session.FindElementByAccessibilityId("WindowStateMaximized").SendClick();
Session.FindElementByAccessibilityId("CurrentWindowState").SendClick();
Session.FindElementByAccessibilityId("WindowStateNormal").SendClick();
var updatedInfo = GetWindowInfo();
Assert.Equal(info.FrameSize, updatedInfo.FrameSize);
Assert.Equal(info.Position, updatedInfo.Position);
}
}
[PlatformFact(TestPlatforms.Windows)]
public void Changing_Size_Should_Not_Change_Position()
{
using (OpenWindow())
{
var info = GetWindowInfo();
Session.FindElementByAccessibilityId("AddToWidth").SendClick();
Session.FindElementByAccessibilityId("AddToHeight").SendClick();
var updatedInfo = GetWindowInfo();
Assert.Equal(info.Position, updatedInfo.Position);
Assert.Equal(info.FrameSize
.WithWidth(info.FrameSize.Width + 10)
.WithHeight(info.FrameSize.Height + 10), updatedInfo.FrameSize);
}
}
public static TheoryData<Size?, ShowWindowMode, WindowStartupLocation, bool> StartupLocationData()
{
var sizes = new Size?[] { null, new Size(400, 300) };
var data = new TheoryData<Size?, ShowWindowMode, WindowStartupLocation, bool>();
foreach (var size in sizes)
{
foreach (var mode in Enum.GetValues<ShowWindowMode>())
{
foreach (var location in Enum.GetValues<WindowStartupLocation>())
{
if (!(location == WindowStartupLocation.CenterOwner && mode == ShowWindowMode.NonOwned))
{
data.Add(size, mode, location, true);
data.Add(size, mode, location, false);
}
}
}
}
return data;
}
public static TheoryData<Size?, ShowWindowMode, WindowState, bool> WindowStateData()
{
var sizes = new Size?[] { null, new Size(400, 300) };
var data = new TheoryData<Size?, ShowWindowMode, WindowState, bool>();
foreach (var size in sizes)
{
foreach (var mode in Enum.GetValues<ShowWindowMode>())
{
foreach (var state in Enum.GetValues<WindowState>())
{
// Not sure how to handle testing minimized windows currently.
if (state == Controls.WindowState.Minimized)
continue;
// Child/Modal windows cannot be fullscreen on macOS.
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) &&
state == Controls.WindowState.FullScreen &&
mode != ShowWindowMode.NonOwned)
continue;
data.Add(size, mode, state, true);
data.Add(size, mode, state, false);
}
}
}
return data;
}
private static void AssertCloseEnough(PixelPoint expected, PixelPoint actual)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// On win32, accurate frame information cannot be obtained until a window is shown but
// WindowStartupLocation needs to be calculated before the window is shown, meaning that
// the position of a centered window can be off by a bit. From initial testing, looks
// like this shouldn't be more than 10 pixels.
if (Math.Abs(expected.X - actual.X) > 10)
throw EqualException.ForMismatchedValues(expected, actual);
if (Math.Abs(expected.Y - actual.Y) > 10)
throw EqualException.ForMismatchedValues(expected, actual);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (Math.Abs(expected.X - actual.X) > 15)
throw EqualException.ForMismatchedValues(expected, actual);
if (Math.Abs(expected.Y - actual.Y) > 15)
throw EqualException.ForMismatchedValues(expected, actual);
}
else
{
Assert.Equal(expected, actual);
}
}
private IDisposable OpenWindow(
Size? size = null,
ShowWindowMode mode = ShowWindowMode.NonOwned,
WindowStartupLocation location = WindowStartupLocation.Manual,
WindowState state = Controls.WindowState.Normal,
bool canResize = true,
bool extendClientArea = false,
bool canMinimize = true,
bool canMaximize = true)
{
var sizeTextBox = Session.FindElementByAccessibilityId("ShowWindowSize");
var modeComboBox = Session.FindElementByAccessibilityId("ShowWindowMode");
var locationComboBox = Session.FindElementByAccessibilityId("ShowWindowLocation");
var stateComboBox = Session.FindElementByAccessibilityId("ShowWindowState");
var canResizeCheckBox = Session.FindElementByAccessibilityId("ShowWindowCanResize");
var canMinimizeCheckBox = Session.FindElementByAccessibilityId("ShowWindowCanMinimize");
var canMaximizeCheckBox = Session.FindElementByAccessibilityId("ShowWindowCanMaximize");
var showButton = Session.FindElementByAccessibilityId("ShowWindow");
var extendClientAreaCheckBox = Session.FindElementByAccessibilityId("ShowWindowExtendClientAreaToDecorationsHint");
if (size.HasValue)
sizeTextBox.SendKeys($"{size.Value.Width}, {size.Value.Height}");
if (modeComboBox.GetComboBoxValue() != mode.ToString())
{
modeComboBox.Click();
Session.FindElementByName(mode.ToString()).SendClick();
}
if (locationComboBox.GetComboBoxValue() != location.ToString())
{
locationComboBox.Click();
Session.FindElementByName(location.ToString()).SendClick();
}
if (stateComboBox.GetComboBoxValue() != state.ToString())
{
stateComboBox.Click();
Session.FindElementByAccessibilityId($"ShowWindowState{state}").SendClick();
}
if (canResizeCheckBox.GetIsChecked() != canResize)
canResizeCheckBox.Click();
if (canMinimizeCheckBox.GetIsChecked() != canMinimize)
canMinimizeCheckBox.Click();
if (canMaximizeCheckBox.GetIsChecked() != canMaximize)
canMaximizeCheckBox.Click();
if (extendClientAreaCheckBox.GetIsChecked() != extendClientArea)
extendClientAreaCheckBox.Click();
return showButton.OpenWindowWithClick();
}
private WindowInfo GetWindowInfo()
{
PixelRect? ReadOwnerRect()
{
var text = Session.FindElementByAccessibilityId("CurrentOwnerRect").Text;
return !string.IsNullOrWhiteSpace(text) ? PixelRect.Parse(text) : null;
}
var retry = 0;
for (;;)
{
try
{
return new(
Size.Parse(Session.FindElementByAccessibilityId("CurrentClientSize").Text),
Size.Parse(Session.FindElementByAccessibilityId("CurrentFrameSize").Text),
PixelPoint.Parse(Session.FindElementByAccessibilityId("CurrentPosition").Text),
ReadOwnerRect(),
PixelRect.Parse(Session.FindElementByAccessibilityId("CurrentScreenRect").Text),
double.Parse(Session.FindElementByAccessibilityId("CurrentScaling").Text),
Enum.Parse<WindowState>(Session.FindElementByAccessibilityId("CurrentWindowState").Text));
}
catch (OpenQA.Selenium.NoSuchElementException) when (retry++ < 3)
{
// MacOS sometimes seems to need a bit of time to get itself back in order after switching out
// of fullscreen.
Thread.Sleep(1000);
}
}
}
| WindowTests |
csharp | ardalis__Result | tests/Ardalis.Result.UnitTests/ResultMap.cs | {
"start": 177,
"end": 8083
} | public class ____
{
[Fact]
public void ShouldProduceReturnValueFromSuccess()
{
int successValue = 123;
var result = Result<int>.Success(successValue);
string expected = successValue.ToString();
var actual = result.Map(val => val.ToString());
expected.Should().BeEquivalentTo(actual.Value);
}
[Fact]
public void ShouldProduceComplexTypeReturnValueFromSuccessAnonymously()
{
var foo = new Foo("Bar");
var result = Result<Foo>.Success(foo);
var actual = result.Map(foo => new FooDto(foo.Bar));
actual.Value.Bar.Should().Be(foo.Bar);
}
[Fact]
public void ShouldProduceComplexTypeReturnValueFromSuccessWithMethod()
{
var foo = new Foo("Bar");
var result = Result<Foo>.Success(foo);
var actual = result.Map(FooDto.CreateFromFoo);
actual.Value.Bar.Should().Be(foo.Bar);
}
[Fact]
public void ShouldProduceReturnValueFromCreated()
{
int createdValue = 123;
var result = Result<int>.Created(createdValue);
string expected = createdValue.ToString();
var actual = result.Map(val => val.ToString());
expected.Should().BeEquivalentTo(actual.Value);
}
[Fact]
public void ShouldProduceComplexTypeReturnValueFromCreatedAnonymously()
{
var foo = new Foo("Bar");
var result = Result<Foo>.Created(foo);
var actual = result.Map(foo => new FooDto(foo.Bar));
actual.Value.Bar.Should().Be(foo.Bar);
}
[Fact]
public void ShouldProduceComplexTypeReturnValueFromCreatedWithMethod()
{
var foo = new Foo("Bar");
var result = Result<Foo>.Created(foo);
var actual = result.Map(FooDto.CreateFromFoo);
actual.Value.Bar.Should().Be(foo.Bar);
}
[Fact]
public void ShouldProduceNotFound()
{
var result = Result<int>.NotFound();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.NotFound);
}
[Fact]
public void ShouldProduceNotFoundWithError()
{
string expectedMessage = "Some integer not found";
var result = Result<int>.NotFound(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.NotFound);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProduceUnauthorized()
{
var result = Result<int>.Unauthorized();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Unauthorized);
}
[Fact]
public void ShouldProduceForbidden()
{
var result = Result<int>.Forbidden();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Forbidden);
}
[Fact]
public void ShouldProduceInvalidWithValidationErrors()
{
var validationErrors = new List<ValidationError>
{
new ValidationError
{
ErrorMessage = "Validation Error 1"
},
new ValidationError
{
ErrorMessage = "Validation Error 2"
}
};
var result = Result<int>.Invalid(validationErrors);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Invalid);
actual.ValidationErrors.Should().BeEquivalentTo(validationErrors);
}
[Fact]
public void ShouldProduceInvalidWithoutValidationErrors()
{
var validationErrors = new List<ValidationError>();
var result = Result<int>.Invalid(validationErrors);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Invalid);
actual.ValidationErrors.Should().BeEquivalentTo(validationErrors);
}
[Fact]
public void ShouldProduceErrorResultWithErrors()
{
var errorList = new ErrorList(["Error 1", "Error 2"], default);
var result = Result<int>.Error(errorList);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Error);
actual.Errors.Should().BeEquivalentTo(errorList.ErrorMessages);
}
[Fact]
public void ShouldProduceErrorResultWithNoErrors()
{
var result = Result<int>.Error();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Error);
actual.Errors.Should().BeEmpty();
actual.CorrelationId.Should().BeEmpty();
}
[Fact]
public void ShouldProduceConflict()
{
var result = Result<int>.Conflict();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Conflict);
}
[Fact]
public void ShouldProduceConflictWithError()
{
string expectedMessage = "Some conflict";
var result = Result<int>.Conflict(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Conflict);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProduceUnavailableWithError()
{
string expectedMessage = "Something unavailable";
var result = Result<int>.Unavailable(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Unavailable);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProduceCriticalErrorWithError()
{
string expectedMessage = "Some critical error";
var result = Result<int>.CriticalError(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.CriticalError);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProduceForbiddenWithError()
{
string expectedMessage = "You are forbidden";
var result = Result<int>.Forbidden(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Forbidden);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProduceUnauthorizedWithError()
{
string expectedMessage = "You are unauthorized";
var result = Result<int>.Unauthorized(expectedMessage);
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.Unauthorized);
actual.Errors.Single().Should().Be(expectedMessage);
}
[Fact]
public void ShouldProductNoContentWithoutAnyContent()
{
var result = Result<int>.NoContent();
var actual = result.Map(val => val.ToString());
actual.Status.Should().Be(ResultStatus.NoContent);
actual.Value.Should().BeNull();
actual.Errors.Should().BeEmpty();
actual.ValidationErrors.Should().BeEmpty();
}
| ResultMap |
csharp | dotnet__tye | src/Microsoft.Tye.Hosting/Infrastructure/IngressHostMatcherPolicy.cs | {
"start": 6164,
"end": 6901
} | struct ____
{
internal static readonly EdgeKey WildcardEdgeKey = new EdgeKey(null, null);
public readonly int? Port;
public readonly string Host;
public EdgeKey(string? host, int? port)
{
Host = host ?? WildcardHost;
Port = port;
HasHostWildcard = Host.StartsWith(WildcardPrefix, StringComparison.Ordinal);
}
public bool HasHostWildcard { get; }
public bool MatchesHost => !string.Equals(Host, WildcardHost, StringComparison.Ordinal);
public bool MatchesPort => Port != null;
public bool MatchesAll => !MatchesHost && !MatchesPort;
}
}
}
| EdgeKey |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs | {
"start": 8850,
"end": 9433
} | sealed class ____ : IEqualityComparer<Vector3Int>
{
public static readonly Vector3IntEqualityComparer Default = new Vector3IntEqualityComparer();
public bool Equals(Vector3Int self, Vector3Int vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z);
}
public int GetHashCode(Vector3Int obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2;
}
}
| Vector3IntEqualityComparer |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/PersistentSubscription/PersistentSubscriptionMessageParkerTests.cs | {
"start": 10454,
"end": 11897
} | public class ____<TLogFormat, TStreamId> : TestFixtureWithExistingEvents<TLogFormat, TStreamId> {
private PersistentSubscriptionMessageParker _messageParker;
private string _streamId = Guid.NewGuid().ToString();
private TaskCompletionSource<bool> _parked;
private TaskCompletionSource<bool> _done = new TaskCompletionSource<bool>();
protected override void Given() {
base.Given();
AllWritesSucceed();
_parked = new TaskCompletionSource<bool>();
_messageParker = new PersistentSubscriptionMessageParker(_streamId, _ioDispatcher);
_messageParker.BeginParkMessage(CreateResolvedEvent(0, 0), "testing", ParkReason.MaxRetries, (_, __) => {
_messageParker.BeginParkMessage(CreateResolvedEvent(1, 100), "testing", ParkReason.MaxRetries, (_, __) => {
_parked.SetResult(true);
});
});
}
[Test]
public async Task should_have_no_parked_messages() {
await _parked.Task;
_messageParker.BeginMarkParkedMessagesReprocessed(2, null, true, () => {
Assert.Zero(_messageParker.ParkedMessageCount);
Assert.AreEqual(0, _messageParker.ParkedDueToClientNak);
Assert.AreEqual(2, _messageParker.ParkedDueToMaxRetries);
Assert.Null(_messageParker.GetOldestParkedMessage);
_done.TrySetResult(true);
});
await _done.Task.WithTimeout();
}
}
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
| given_messages_are_parked_and_then_replayed |
csharp | cake-build__cake | src/Cake.Common.Tests/Fixtures/Tools/DotNetCore/Execute/DotNetCoreExecutorFixture.cs | {
"start": 330,
"end": 754
} | internal sealed class ____ : DotNetFixture<DotNetExecuteSettings>
{
public FilePath AssemblyPath { get; set; }
public ProcessArgumentBuilder Arguments { get; set; }
protected override void RunTool()
{
var tool = new DotNetExecutor(FileSystem, Environment, ProcessRunner, Tools);
tool.Execute(AssemblyPath, Arguments, Settings);
}
}
} | DotNetExecutorFixture |
csharp | dotnet__efcore | test/EFCore.Tests/Extensions/TypeExtensionsTest.cs | {
"start": 24280,
"end": 28511
} | class
____ void Can_pretty_print_CLR_name(Type type, string expected)
=> Assert.Equal(expected, type.ShortDisplayName());
[ConditionalTheory, InlineData(typeof(bool), "bool"), InlineData(typeof(byte), "byte"), InlineData(typeof(char), "char"),
InlineData(typeof(decimal), "decimal"), InlineData(typeof(double), "double"), InlineData(typeof(float), "float"),
InlineData(typeof(int), "int"), InlineData(typeof(long), "long"), InlineData(typeof(object), "object"),
InlineData(typeof(sbyte), "sbyte"), InlineData(typeof(short), "short"), InlineData(typeof(string), "string"),
InlineData(typeof(uint), "uint"), InlineData(typeof(ulong), "ulong"), InlineData(typeof(ushort), "ushort"),
InlineData(typeof(void), "void")]
public void Returns_common_name_for_built_in_types(Type type, string expected)
=> Assert.Equal(expected, type.DisplayName());
[ConditionalTheory, InlineData(typeof(int[]), true, "int[]"), InlineData(typeof(string[][]), true, "string[][]"),
InlineData(typeof(int[,]), true, "int[,]"), InlineData(typeof(bool[,,,]), true, "bool[,,,]"),
InlineData(typeof(A[,][,,]), true, "Microsoft.EntityFrameworkCore.TypeExtensionsTest+A[,][,,]"),
InlineData(typeof(List<int[,][,,]>), true, "System.Collections.Generic.List<int[,][,,]>"),
InlineData(typeof(List<int[,,][,]>[,][,,]), false, "List<int[,,][,]>[,][,,]")]
public void Can_pretty_print_array_name(Type type, bool fullName, string expected)
=> Assert.Equal(expected, type.DisplayName(fullName));
public static TheoryData OpenGenericsTestData { get; } = CreateOpenGenericsTestData();
public static TheoryData CreateOpenGenericsTestData()
{
var openDictionaryType = typeof(Dictionary<,>);
var genArgsDictionary = openDictionaryType.GetGenericArguments();
genArgsDictionary[0] = typeof(B<>);
var closedDictionaryType = openDictionaryType.MakeGenericType(genArgsDictionary);
var openLevelType = typeof(Level1<>.Level2<>.Level3<>);
var genArgsLevel = openLevelType.GetGenericArguments();
genArgsLevel[1] = typeof(string);
var closedLevelType = openLevelType.MakeGenericType(genArgsLevel);
var openInnerType = typeof(OuterGeneric<>.InnerNonGeneric.InnerGeneric<,>.InnerGenericLeafNode<>);
var genArgsInnerType = openInnerType.GetGenericArguments();
genArgsInnerType[3] = typeof(bool);
var closedInnerType = openInnerType.MakeGenericType(genArgsInnerType);
return new TheoryData<Type, bool, string>
{
{ typeof(List<>), false, "List<>" },
{ typeof(Dictionary<,>), false, "Dictionary<,>" },
{ typeof(List<>), true, "System.Collections.Generic.List<>" },
{ typeof(Dictionary<,>), true, "System.Collections.Generic.Dictionary<,>" },
{ typeof(Level1<>.Level2<>.Level3<>), true, "Microsoft.EntityFrameworkCore.TypeExtensionsTest+Level1<>+Level2<>+Level3<>" },
{ typeof(PartiallyClosedGeneric<>).BaseType, true, "Microsoft.EntityFrameworkCore.TypeExtensionsTest+C<, int>" },
{
typeof(OuterGeneric<>.InnerNonGeneric.InnerGeneric<,>.InnerGenericLeafNode<>), true,
"Microsoft.EntityFrameworkCore.TypeExtensionsTest+OuterGeneric<>+InnerNonGeneric+InnerGeneric<,>+InnerGenericLeafNode<>"
},
{ closedDictionaryType, true, "System.Collections.Generic.Dictionary<Microsoft.EntityFrameworkCore.TypeExtensionsTest+B<>,>" },
{ closedLevelType, true, "Microsoft.EntityFrameworkCore.TypeExtensionsTest+Level1<>+Level2<string>+Level3<>" },
{
closedInnerType, true,
"Microsoft.EntityFrameworkCore.TypeExtensionsTest+OuterGeneric<>+InnerNonGeneric+InnerGeneric<,>+InnerGenericLeafNode<bool>"
}
};
}
[ConditionalFact]
public void Can_pretty_print_open_generics()
{
foreach (var testData in OpenGenericsTestData)
{
var type = (Type)testData[0];
var fullName = (bool)testData[1];
var expected = (string)testData[2];
Assert.Equal(expected, type.DisplayName(fullName));
}
}
| public |
csharp | MassTransit__MassTransit | src/Scheduling/MassTransit.HangfireIntegration/Configuration/Configuration/ScheduleMessageConsumerDefinition.cs | {
"start": 97,
"end": 1098
} | public class ____ :
ConsumerDefinition<ScheduleMessageConsumer>
{
readonly HangfireEndpointDefinition _endpointDefinition;
public ScheduleMessageConsumerDefinition(HangfireEndpointDefinition endpointDefinition)
{
_endpointDefinition = endpointDefinition;
EndpointDefinition = endpointDefinition;
}
protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator,
IConsumerConfigurator<ScheduleMessageConsumer> consumerConfigurator, IRegistrationContext context)
{
endpointConfigurator.UseMessageRetry(r => r.Interval(5, 250));
consumerConfigurator.Message<ScheduleMessage>(m => m.UsePartitioner(_endpointDefinition.Partition, p => p.Message.CorrelationId));
consumerConfigurator.Message<CancelScheduledMessage>(m => m.UsePartitioner(_endpointDefinition.Partition, p => p.Message.TokenId));
}
}
}
| ScheduleMessageConsumerDefinition |
csharp | icsharpcode__AvalonEdit | ICSharpCode.AvalonEdit/Rendering/LayerPosition.cs | {
"start": 2693,
"end": 3646
} | sealed class ____ : IComparable<LayerPosition>
{
internal static readonly DependencyProperty LayerPositionProperty =
DependencyProperty.RegisterAttached("LayerPosition", typeof(LayerPosition), typeof(LayerPosition));
public static void SetLayerPosition(UIElement layer, LayerPosition value)
{
layer.SetValue(LayerPositionProperty, value);
}
public static LayerPosition GetLayerPosition(UIElement layer)
{
return (LayerPosition)layer.GetValue(LayerPositionProperty);
}
internal readonly KnownLayer KnownLayer;
internal readonly LayerInsertionPosition Position;
public LayerPosition(KnownLayer knownLayer, LayerInsertionPosition position)
{
this.KnownLayer = knownLayer;
this.Position = position;
}
public int CompareTo(LayerPosition other)
{
int r = this.KnownLayer.CompareTo(other.KnownLayer);
if (r != 0)
return r;
else
return this.Position.CompareTo(other.Position);
}
}
}
| LayerPosition |
csharp | serilog__serilog | src/Serilog/Core/IScalarConversionPolicy.cs | {
"start": 174,
"end": 620
} | interface ____
{
/// <summary>
/// If supported, convert the provided value into an immutable scalar.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="result">The converted value, or null.</param>
/// <returns>True if the value could be converted under this policy.</returns>
bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result);
}
| IScalarConversionPolicy |
csharp | neuecc__MessagePack-CSharp | tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs | {
"start": 1694,
"end": 1977
} | public enum ____
{
D, E
}
}
""";
await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource);
}
[Fact]
public async Task GenericType_CollidingTypeNames()
{
string testSource = """
using MessagePack;
[MessagePackObject]
| MyEnum |
csharp | protobuf-net__protobuf-net | src/Examples/Issues/SO7078615.cs | {
"start": 218,
"end": 530
} | interface ____ a contract
// since protobuf-net *by default* doesn't know about type metadata, need to use some clue
[ProtoInclude(1, typeof(DogBarkedEvent))]
// other concrete messages here; note these can also be defined at runtime - nothing *needs*
// to use attributes
| as |
csharp | dotnetcore__Util | src/Util.Microservices.Polly/IRetryPolicyHandler.cs | {
"start": 73,
"end": 537
} | public interface ____ {
/// <summary>
/// 指定触发重试的结果处理条件
/// </summary>
/// <typeparam name="TResult">结果类型</typeparam>
/// <param name="action">触发重试的结果处理条件</param>
IRetryPolicy<TResult> HandleResult<TResult>( Func<TResult, bool> action );
/// <summary>
/// 指定触发重试的异常
/// </summary>
/// <typeparam name="TException">异常类型</typeparam>
IRetryPolicy HandleException<TException>() where TException : Exception;
} | IRetryPolicyHandler |
csharp | nunit__nunit | src/NUnitFramework/framework/Constraints/PropertyConstraintResult.cs | {
"start": 273,
"end": 1482
} | internal sealed class ____ : ConstraintResult
{
private readonly ConstraintResult _baseResult;
#region Constructors
/// <summary>
/// Constructs a <see cref="PropertyConstraintResult"/> for a particular <see cref="PropertyConstraint"/>.
/// </summary>
/// <param name="constraint">The Constraint to which this result applies.</param>
/// <param name="baseResult">The base result with actual value to which the Constraint was applied.</param>
public PropertyConstraintResult(IConstraint constraint, ConstraintResult baseResult) : base(constraint, baseResult.ActualValue, baseResult.Status)
{
_baseResult = baseResult;
}
#endregion
#region Write Methods
/// <summary>
/// Write the additional failure message for a failing constraint to a
/// MessageWriter.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public override void WriteAdditionalLinesTo(MessageWriter writer)
{
_baseResult.WriteAdditionalLinesTo(writer);
}
#endregion
}
}
| PropertyConstraintResult |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/Issues/1113.cs | {
"start": 23129,
"end": 25192
} | class ____
{
public int Level { get; set; }
public TableRefTree Parent { get; set; }
public TableInfo TableInfo { get; set; }
public TableRef TableRef { get; set; }
public List<TableRefTree> Subs { get; set; }
public static TableRefTree GetTableRefTree<T1>(ISelect<T1> select, int maxLevel, string[] properties = null)
{
var orm = select.GetType().GetField("_orm").GetValue(select) as IFreeSql;
var tableInfo = orm.CodeFirst.GetTableByEntity(typeof(T1));
var tree = new TableRefTree()
{
Level = 1,
TableInfo = tableInfo,
};
tree.Subs = GetTableRefTree(orm, tree, maxLevel, properties).ToList();
return tree;
}
public static IEnumerable<TableRefTree> GetTableRefTree(IFreeSql orm, TableRefTree tree, int maxLevel, string[] properties = null)
{
if (tree.Level > maxLevel) yield break;
var tableRefs = tree.TableInfo.Properties.Where(property => properties == null || string.Equals(properties[tree.Level - 1], property.Key, StringComparison.OrdinalIgnoreCase)).Select(a => tree.TableInfo.GetTableRef(a.Key, false)).Where(a => a != null).ToList();
foreach (var tableRef in tableRefs)
{
var tableInfo = orm.CodeFirst.GetTableByEntity(tableRef.RefEntityType);
var sub = new TableRefTree()
{
Level = tree.Level + 1,
TableInfo = tableInfo,
TableRef = tableRef,
Parent = tree,
};
// 排除重复类型
if (sub.CheckRepeat()) continue;
sub.Subs = GetTableRefTree(orm, sub, maxLevel, properties).ToList();
yield return sub;
}
}
}
}
}
| TableRefTree |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/IdGenerators/AscendingGuidGeneratorTests.cs | {
"start": 758,
"end": 3533
} | public class ____
{
private AscendingGuidGenerator _generator = new AscendingGuidGenerator();
[Fact]
public void TestIsEmpty()
{
Assert.True(_generator.IsEmpty(null));
Assert.True(_generator.IsEmpty(Guid.Empty));
var guid = _generator.GenerateId(null, null);
Assert.False(_generator.IsEmpty(guid));
}
[Fact]
public void TestGuid()
{
var expectedTicks = DateTime.Now.Ticks;
var expectedIncrement = 1000;
var expectedMachineProcessId = new byte[] { 1, 32, 64, 128, 255 };
var guid = (Guid)_generator.GenerateId(expectedTicks, expectedMachineProcessId, expectedIncrement);
var bytes = guid.ToByteArray();
var actualTicks = GetTicks(bytes);
var actualMachineProcessId = GetMachineProcessId(bytes);
var actualIncrement = GetIncrement(bytes);
Assert.Equal(expectedTicks, actualTicks);
Assert.True(expectedMachineProcessId.SequenceEqual(actualMachineProcessId));
Assert.Equal(expectedIncrement, actualIncrement);
}
[Fact]
public void TestGuidWithSpecifiedTicks()
{
var expectedTicks = 0x8000L;
var expectedIncrement = 32;
var expectedMachineProcessId = new byte[] { 1, 32, 64, 128, 255 };
var guid = (Guid)_generator.GenerateId(expectedTicks, expectedMachineProcessId, expectedIncrement);
var bytes = guid.ToByteArray();
var actualTicks = GetTicks(bytes);
var actualMachineProcessId = GetMachineProcessId(bytes);
var actualIncrement = GetIncrement(bytes);
Assert.Equal(expectedTicks, actualTicks);
Assert.True(expectedMachineProcessId.SequenceEqual(actualMachineProcessId));
Assert.Equal(expectedIncrement, actualIncrement);
}
private long GetTicks(byte[] bytes)
{
var a = (ulong)BinaryPrimitives.ReadUInt32LittleEndian(new ReadOnlySpan<byte>(bytes, 0, 4));
var b = (ulong)BinaryPrimitives.ReadUInt16LittleEndian(new ReadOnlySpan<byte>(bytes, 4, 2));
var c = (ulong)BinaryPrimitives.ReadUInt16LittleEndian(new ReadOnlySpan<byte>(bytes, 6, 2));
return (long)((a << 32) | (b << 16) | c);
}
private byte[] GetMachineProcessId(byte[] bytes)
{
var result = new byte[5];
Array.Copy(bytes, 8, result, 0, 5);
return result;
}
private int GetIncrement(byte[] bytes)
{
var increment = (bytes[13] << 16) + (bytes[14] << 8) + bytes[15];
return increment;
}
}
}
| AscendingGuidGeneratorTests |
csharp | abpframework__abp | framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs | {
"start": 1588,
"end": 1722
} | public class ____
{
public Task<string> GetResponseAsync()
{
return Task.FromResult("hello api!");
}
}
| DataBaseService |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/test/WebApplicationBuilder/DisallowConfigureWebHostBuilderConfigureTest.cs | {
"start": 4270,
"end": 5798
} | public class ____ { }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
var diagnostic = Assert.Single(diagnostics);
Assert.Same(DiagnosticDescriptors.DoNotUseConfigureWithConfigureWebHostBuilder, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("Configure cannot be used with WebApplicationBuilder.WebHost", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
[Fact]
public async Task HostBuilder_WebHostBuilder_Configure_DoesNotProduceDiagnostic()
{
// Arrange
var source = @"
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
var builder = Host.CreateDefaultBuilder();
builder.ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.Configure(configure => { }));
";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task WebHostBuilder_Configure_DoesNotProduceDiagnostic()
{
// Arrange
var source = @"
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
var builder = WebHost.CreateDefaultBuilder();
builder.Configure(configure => { });
builder.Configure((context, webHostBuilder) => { });
";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
}
| Startup |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Min.cs | {
"start": 2960,
"end": 4255
} | private sealed class ____ : _
{
private TSource? _lastValue;
public Null(IComparer<TSource> comparer, IObserver<TSource> observer)
: base(comparer, observer)
{
}
public override void OnNext(TSource value)
{
if (value != null)
{
if (_lastValue == null)
{
_lastValue = value;
}
else
{
int comparison;
try
{
comparison = _comparer.Compare(value, _lastValue);
}
catch (Exception ex)
{
ForwardOnError(ex);
return;
}
if (comparison < 0)
{
_lastValue = value;
}
}
}
}
public override void OnCompleted()
{
ForwardOnNext(_lastValue!);
ForwardOnCompleted();
}
}
}
| Null |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 23153,
"end": 23370
} | public class ____
{
public int Id { get; set; }
public RelatedEntity107 ParentEntity { get; set; }
public IEnumerable<RelatedEntity109> ChildEntities { get; set; }
}
| RelatedEntity108 |
csharp | microsoft__garnet | libs/server/Storage/Session/MainStore/HyperLogLogOps.cs | {
"start": 414,
"end": 10746
} | partial class ____ : IDisposable
{
/// <summary>
/// Adds all the element arguments to the HyperLogLog data structure stored at the variable name specified as key.
/// </summary>
public unsafe GarnetStatus HyperLogLogAdd<TContext>(ArgSlice key, string[] elements, out bool updated, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, RawStringInput, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
updated = false;
parseState.Initialize(1);
var input = new RawStringInput(RespCommand.PFADD, ref parseState);
var output = stackalloc byte[1];
byte pfaddUpdated = 0;
foreach (var element in elements)
{
var elementSlice = scratchBufferBuilder.CreateArgSlice(element);
parseState.SetArgument(0, elementSlice);
var o = new SpanByteAndMemory(output, 1);
var sbKey = key.SpanByte;
RMW_MainStore(ref sbKey, ref input, ref o, ref context);
scratchBufferBuilder.RewindScratchBuffer(ref elementSlice);
//Invalid HLL Type
if (*output == (byte)0xFF)
{
pfaddUpdated = 0;
break;
}
pfaddUpdated |= *output;
}
updated = pfaddUpdated > 0;
return GarnetStatus.OK;
}
/// <summary>
/// Adds one element to the HyperLogLog data structure stored at the variable name specified.
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="key"></param>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="context"></param>
/// <returns></returns>
public GarnetStatus HyperLogLogAdd<TContext>(ref SpanByte key, ref RawStringInput input, ref SpanByteAndMemory output, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, RawStringInput, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
=> RMW_MainStore(ref key, ref input, ref output, ref context);
public unsafe GarnetStatus HyperLogLogLength<TContext>(Span<ArgSlice> keys, out long count, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, RawStringInput, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
parseState.Initialize(keys.Length);
for (var i = 0; i < keys.Length; i++)
{
parseState.SetArgument(i, keys[i]);
}
var input = new RawStringInput(RespCommand.PFCOUNT, ref parseState);
return HyperLogLogLength(ref input, out count, out _, ref context);
}
/// <summary>
/// Returns the approximated cardinality computed by the HyperLogLog data structure stored at the specified key,
/// or 0 if the key does not exist.
/// </summary>
/// <param name="input"></param>
/// <param name="count"></param>
/// <param name="error"></param>
/// <param name="context"></param>
/// <returns></returns>
public unsafe GarnetStatus HyperLogLogLength<TContext>(ref RawStringInput input, out long count, out bool error, ref TContext context)
where TContext : ITsavoriteContext<SpanByte, SpanByte, RawStringInput, SpanByteAndMemory, long, MainSessionFunctions, MainStoreFunctions, MainStoreAllocator>
{
error = false;
count = default;
if (input.parseState.Count == 0)
return GarnetStatus.OK;
var createTransaction = false;
if (txnManager.state != TxnState.Running)
{
Debug.Assert(txnManager.state == TxnState.None);
createTransaction = true;
var dstKey = input.parseState.GetArgSliceByRef(0);
txnManager.SaveKeyEntryToLock(dstKey, false, LockType.Exclusive);
for (var i = 1; i < input.parseState.Count; i++)
{
var currSrcKey = input.parseState.GetArgSliceByRef(i);
txnManager.SaveKeyEntryToLock(currSrcKey, false, LockType.Shared);
}
txnManager.Run(true);
}
var currLockableContext = txnManager.LockableContext;
try
{
sectorAlignedMemoryHll1 ??= new SectorAlignedMemory(hllBufferSize + sectorAlignedMemoryPoolAlignment,
sectorAlignedMemoryPoolAlignment);
sectorAlignedMemoryHll2 ??= new SectorAlignedMemory(hllBufferSize + sectorAlignedMemoryPoolAlignment,
sectorAlignedMemoryPoolAlignment);
var srcReadBuffer = sectorAlignedMemoryHll1.GetValidPointer();
var dstReadBuffer = sectorAlignedMemoryHll2.GetValidPointer();
var dstMergeBuffer = new SpanByteAndMemory(srcReadBuffer, hllBufferSize);
var srcMergeBuffer = new SpanByteAndMemory(dstReadBuffer, hllBufferSize);
var isFirst = false;
for (var i = 0; i < input.parseState.Count; i++)
{
var currInput = new RawStringInput(RespCommand.PFCOUNT);
var srcKey = input.parseState.GetArgSliceByRef(i).SpanByte;
var status = GET(ref srcKey, ref currInput, ref srcMergeBuffer, ref currLockableContext);
// Handle case merging source key does not exist
if (status == GarnetStatus.NOTFOUND)
continue;
// Invalid Type
if (*(long*)srcReadBuffer == -1)
{
error = true;
break;
}
var sbSrcHLL = srcMergeBuffer.SpanByte;
var sbDstHLL = dstMergeBuffer.SpanByte;
var srcHLL = sbSrcHLL.ToPointer();
var dstHLL = sbDstHLL.ToPointer();
if (!isFirst)
{
isFirst = true;
if (i == input.parseState.Count - 1)
count = HyperLogLog.DefaultHLL.Count(srcMergeBuffer.SpanByte.ToPointer());
else
Buffer.MemoryCopy(srcHLL, dstHLL, sbSrcHLL.Length, sbSrcHLL.Length);
continue;
}
HyperLogLog.DefaultHLL.TryMerge(srcHLL, dstHLL, sbDstHLL.Length);
if (i == input.parseState.Count - 1)
{
count = HyperLogLog.DefaultHLL.Count(dstHLL);
}
}
}
finally
{
if (createTransaction)
txnManager.Commit(true);
}
return GarnetStatus.OK;
}
/// <summary>
/// Merge multiple HyperLogLog values into a unique value that will approximate the cardinality
/// of the union of the observed Sets of the source HyperLogLog structures.
/// </summary>
/// <param name="input"></param>
/// <param name="error"></param>
/// <returns></returns>
public unsafe GarnetStatus HyperLogLogMerge(ref RawStringInput input, out bool error)
{
error = false;
if (input.parseState.Count == 0)
return GarnetStatus.OK;
var createTransaction = false;
if (txnManager.state != TxnState.Running)
{
Debug.Assert(txnManager.state == TxnState.None);
createTransaction = true;
var dstKey = input.parseState.GetArgSliceByRef(0);
txnManager.SaveKeyEntryToLock(dstKey, false, LockType.Exclusive);
for (var i = 1; i < input.parseState.Count; i++)
{
var currSrcKey = input.parseState.GetArgSliceByRef(i);
txnManager.SaveKeyEntryToLock(currSrcKey, false, LockType.Shared);
}
txnManager.Run(true);
}
var currLockableContext = txnManager.LockableContext;
try
{
sectorAlignedMemoryHll1 ??= new SectorAlignedMemory(hllBufferSize + sectorAlignedMemoryPoolAlignment, sectorAlignedMemoryPoolAlignment);
var readBuffer = sectorAlignedMemoryHll1.GetValidPointer();
var dstKey = input.parseState.GetArgSliceByRef(0).SpanByte;
for (var i = 1; i < input.parseState.Count; i++)
{
#region readSrcHLL
var currInput = new RawStringInput(RespCommand.PFMERGE);
var mergeBuffer = new SpanByteAndMemory(readBuffer, hllBufferSize);
var srcKey = input.parseState.GetArgSliceByRef(i).SpanByte;
var status = GET(ref srcKey, ref currInput, ref mergeBuffer, ref currLockableContext);
// Handle case merging source key does not exist
if (status == GarnetStatus.NOTFOUND)
continue;
// Invalid Type
if (*(long*)readBuffer == -1)
{
error = true;
break;
}
#endregion
#region mergeToDst
var mergeSlice = new ArgSlice(ref mergeBuffer.SpanByte);
parseState.InitializeWithArgument(mergeSlice);
currInput.parseState = parseState;
SET_Conditional(ref dstKey, ref currInput, ref mergeBuffer, ref currLockableContext);
#endregion
}
}
finally
{
if (createTransaction)
txnManager.Commit(true);
}
return GarnetStatus.OK;
}
}
} | StorageSession |
csharp | dotnet__orleans | test/Extensions/Consul.Tests/ConsulClusteringOptionsTests.cs | {
"start": 2658,
"end": 6042
} | private class ____ : IConsulClient
{
[Obsolete]
public IACLEndpoint ACL => throw new NotImplementedException();
public IPolicyEndpoint Policy => throw new NotImplementedException();
public IRoleEndpoint Role => throw new NotImplementedException();
public ITokenEndpoint Token => throw new NotImplementedException();
public IAgentEndpoint Agent => throw new NotImplementedException();
public ICatalogEndpoint Catalog => throw new NotImplementedException();
public IEventEndpoint Event => throw new NotImplementedException();
public IHealthEndpoint Health => throw new NotImplementedException();
public IKVEndpoint KV => throw new NotImplementedException();
public IRawEndpoint Raw => throw new NotImplementedException();
public ISessionEndpoint Session => throw new NotImplementedException();
public IStatusEndpoint Status => throw new NotImplementedException();
public IOperatorEndpoint Operator => throw new NotImplementedException();
public IPreparedQueryEndpoint PreparedQuery => throw new NotImplementedException();
public ICoordinateEndpoint Coordinate => throw new NotImplementedException();
public ISnapshotEndpoint Snapshot => throw new NotImplementedException();
public Task<IDistributedLock> AcquireLock(LockOptions opts, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IDistributedLock> AcquireLock(string key, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IDistributedSemaphore> AcquireSemaphore(SemaphoreOptions opts, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IDistributedSemaphore> AcquireSemaphore(string prefix, int limit, CancellationToken ct = default) => throw new NotImplementedException();
public IDistributedLock CreateLock(LockOptions opts) => throw new NotImplementedException();
public IDistributedLock CreateLock(string key) => throw new NotImplementedException();
public void Dispose() => throw new NotImplementedException();
public Task ExecuteInSemaphore(SemaphoreOptions opts, Action a, CancellationToken ct = default) => throw new NotImplementedException();
public Task ExecuteInSemaphore(string prefix, int limit, Action a, CancellationToken ct = default) => throw new NotImplementedException();
public Task ExecuteLocked(LockOptions opts, Action action, CancellationToken ct = default) => throw new NotImplementedException();
public Task ExecuteLocked(LockOptions opts, CancellationToken ct, Action action) => throw new NotImplementedException();
public Task ExecuteLocked(string key, Action action, CancellationToken ct = default) => throw new NotImplementedException();
public Task ExecuteLocked(string key, CancellationToken ct, Action action) => throw new NotImplementedException();
public IDistributedSemaphore Semaphore(SemaphoreOptions opts) => throw new NotImplementedException();
public IDistributedSemaphore Semaphore(string prefix, int limit) => throw new NotImplementedException();
}
}
}
| FakeConsul |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Activation/PhoneCallActivatedEventArgs.cs | {
"start": 310,
"end": 4520
} | public partial class ____ : global::Windows.ApplicationModel.Activation.IPhoneCallActivatedEventArgs, global::Windows.ApplicationModel.Activation.IActivatedEventArgs, global::Windows.ApplicationModel.Activation.IActivatedEventArgsWithUser
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal PhoneCallActivatedEventArgs()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.ApplicationModel.Activation.ActivationKind Kind
{
get
{
throw new global::System.NotImplementedException("The member ActivationKind PhoneCallActivatedEventArgs.Kind is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ActivationKind%20PhoneCallActivatedEventArgs.Kind");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.ApplicationModel.Activation.ApplicationExecutionState PreviousExecutionState
{
get
{
throw new global::System.NotImplementedException("The member ApplicationExecutionState PhoneCallActivatedEventArgs.PreviousExecutionState is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ApplicationExecutionState%20PhoneCallActivatedEventArgs.PreviousExecutionState");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.ApplicationModel.Activation.SplashScreen SplashScreen
{
get
{
throw new global::System.NotImplementedException("The member SplashScreen PhoneCallActivatedEventArgs.SplashScreen is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SplashScreen%20PhoneCallActivatedEventArgs.SplashScreen");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.System.User User
{
get
{
throw new global::System.NotImplementedException("The member User PhoneCallActivatedEventArgs.User is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=User%20PhoneCallActivatedEventArgs.User");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Guid LineId
{
get
{
throw new global::System.NotImplementedException("The member Guid PhoneCallActivatedEventArgs.LineId is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Guid%20PhoneCallActivatedEventArgs.LineId");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.Activation.PhoneCallActivatedEventArgs.LineId.get
// Forced skipping of method Windows.ApplicationModel.Activation.PhoneCallActivatedEventArgs.Kind.get
// Forced skipping of method Windows.ApplicationModel.Activation.PhoneCallActivatedEventArgs.PreviousExecutionState.get
// Forced skipping of method Windows.ApplicationModel.Activation.PhoneCallActivatedEventArgs.SplashScreen.get
// Forced skipping of method Windows.ApplicationModel.Activation.PhoneCallActivatedEventArgs.User.get
// Processing: Windows.ApplicationModel.Activation.IPhoneCallActivatedEventArgs
// Processing: Windows.ApplicationModel.Activation.IActivatedEventArgs
// Processing: Windows.ApplicationModel.Activation.IActivatedEventArgsWithUser
}
}
| PhoneCallActivatedEventArgs |
csharp | AutoMapper__AutoMapper | src/AutoMapper/Configuration/Annotations/ValueConverterAttribute.cs | {
"start": 469,
"end": 1210
} | public sealed class ____(Type type) : Attribute, IMemberConfigurationProvider
{
/// <summary>
/// <see cref="IValueConverter{TSourceMember,TDestinationMember}" /> type
/// </summary>
public Type Type { get; } = type;
public void ApplyConfiguration(IMemberConfigurationExpression memberConfigurationExpression)
{
var sourceMemberAttribute = memberConfigurationExpression.DestinationMember.GetCustomAttribute<SourceMemberAttribute>();
if (sourceMemberAttribute != null)
{
memberConfigurationExpression.ConvertUsing(Type, sourceMemberAttribute.Name);
}
else
{
memberConfigurationExpression.ConvertUsing(Type);
}
}
} | ValueConverterAttribute |
csharp | dotnet__BenchmarkDotNet | src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs | {
"start": 4180,
"end": 18188
} | class ____ method)")]
public IEnumerable<string> AttributeNames { get; set; }
[Option("join", Required = false, Default = false, HelpText = "Prints single table with results for all benchmarks")]
public bool Join { get; set; }
[Option("keepFiles", Required = false, Default = false, HelpText = "Determines if all auto-generated files should be kept or removed after running the benchmarks.")]
public bool KeepBenchmarkFiles { get; set; }
[Option("noOverwrite", Required = false, Default = false, HelpText = "Determines if the exported result files should not be overwritten (be default they are overwritten).")]
public bool DontOverwriteResults { get; set; }
[Option("counters", Required = false, HelpText = "Hardware Counters", Separator = '+')]
public IEnumerable<string> HardwareCounters { get; set; }
[Option("cli", Required = false, HelpText = "Path to dotnet cli (optional).")]
public FileInfo CliPath { get; set; }
[Option("packages", Required = false, HelpText = "The directory to restore packages to (optional).")]
public DirectoryInfo RestorePath { get; set; }
[Option("coreRun", Required = false, HelpText = "Path(s) to CoreRun (optional).")]
public IReadOnlyList<FileInfo> CoreRunPaths { get; set; }
[Option("monoPath", Required = false, HelpText = "Optional path to Mono which should be used for running benchmarks.")]
public FileInfo MonoPath { get; set; }
[Option("clrVersion", Required = false, HelpText = "Optional version of private CLR build used as the value of COMPLUS_Version env var.")]
public string ClrVersion { get; set; }
[Option("ilCompilerVersion", Required = false, HelpText = "Optional version of Microsoft.DotNet.ILCompiler which should be used to run with NativeAOT. Example: \"7.0.0-preview.3.22123.2\"")]
public string ILCompilerVersion { get; set; }
[Option("ilcPackages", Required = false, HelpText = @"Optional path to shipping packages produced by local dotnet/runtime build. Example: 'D:\projects\runtime\artifacts\packages\Release\Shipping\'")]
public DirectoryInfo IlcPackages { get; set; }
[Option("launchCount", Required = false, HelpText = "How many times we should launch process with target benchmark. The default is 1.")]
public int? LaunchCount { get; set; }
[Option("warmupCount", Required = false, HelpText = "How many warmup iterations should be performed. If you set it, the minWarmupCount and maxWarmupCount are ignored. By default calculated by the heuristic.")]
public int? WarmupIterationCount { get; set; }
[Option("minWarmupCount", Required = false, HelpText = "Minimum count of warmup iterations that should be performed. The default is 6.")]
public int? MinWarmupIterationCount { get; set; }
[Option("maxWarmupCount", Required = false, HelpText = "Maximum count of warmup iterations that should be performed. The default is 50.")]
public int? MaxWarmupIterationCount { get; set; }
[Option("iterationTime", Required = false, HelpText = "Desired time of execution of an iteration in milliseconds. Used by Pilot stage to estimate the number of invocations per iteration. 500ms by default")]
public int? IterationTimeInMilliseconds { get; set; }
[Option("iterationCount", Required = false, HelpText = "How many target iterations should be performed. By default calculated by the heuristic.")]
public int? IterationCount { get; set; }
[Option("minIterationCount", Required = false, HelpText = "Minimum number of iterations to run. The default is 15.")]
public int? MinIterationCount { get; set; }
[Option("maxIterationCount", Required = false, HelpText = "Maximum number of iterations to run. The default is 100.")]
public int? MaxIterationCount { get; set; }
[Option("invocationCount", Required = false, HelpText = "Invocation count in a single iteration. By default calculated by the heuristic.")]
public long? InvocationCount { get; set; }
[Option("unrollFactor", Required = false, HelpText = "How many times the benchmark method will be invoked per one iteration of a generated loop. 16 by default")]
public int? UnrollFactor { get; set; }
[Option("strategy", Required = false, HelpText = "The RunStrategy that should be used. Throughput/ColdStart/Monitoring.")]
public RunStrategy? RunStrategy { get; set; }
[Option("platform", Required = false, HelpText = "The Platform that should be used. If not specified, the host process platform is used (default). AnyCpu/X86/X64/Arm/Arm64/LoongArch64.")]
public Platform? Platform { get; set; }
[Option("runOncePerIteration", Required = false, Default = false, HelpText = "Run the benchmark exactly once per iteration.")]
public bool RunOncePerIteration { get; set; }
[Option("info", Required = false, Default = false, HelpText = "Print environment information.")]
public bool PrintInformation { get; set; }
[Option("apples", Required = false, Default = false, HelpText = "Runs apples-to-apples comparison for specified Jobs.")]
public bool ApplesToApples { get; set; }
[Option("list", Required = false, Default = ListBenchmarkCaseMode.Disabled, HelpText = "Prints all of the available benchmark names. Flat/Tree")]
public ListBenchmarkCaseMode ListBenchmarkCaseMode { get; set; }
[Option("disasmDepth", Required = false, Default = DefaultDisassemblerRecursiveDepth, HelpText = "Sets the recursive depth for the disassembler.")]
public int DisassemblerRecursiveDepth { get; set; }
[Option("disasmFilter", Required = false, HelpText = "Glob patterns applied to full method signatures by the the disassembler.")]
public IEnumerable<string> DisassemblerFilters { get; set; }
[Option("disasmDiff", Required = false, Default = false, HelpText = "Generates diff reports for the disassembler.")]
public bool DisassemblerDiff { get; set; }
[Option("logBuildOutput", Required = false, HelpText = "Log Build output.")]
public bool LogBuildOutput { get; set; }
[Option("generateBinLog", Required = false, HelpText = "Generate msbuild binlog for builds")]
public bool GenerateMSBuildBinLog { get; set; }
[Option("buildTimeout", Required = false, HelpText = "Build timeout in seconds.")]
public int? TimeOutInSeconds { get; set; }
[Option("wakeLock", Required = false, HelpText = "Prevents the system from entering sleep or turning off the display. None/System/Display.")]
public WakeLockType? WakeLock { get; set; }
[Option("stopOnFirstError", Required = false, Default = false, HelpText = "Stop on first error.")]
public bool StopOnFirstError { get; set; }
[Option("statisticalTest", Required = false, HelpText = "Threshold for Mann–Whitney U Test. Examples: 5%, 10ms, 100ns, 1s")]
public string StatisticalTestThreshold { get; set; }
[Option("disableLogFile", Required = false, HelpText = "Disables the logfile.")]
public bool DisableLogFile { get; set; }
[Option("maxWidth", Required = false, HelpText = "Max parameter column width, the default is 20.")]
public int? MaxParameterColumnWidth { get; set; }
[Option("envVars", Required = false, HelpText = "Colon separated environment variables (key:value)")]
public IEnumerable<string> EnvironmentVariables { get; set; }
[Option("memoryRandomization", Required = false, HelpText = "Specifies whether Engine should allocate some random-sized memory between iterations. It makes [GlobalCleanup] and [GlobalSetup] methods to be executed after every iteration.")]
public bool MemoryRandomization { get; set; }
[Option("wasmEngine", Required = false, HelpText = "Full path to a java script engine used to run the benchmarks, used by Wasm toolchain.")]
public FileInfo WasmJavascriptEngine { get; set; }
[Option("wasmArgs", Required = false, Default = "--expose_wasm", HelpText = "Arguments for the javascript engine used by Wasm toolchain.")]
public string WasmJavaScriptEngineArguments { get; set; }
[Option("customRuntimePack", Required = false, HelpText = "Path to a custom runtime pack. Only used for wasm/MonoAotLLVM currently.")]
public string CustomRuntimePack { get; set; }
[Option("AOTCompilerPath", Required = false, HelpText = "Path to Mono AOT compiler, used for MonoAotLLVM.")]
public FileInfo AOTCompilerPath { get; set; }
[Option("AOTCompilerMode", Required = false, Default = MonoAotCompilerMode.mini, HelpText = "Mono AOT compiler mode, either 'mini' or 'llvm'")]
public MonoAotCompilerMode AOTCompilerMode { get; set; }
[Option("wasmDataDir", Required = false, HelpText = "Wasm data directory")]
public DirectoryInfo WasmDataDirectory { get; set; }
[Option("noForcedGCs", Required = false, HelpText = "Specifying would not forcefully induce any GCs.")]
public bool NoForcedGCs { get; set; }
[Option("noOverheadEvaluation", Required = false, HelpText = "Specifying would not run the evaluation overhead iterations.")]
public bool NoEvaluationOverhead { get; set; }
[Option("resume", Required = false, Default = false, HelpText = "Continue the execution if the last run was stopped.")]
public bool Resume { get; set; }
internal bool UserProvidedFilters => Filters.Any() || AttributeNames.Any() || AllCategories.Any() || AnyCategories.Any();
[Usage(ApplicationAlias = "")]
[PublicAPI]
public static IEnumerable<Example> Examples
{
get
{
var shortName = new UnParserSettings { PreferShortName = true };
var longName = new UnParserSettings { PreferShortName = false };
yield return new Example("Use Job.ShortRun for running the benchmarks", shortName, new CommandLineOptions { BaseJob = "short" });
yield return new Example("Run benchmarks in process", shortName, new CommandLineOptions { RunInProcess = true });
yield return new Example("Run benchmarks for .NET 4.7.2, .NET 8.0 and Mono. .NET 4.7.2 will be baseline because it was first.", longName, new CommandLineOptions { Runtimes = new[] { "net472", "net8.0", "Mono" } });
yield return new Example("Run benchmarks for .NET Core 3.1, .NET 6.0 and .NET 8.0. .NET Core 3.1 will be baseline because it was first.", longName, new CommandLineOptions { Runtimes = new[] { "netcoreapp3.1", "net6.0", "net8.0" } });
yield return new Example("Use MemoryDiagnoser to get GC stats", shortName, new CommandLineOptions { UseMemoryDiagnoser = true });
yield return new Example("Use DisassemblyDiagnoser to get disassembly", shortName, new CommandLineOptions { UseDisassemblyDiagnoser = true });
yield return new Example("Use HardwareCountersDiagnoser to get hardware counter info", longName, new CommandLineOptions { HardwareCounters = new[] { nameof(HardwareCounter.CacheMisses), nameof(HardwareCounter.InstructionRetired) } });
yield return new Example("Run all benchmarks exactly once", shortName, new CommandLineOptions { BaseJob = "Dry", Filters = new[] { Escape("*") } });
yield return new Example("Run all benchmarks from System.Memory namespace", shortName, new CommandLineOptions { Filters = new[] { Escape("System.Memory*") } });
yield return new Example("Run all benchmarks from ClassA and ClassB using type names", shortName, new CommandLineOptions { Filters = new[] { "ClassA", "ClassB" } });
yield return new Example("Run all benchmarks from ClassA and ClassB using patterns", shortName, new CommandLineOptions { Filters = new[] { Escape("*.ClassA.*"), Escape("*.ClassB.*") } });
yield return new Example("Run all benchmarks called `BenchmarkName` and show the results in single summary", longName, new CommandLineOptions { Join = true, Filters = new[] { Escape("*.BenchmarkName") } });
yield return new Example("Run selected benchmarks once per iteration", longName, new CommandLineOptions { RunOncePerIteration = true });
yield return new Example("Run selected benchmarks 100 times per iteration. Perform single warmup iteration and 5 actual workload iterations", longName, new CommandLineOptions { InvocationCount = 100, WarmupIterationCount = 1, IterationCount = 5});
yield return new Example("Run selected benchmarks 250ms per iteration. Perform from 9 to 15 iterations", longName, new CommandLineOptions { IterationTimeInMilliseconds = 250, MinIterationCount = 9, MaxIterationCount = 15});
yield return new Example("Run MannWhitney test with relative ratio of 5% for all benchmarks for .NET 6.0 (base) vs .NET 8.0 (diff). .NET Core 6.0 will be baseline because it was provided as first.", longName,
new CommandLineOptions { Filters = new[] { "*"}, Runtimes = new[] { "net6.0", "net8.0" }, StatisticalTestThreshold = "5%" });
yield return new Example("Run benchmarks using environment variables 'ENV_VAR_KEY_1' with value 'value_1' and 'ENV_VAR_KEY_2' with value 'value_2'", longName,
new CommandLineOptions { EnvironmentVariables = new[] { "ENV_VAR_KEY_1:value_1", "ENV_VAR_KEY_2:value_2" } });
yield return new Example("Hide Mean and Ratio columns (use double quotes for multi-word columns: \"Alloc Ratio\")", shortName, new CommandLineOptions { HiddenColumns = new[] { "Mean", "Ratio" }, });
}
}
private static string Escape(string input) => UserInteractionHelper.EscapeCommandExample(input);
}
}
| or |
csharp | dotnet__maui | src/Core/tests/DeviceTests/Handlers/Button/ButtonHandlerTests.cs | {
"start": 3942,
"end": 4102
} | public class ____ : FocusHandlerTests<ButtonHandler, ButtonStub, VerticalStackLayoutStub>
{
public ButtonFocusTests()
{
}
}
#endif
}
} | ButtonFocusTests |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Bugzilla/Bugzilla44476.cs | {
"start": 116,
"end": 559
} | public class ____ : _IssuesUITest
{
public Bugzilla44476(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "[Android] Unwanted margin at top of details page when nested in a NavigationPage";
[Test]
[Category(UITestCategories.Navigation)]
[Category(UITestCategories.Compatibility)]
public void Issue44476TestUnwantedMargin()
{
App.WaitForElement("This should be visible.");
}
}
} | Bugzilla44476 |
csharp | AutoMapper__AutoMapper | src/UnitTests/IMappingExpression/IncludeMembers.cs | {
"start": 59433,
"end": 59817
} | class ____
{
public string Name { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>().IncludeMembers(s => s.InnerSource);
cfg.CreateMap<InnerSource, Destination>(MemberList.None);
});
[Fact]
public void Validate() => AssertConfigurationIsValid();
}
| Destination |
csharp | bitwarden__server | src/Core/Auth/Repositories/ISsoConfigRepository.cs | {
"start": 118,
"end": 407
} | public interface ____ : IRepository<SsoConfig, long>
{
Task<SsoConfig?> GetByOrganizationIdAsync(Guid organizationId);
Task<SsoConfig?> GetByIdentifierAsync(string identifier);
Task<ICollection<SsoConfig>> GetManyByRevisionNotBeforeDate(DateTime? notBefore);
}
| ISsoConfigRepository |
csharp | open-telemetry__opentelemetry-dotnet | src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/Serializer/ProtobufOtlpLogFieldNumberConstants.cs | {
"start": 372,
"end": 2940
} | internal static class ____
{
// Logs data
internal const int LogsData_Resource_Logs = 1;
// Resource Logs
internal const int ResourceLogs_Resource = 1;
internal const int ResourceLogs_Scope_Logs = 2;
internal const int ResourceLogs_Schema_Url = 3;
// Resource
internal const int Resource_Attributes = 1;
// ScopeLogs
internal const int ScopeLogs_Scope = 1;
internal const int ScopeLogs_Log_Records = 2;
internal const int ScopeLogs_Schema_Url = 3;
// LogRecord
internal const int LogRecord_Time_Unix_Nano = 1;
internal const int LogRecord_Observed_Time_Unix_Nano = 11;
internal const int LogRecord_Severity_Number = 2;
internal const int LogRecord_Severity_Text = 3;
internal const int LogRecord_Body = 5;
internal const int LogRecord_Attributes = 6;
internal const int LogRecord_Dropped_Attributes_Count = 7;
internal const int LogRecord_Flags = 8;
internal const int LogRecord_Trace_Id = 9;
internal const int LogRecord_Span_Id = 10;
internal const int LogRecord_Event_Name = 12;
// SeverityNumber
internal const int Severity_Number_Unspecified = 0;
internal const int Severity_Number_Trace = 1;
internal const int Severity_Number_Trace2 = 2;
internal const int Severity_Number_Trace3 = 3;
internal const int Severity_Number_Trace4 = 4;
internal const int Severity_Number_Debug = 5;
internal const int Severity_Number_Debug2 = 6;
internal const int Severity_Number_Debug3 = 7;
internal const int Severity_Number_Debug4 = 8;
internal const int Severity_Number_Info = 9;
internal const int Severity_Number_Info2 = 10;
internal const int Severity_Number_Info3 = 11;
internal const int Severity_Number_Info4 = 12;
internal const int Severity_Number_Warn = 13;
internal const int Severity_Number_Warn2 = 14;
internal const int Severity_Number_Warn3 = 15;
internal const int Severity_Number_Warn4 = 16;
internal const int Severity_Number_Error = 17;
internal const int Severity_Number_Error2 = 18;
internal const int Severity_Number_Error3 = 19;
internal const int Severity_Number_Error4 = 20;
internal const int Severity_Number_Fatal = 21;
internal const int Severity_Number_Fatal2 = 22;
internal const int Severity_Number_Fatal3 = 23;
internal const int Severity_Number_Fatal4 = 24;
// LogRecordFlags
internal const int LogRecord_Flags_Do_Not_Use = 0;
internal const int LogRecord_Flags_Trace_Flags_Mask = 0x000000FF;
}
| ProtobufOtlpLogFieldNumberConstants |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/NuGet/NuGet.Generated.cs | {
"start": 37968,
"end": 43078
} | public partial class ____ : ToolOptions
{
/// <summary>Path of the package to sign.</summary>
[Argument(Format = "{value}", Position = 1)] public string TargetPath => Get<string>(() => TargetPath);
/// <summary>Specifies the fingerprint to be used to search for the certificate in a local certificate store.</summary>
[Argument(Format = "-CertificateFingerprint {value}")] public string CertificateFingerprint => Get<string>(() => CertificateFingerprint);
/// <summary>Specifies the certificate password, if needed. If a certificate is password protected but no password is provided, the command will prompt for a password at run time, unless the -NonInteractive option is passed.</summary>
[Argument(Format = "-CertificatePassword {value}", Secret = true)] public string CertificatePassword => Get<string>(() => CertificatePassword);
/// <summary>Specifies the file path to the certificate to be used in signing the package.</summary>
[Argument(Format = "-CertificatePath {value}")] public string CertificatePath => Get<string>(() => CertificatePath);
/// <summary>Specifies the name of the X.509 certificate store use to search for the certificate. Defaults to 'CurrentUser', the X.509 certificate store used by the current user. This option should be used when specifying the certificate via -CertificateSubjectName or -CertificateFingerprint options.</summary>
[Argument(Format = "-CertificateStoreLocation {value}")] public string CertificateStoreLocation => Get<string>(() => CertificateStoreLocation);
/// <summary>Specifies the name of the X.509 certificate store to use to search for the certificate. Defaults to 'My', the X.509 certificate store for personal certificates. This option should be used when specifying the certificate via -CertificateSubjectName or -CertificateFingerprint options.</summary>
[Argument(Format = "-CertificateStoreName {value}")] public string CertificateStoreName => Get<string>(() => CertificateStoreName);
/// <summary>Specifies the subject name of the certificate used to search a local certificate store for the certificate. The search is a case-insensitive string comparison using the supplied value, which will find all certificates with the subject name containing that string, regardless of other subject values. The certificate store can be specified by -CertificateStoreName and -CertificateStoreLocation options.</summary>
[Argument(Format = "-CertificateSubjectName {value}")] public string CertificateSubjectName => Get<string>(() => CertificateSubjectName);
/// <summary>Hash algorithm to be used to sign the package. Defaults to SHA256. Possible values are SHA256, SHA384, and SHA512.</summary>
[Argument(Format = "-HashAlgorithm {value}")] public NuGetSignHashAlgorithm HashAlgorithm => Get<NuGetSignHashAlgorithm>(() => HashAlgorithm);
/// <summary>Specifies the directory where the signed package should be saved. By default the original package is overwritten by the signed package.</summary>
[Argument(Format = "-OutputDirectory {value}")] public string OutputDirectory => Get<string>(() => OutputDirectory);
/// <summary>Switch to indicate if the current signature should be overwritten. By default the command will fail if the package already has a signature.</summary>
[Argument(Format = "-Overwrite")] public bool? Overwrite => Get<bool?>(() => Overwrite);
/// <summary>URL to an RFC 3161 timestamping server.</summary>
[Argument(Format = "-Timestamper {value}")] public string Timestamper => Get<string>(() => Timestamper);
/// <summary>Hash algorithm to be used by the RFC 3161 timestamp server. Defaults to SHA256.</summary>
[Argument(Format = "-TimestampHashAlgorithm {value}")] public NuGetSignHashAlgorithm TimestampHashAlgorithm => Get<NuGetSignHashAlgorithm>(() => TimestampHashAlgorithm);
/// <summary>The NuGet configuration file to apply. If not specified, <c>%AppData%\NuGet\NuGet.Config</c> (Windows) or <c>~/.nuget/NuGet/NuGet.Config</c> (Mac/Linux) is used.</summary>
[Argument(Format = "-ConfigFile {value}")] public string ConfigFile => Get<string>(() => ConfigFile);
/// <summary><em>(3.5+)</em> Forces nuget.exe to run using an invariant, English-based culture.</summary>
[Argument(Format = "-ForceEnglishOutput")] public bool? ForceEnglishOutput => Get<bool?>(() => ForceEnglishOutput);
/// <summary>Suppresses prompts for user input or confirmations.</summary>
[Argument(Format = "-NonInteractive")] public bool? NonInteractive => Get<bool?>(() => NonInteractive);
/// <summary>Specifies the amount of detail displayed in the output: <em>normal</em>, <em>quiet</em>, <em>detailed</em>.</summary>
[Argument(Format = "-Verbosity {value}")] public NuGetVerbosity Verbosity => Get<NuGetVerbosity>(() => Verbosity);
}
#endregion
#region NuGetVerifySettings
/// <inheritdoc cref="NuGetTasks.NuGetVerify(Nuke.Common.Tools.NuGet.NuGetVerifySettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Command(Type = typeof(NuGetTasks), Command = nameof(NuGetTasks.NuGetVerify), Arguments = "verify")]
| NuGetSignSettings |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp/Notifications/UserNotificationInfoWithNotificationInfo.cs | {
"start": 58,
"end": 178
} | class ____ a <see cref="UserNotificationInfo"/> and related <see cref="NotificationInfo"/>.
/// </summary>
| contains |
csharp | dotnet__aspire | src/Aspire.Hosting.Azure/api/Aspire.Hosting.Azure.cs | {
"start": 5197,
"end": 7580
} | partial class ____
{
public static ApplicationModel.IResourceBuilder<Azure.AzureProvisioningResource> AddAzureInfrastructure(this IDistributedApplicationBuilder builder, string name, System.Action<Azure.AzureResourceInfrastructure> configureInfrastructure) { throw null; }
public static global::Azure.Provisioning.KeyVault.KeyVaultSecret AsKeyVaultSecret(this Azure.IAzureKeyVaultSecretReference secretReference, Azure.AzureResourceInfrastructure infrastructure) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this ApplicationModel.EndpointReference endpointReference, Azure.AzureResourceInfrastructure infrastructure, string parameterName) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this ApplicationModel.IManifestExpressionProvider manifestExpressionProvider, Azure.AzureResourceInfrastructure infrastructure, string? parameterName = null, bool? isSecure = null) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this ApplicationModel.IResourceBuilder<ApplicationModel.ParameterResource> parameterResourceBuilder, Azure.AzureResourceInfrastructure infrastructure, string? parameterName = null) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this ApplicationModel.ParameterResource parameterResource, Azure.AzureResourceInfrastructure infrastructure, string? parameterName = null) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this ApplicationModel.ReferenceExpression expression, Azure.AzureResourceInfrastructure infrastructure, string parameterName) { throw null; }
public static global::Azure.Provisioning.ProvisioningParameter AsProvisioningParameter(this Azure.BicepOutputReference outputReference, Azure.AzureResourceInfrastructure infrastructure, string? parameterName = null) { throw null; }
public static ApplicationModel.IResourceBuilder<T> ConfigureInfrastructure<T>(this ApplicationModel.IResourceBuilder<T> builder, System.Action<Azure.AzureResourceInfrastructure> configure)
where T : Azure.AzureProvisioningResource { throw null; }
}
public static | AzureProvisioningResourceExtensions |
csharp | exceptionless__Exceptionless | src/Exceptionless.Core/Plugins/EventProcessor/EventPluginManager.cs | {
"start": 92,
"end": 2926
} | public class ____ : PluginManagerBase<IEventProcessorPlugin>
{
public EventPluginManager(IServiceProvider serviceProvider, AppOptions options, ILoggerFactory loggerFactory) : base(serviceProvider, options, loggerFactory) { }
/// <summary>
/// Runs all the event plugins startup method.
/// </summary>
public async Task StartupAsync()
{
foreach (var plugin in Plugins.Values.ToList())
{
try
{
string metricName = String.Concat(_metricPrefix, plugin.Name.ToLower());
await AppDiagnostics.TimeAsync(() => plugin.StartupAsync(), metricName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calling startup in plugin {PluginName}: {Message}", plugin.Name, ex.Message);
}
}
}
/// <summary>
/// Runs all the event plugins event processing method.
/// </summary>
public async Task EventBatchProcessingAsync(ICollection<EventContext> contexts)
{
foreach (var plugin in Plugins.Values)
{
var contextsToProcess = contexts.Where(c => c is { IsCancelled: false, HasError: false }).ToList();
if (contextsToProcess.Count == 0)
break;
string metricName = String.Concat(_metricPrefix, plugin.Name.ToLower());
try
{
await AppDiagnostics.TimeAsync(() => plugin.EventBatchProcessingAsync(contextsToProcess), metricName);
if (contextsToProcess.All(c => c.IsCancelled || c.HasError))
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calling event processing in plugin {PluginName}: {Message}", plugin.Name, ex.Message);
}
}
}
/// <summary>
/// Runs all the event plugins event processed method.
/// </summary>
public async Task EventBatchProcessedAsync(ICollection<EventContext> contexts)
{
foreach (var plugin in Plugins.Values)
{
var contextsToProcess = contexts.Where(c => c is { IsCancelled: false, HasError: false }).ToList();
if (contextsToProcess.Count == 0)
break;
string metricName = String.Concat(_metricPrefix, plugin.Name.ToLower());
try
{
await AppDiagnostics.TimeAsync(() => plugin.EventBatchProcessedAsync(contextsToProcess), metricName);
if (contextsToProcess.All(c => c.IsCancelled || c.HasError))
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calling event processed in plugin {PluginName}: {Message}", plugin.Name, ex.Message);
}
}
}
}
| EventPluginManager |
csharp | domaindrivendev__Swashbuckle.AspNetCore | src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/SchemaFilterContext.cs | {
"start": 73,
"end": 652
} | public class ____(
Type type,
ISchemaGenerator schemaGenerator,
SchemaRepository schemaRepository,
MemberInfo memberInfo = null,
ParameterInfo parameterInfo = null)
{
public Type Type { get; } = type;
public ISchemaGenerator SchemaGenerator { get; } = schemaGenerator;
public SchemaRepository SchemaRepository { get; } = schemaRepository;
public MemberInfo MemberInfo { get; } = memberInfo;
public ParameterInfo ParameterInfo { get; } = parameterInfo;
public string DocumentName => SchemaRepository.DocumentName;
}
| SchemaFilterContext |
csharp | smartstore__Smartstore | src/Smartstore.Core/Catalog/Products/Extensions/CatalogMessageFactoryExtensions.cs | {
"start": 129,
"end": 6288
} | partial class ____
{
/// <summary>
/// Sends an "email a friend" message.
/// </summary>
/// <param name="factory">Message factory.</param>
/// <param name="customer">Customer.</param>
/// <param name="product">Product.</param>
/// <param name="fromEmail">Sender email address.</param>
/// <param name="toEmail">Recipient email address.</param>
/// <param name="personalMessage">Message text.</param>
/// <param name="languageId">Language identifier.</param>
/// <returns>Create message result.</returns>
public static Task<CreateMessageResult> SendShareProductMessageAsync(
this IMessageFactory factory,
Customer customer,
Product product,
string fromEmail,
string toEmail,
string personalMessage,
int languageId = 0)
{
Guard.NotNull(customer);
Guard.NotNull(product);
var model = new NamedModelPart("Message")
{
["Body"] = personalMessage.NullEmpty(),
["From"] = fromEmail.NullEmpty(),
["To"] = toEmail.NullEmpty()
};
return factory.CreateMessageAsync(
MessageContext.Create(MessageTemplateNames.ShareProduct, languageId, customer: customer),
true,
product,
model);
}
/// <summary>
/// Sends an ask product question message.
/// </summary>
/// <param name="factory">Message factory.</param>
/// <param name="customer">Customer.</param>
/// <param name="product">Product.</param>
/// <param name="senderEmail">Sender email address.</param>
/// <param name="senderName">Sender name.</param>
/// <param name="senderPhone">Sender phone number.</param>
/// <param name="question">Question text.</param>
/// <param name="attributeInfo">Attribute informations.</param>
/// <param name="productUrl">Product URL including the query string with the selected product variant.</param>
/// <param name="isQuoteRequest">A value indicating whether the message is a quote request.</param>
/// <param name="languageId">Language identifier.</param>
/// <returns>Create message result.</returns>
public static Task<CreateMessageResult> SendProductQuestionMessageAsync(
this IMessageFactory factory,
Customer customer,
Product product,
string senderEmail,
string senderName,
string senderPhone,
string question,
string attributeInfo,
string productUrl,
bool isQuoteRequest,
int languageId = 0)
{
Guard.NotNull(customer);
Guard.NotNull(product);
var model = new NamedModelPart("Message")
{
["ProductUrl"] = productUrl.NullEmpty(),
["IsQuoteRequest"] = isQuoteRequest,
["ProductAttributes"] = attributeInfo.NullEmpty(),
["Message"] = question.NullEmpty(),
["SenderEmail"] = senderEmail.NullEmpty(),
["SenderName"] = senderName.NullEmpty(),
["SenderPhone"] = senderPhone.NullEmpty()
};
return factory.CreateMessageAsync(
MessageContext.Create(MessageTemplateNames.ProductQuestion, languageId, customer: customer),
true,
product,
model);
}
/// <summary>
/// Sends a product review notification message to a store owner.
/// </summary>
/// <param name="factory">Message factory.</param>
/// <param name="productReview">Product review</param>
/// <param name="languageId">Language identifier.</param>
/// <returns>Create message result.</returns>
public static Task<CreateMessageResult> SendProductReviewNotificationMessageAsync(this IMessageFactory factory, ProductReview productReview, int languageId = 0)
{
Guard.NotNull(productReview);
return factory.CreateMessageAsync(
MessageContext.Create(MessageTemplateNames.ProductReviewStoreOwner, languageId, customer: productReview.Customer),
true,
productReview,
productReview.Product);
}
/// <summary>
/// Sends a "quantity below" notification to a store owner.
/// </summary>
/// <param name="factory">Message factory.</param>
/// <param name="product">Product.</param>
/// <param name="languageId">Language identifier.</param>
/// <returns>Create message result.</returns>
public static Task<CreateMessageResult> SendQuantityBelowStoreOwnerNotificationAsync(this IMessageFactory factory, Product product, int languageId = 0)
{
Guard.NotNull(product);
return factory.CreateMessageAsync(
MessageContext.Create(MessageTemplateNames.QuantityBelowStoreOwner, languageId),
true,
product);
}
/// <summary>
/// Sends a 'Back in stock' notification message to a customer.
/// </summary>
/// <param name="factory">Message factory.</param>
/// <param name="subscription">Back in stock subscription.</param>
/// <returns>Create message result.</returns>
public static Task<CreateMessageResult> SendBackInStockNotificationAsync(this IMessageFactory factory, BackInStockSubscription subscription)
{
Guard.NotNull(subscription);
var customer = subscription.Customer;
var languageId = customer.GenericAttributes.LanguageId ?? 0;
return factory.CreateMessageAsync(
MessageContext.Create(MessageTemplateNames.BackInStockCustomer, languageId, subscription.StoreId, customer),
true,
subscription.Product);
}
}
}
| CatalogMessageFactoryExtensions |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectWithTempQueryTest.cs | {
"start": 21309,
"end": 22035
} | public class ____
{
[Column(IsPrimary = true)]
public string Id { get; set; }
/// <summary>
/// 样品编号
/// </summary>
public string BottleCode { get; set; }
/// <summary>
/// 送样ID
/// </summary>
public string DeliverId { get; set; }
/// <summary>
/// 送样量
/// </summary>
public string Amount { get; set; }
}
/// <summary>
/// 测试任务送样方法表
/// </summary>
[Table(Name = "Issues1467Class_deliverinfo_protocols")]
| DeliverInfoBottle |
csharp | dotnet__orleans | test/Tester/GrainServiceTests/TestGrainService.cs | {
"start": 1466,
"end": 3044
} | public sealed class ____ : GrainService, ITestGrainService
{
private readonly TestGrainServiceOptions config;
public TestGrainService(GrainId id, Silo silo, ILoggerFactory loggerFactory, IOptions<TestGrainServiceOptions> options) : base(id, silo, loggerFactory)
{
this.config = options.Value;
}
private bool started = false;
private bool startedInBackground = false;
private bool init = false;
public async override Task Init(IServiceProvider serviceProvider)
{
await base.Init(serviceProvider);
init = true;
}
public override Task Start()
{
started = true;
return base.Start();
}
public Task<string> GetHelloWorldUsingCustomService(GrainReference reference)
{
return Task.FromResult("Hello World from Test Grain Service");
}
protected override Task StartInBackground()
{
startedInBackground = true;
return Task.CompletedTask;
}
public Task<bool> HasStarted()
{
return Task.FromResult(started);
}
public Task<bool> HasStartedInBackground()
{
return Task.FromResult(startedInBackground);
}
public Task<bool> HasInit()
{
return Task.FromResult(init);
}
public Task<string> GetServiceConfigProperty()
{
return Task.FromResult(config.ConfigProperty);
}
}
| TestGrainService |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/Popup/Popup.h.mux.cs | {
"start": 168,
"end": 423
} | public partial class ____
{
private bool m_fIsLightDismiss;
internal bool IsFlyout => AssociatedFlyout is not null;
internal override bool IsFocusable =>
m_fIsLightDismiss &&
IsVisible() &&
IsEnabledInternal() &&
AreAllAncestorsVisible();
}
| Popup |
csharp | DuendeSoftware__IdentityServer | identity-server/src/AspNetIdentity/ISessionClaimsFilter.cs | {
"start": 233,
"end": 1198
} | public interface ____
{
/// <summary>
/// Filters the claims in the given SecurityStampRefreshingPrincipalContext to those that should be kept for the session.
/// These claims are not claims persisted by ASP.NET Identity, but are typically captured and login time and need to be
/// persisted across updates to the ClaimsPrincipal in the <see cref="SecurityStampValidatorOptions.OnRefreshingPrincipal"/>
/// method.
/// </summary>
/// <param name="context">The SecurityStampRefreshingPrincipalContext <see cref="SecurityStampRefreshingPrincipalContext.SecurityStampRefreshingPrincipalContext"/>
/// in the call to <see cref="SecurityStampValidatorOptions.OnRefreshingPrincipal"/>.</param>
/// <returns>The claims of the ClaimsPrincipal which should be persisted for the session.</returns>
public Task<IReadOnlyCollection<Claim>> FilterToSessionClaimsAsync(SecurityStampRefreshingPrincipalContext context);
}
| ISessionClaimsFilter |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs | {
"start": 194,
"end": 1443
} | public class ____ : ITranslationProvider
{
private readonly ILocalizationFileLocationProvider _poFilesLocationProvider;
private readonly PoParser _parser;
/// <summary>
/// Creates a new instance of <see cref="PoFilesTranslationsProvider"/>.
/// </summary>
/// <param name="poFileLocationProvider">The <see cref="ILocalizationFileLocationProvider"/>.</param>
public PoFilesTranslationsProvider(ILocalizationFileLocationProvider poFileLocationProvider)
{
_poFilesLocationProvider = poFileLocationProvider;
_parser = new PoParser();
}
/// <inheritdocs />
public void LoadTranslations(string cultureName, CultureDictionary dictionary)
{
foreach (var fileInfo in _poFilesLocationProvider.GetLocations(cultureName))
{
LoadFileToDictionary(fileInfo, dictionary);
}
}
private void LoadFileToDictionary(IFileInfo fileInfo, CultureDictionary dictionary)
{
if (fileInfo.Exists && !fileInfo.IsDirectory)
{
using var stream = fileInfo.CreateReadStream();
using var reader = new StreamReader(stream);
dictionary.MergeTranslations(_parser.Parse(reader));
}
}
}
| PoFilesTranslationsProvider |
csharp | reactiveui__ReactiveUI | src/ReactiveUI.Tests/API/ApiApprovalTests.cs | {
"start": 532,
"end": 1084
} | public class ____
{
/// <summary>
/// Generates public API for the ReactiveUI.Testing API.
/// </summary>
/// <returns>A task to monitor the process.</returns>
[Test]
public Task Testing() => typeof(Testing.SchedulerExtensions).Assembly.CheckApproval(["ReactiveUI"]);
/// <summary>
/// Generates public API for the ReactiveUI API.
/// </summary>
/// <returns>A task to monitor the process.</returns>
[Test]
public Task ReactiveUI() => typeof(RxApp).Assembly.CheckApproval(["ReactiveUI"]);
}
| ApiApprovalTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.