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 | unoplatform__uno | src/Uno.UI.Dispatching/Generated/3.0.0.0/Microsoft.UI.Dispatching/DispatcherQueueShutdownStartingEventArgs.cs | {
"start": 299,
"end": 1145
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal DispatcherQueueShutdownStartingEventArgs()
{
}
#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.Foundation.Deferral GetDeferral()
{
throw new global::System.NotImplementedException("The member Deferral DispatcherQueueShutdownStartingEventArgs.GetDeferral() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Deferral%20DispatcherQueueShutdownStartingEventArgs.GetDeferral%28%29");
}
#endif
}
}
| DispatcherQueueShutdownStartingEventArgs |
csharp | dotnet__maui | src/Essentials/src/Permissions/Permissions.android.cs | {
"start": 9762,
"end": 9978
} | public partial class ____ : BasePlatformPermission
{
public override (string androidPermission, bool isRuntime)[] RequiredPermissions =>
new (string, bool)[] { (Manifest.Permission.Camera, true) };
}
| Camera |
csharp | jbogard__MediatR | test/MediatR.DependencyInjectionTests/Abstractions/BaseAssemblyResolutionTests.cs | {
"start": 237,
"end": 2354
} | public abstract class ____(BaseServiceProviderFixture fixture) : IClassFixture<BaseServiceProviderFixture>
{
private readonly IServiceProvider _provider = fixture.Provider;
[Fact]
public void Should_Resolve_Mediator() =>
_provider.GetService<IMediator>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Public_RequestHandler() =>
_provider.GetService<IRequestHandler<PublicPing, Pong>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Internal_RequestHandler() =>
_provider.GetService<IRequestHandler<InternalPing, Pong>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Private_RequestHandler() =>
_provider.GetService<IRequestHandler<PrivatePing, Pong>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Public_Void_RequestHandler() =>
_provider.GetService<IRequestHandler<PublicVoidPing>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Internal_Void_RequestHandler() =>
_provider.GetService<IRequestHandler<InternalVoidPing>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Private_Void_RequestHandler() =>
_provider.GetService<IRequestHandler<PrivateVoidPing>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Public_Private_Internal_Notification_Handlers() =>
_provider.GetServices<INotificationHandler<Ding>>()
.Count()
.ShouldBe(3);
[Fact]
public void Should_Resolve_Public_Stream_Request_Handlers() =>
_provider.GetService<IStreamRequestHandler<PublicZing, Zong>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Internal_Stream_Request_Handlers() =>
_provider.GetService<IStreamRequestHandler<InternalZing, Zong>>()
.ShouldNotBeNull();
[Fact]
public void Should_Resolve_Private_Stream_Request_Handlers() =>
_provider.GetService<IStreamRequestHandler<PrivateZing, Zong>>()
.ShouldNotBeNull();
} | BaseAssemblyResolutionTests |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Media.Animation/ConnectedAnimationConfiguration.cs | {
"start": 308,
"end": 533
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal ConnectedAnimationConfiguration()
{
}
#endif
}
}
| ConnectedAnimationConfiguration |
csharp | abpframework__abp | framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/TranslateCommand.cs | {
"start": 23111,
"end": 23216
} | public static class ____
{
public const string Long = "online";
}
| Online |
csharp | VerifyTests__Verify | src/Verify/Serialization/VerifyJsonWriter.cs | {
"start": 63,
"end": 10598
} | public class ____ :
JsonTextWriter
{
StringBuilder builder;
internal VerifySettings settings;
internal SerializationSettings serialization;
public IReadOnlyDictionary<string, object> Context { get; }
public Counter Counter { get; }
internal VerifyJsonWriter(StringBuilder builder, VerifySettings settings, Counter counter) :
base(
new StringWriter(builder)
{
NewLine = "\n"
})
{
this.builder = builder;
this.settings = settings;
serialization = settings.serialization;
Context = settings.Context;
Counter = counter;
Formatting = Formatting.Indented;
if (!settings.StrictJson)
{
QuoteValue = false;
EscapeHandling = EscapeHandling.None;
QuoteName = false;
}
}
public void WriteRawValueIfNoStrict(string value) =>
WriteRawValueIfNoStrict(value.AsSpan());
public void WriteRawValueIfNoStrict(CharSpan value)
{
if (settings.StrictJson)
{
base.WriteValue(value);
return;
}
base.WriteRawValue(value);
}
public override void WriteValue(char value)
{
if (settings.StrictJson)
{
base.WriteValue(value);
return;
}
base.WriteRawValue(value.ToString());
}
public void WriteRawValueWithScrubbers(string value) =>
WriteRawValueWithScrubbers(value.AsSpan());
public void WriteRawValueWithScrubbers(CharSpan value)
{
if (value.Length == 0)
{
WriteRawValueIfNoStrict(value);
return;
}
value = ApplyScrubbers.ApplyForPropertyValue(value, settings, Counter);
WriteRawValueIfNoStrict(value);
}
public override void WritePropertyName(CharSpan name, bool escape)
{
if (settings.StrictJson)
{
escape = false;
}
base.WritePropertyName(name, escape);
}
public override void WritePropertyName(string name, bool escape)
{
if (settings.StrictJson)
{
escape = false;
}
base.WritePropertyName(name, escape);
}
public override void WriteValue(string? value)
{
if (value is null)
{
base.WriteNull();
return;
}
WriteValue(value.AsSpan());
}
public override void WriteValue(StringBuilder? value) =>
// TODO:
WriteValue(value?.ToString());
public override void WriteValue(CharSpan value)
{
if (value is "")
{
WriteRawValueIfNoStrict(value);
return;
}
if (Counter.TryConvert(value, out var result))
{
WriteRawValueIfNoStrict(result);
return;
}
value = ApplyScrubbers.ApplyForPropertyValue(value, settings, Counter);
if (settings.StrictJson)
{
base.WriteValue(value);
return;
}
if (value.Contains('\n'))
{
base.Flush();
var builderLength = builder.Length;
if (value[0] != '\n')
{
WriteRawValue("\n");
WriteRaw(value);
}
else
{
WriteRawValue(value);
}
base.Flush();
builder.Remove(builderLength, 1);
return;
}
WriteRawValueIfNoStrict(value);
}
public override void WriteValue(byte[]? value)
{
if (value is null)
{
WriteNull();
return;
}
WriteRawValueIfNoStrict(Convert.ToBase64String(value));
}
public override void WriteValue(DateTimeOffset value)
{
if (Counter.TryConvert(value, out var result))
{
WriteRawValueIfNoStrict(result);
return;
}
WriteRawValueWithScrubbers(DateFormatter.Convert(value));
}
public override void WriteValue(DateTime value)
{
if (Counter.TryConvert(value, out var result))
{
WriteRawValueIfNoStrict(result);
return;
}
WriteRawValueWithScrubbers(DateFormatter.Convert(value));
}
public override void WriteValue(TimeSpan value) =>
WriteRawValueIfNoStrict(value.ToString());
public override void WriteValue(Guid value)
{
if (Counter.TryConvert(value, out var result))
{
WriteRawValueIfNoStrict(result);
return;
}
Span<char> buffer = stackalloc char[36];
value.TryFormat(buffer, out _);
WriteRawValueWithScrubbers(buffer);
}
/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
public void WriteMember<T>(object target, T? value, string name, T defaultIgnore)
{
if (value is null)
{
return;
}
if (EqualityComparer<T>.Default.Equals(value, defaultIgnore))
{
return;
}
WriteMember(target, value, name);
}
/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
public void WriteMember(object target, object? value, string name)
{
if (value is null)
{
WriteNullMember(name);
return;
}
if (ReferenceEquals(target, value))
{
WriteRawOrStrictMember(name, "$parentValue");
return;
}
var declaringType = target.GetType();
var memberType = value.GetType();
if (serialization.TryGetScrubOrIgnore(declaringType, memberType, name, out var scrubOrIgnore))
{
if (scrubOrIgnore != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
return;
}
if (serialization.TryGetScrubOrIgnoreByInstance(value, out scrubOrIgnore))
{
if (scrubOrIgnore != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
return;
}
var converter = VerifierSettings.GetMemberConverter(declaringType, name);
if (converter is not null)
{
value = converter(target, value);
if (value is null)
{
return;
}
}
WritePropertyName(name);
WriteOrSerialize(value);
}
/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
public void WriteMember(object target, string? value, string name)
{
if (value is null)
{
WriteNullMember(name);
return;
}
var declaringType = target.GetType();
if (serialization.TryGetScrubOrIgnore(declaringType, typeof(string), name, out var scrubOrIgnore))
{
if (scrubOrIgnore != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
return;
}
if (serialization.TryGetScrubOrIgnoreByInstance(value, out scrubOrIgnore))
{
if (scrubOrIgnore != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
return;
}
var converter = VerifierSettings.GetMemberConverter(declaringType, name);
if (converter is not null)
{
value = (string?) converter(target, value);
if (value is null)
{
return;
}
}
WritePropertyName(name);
WriteValue(value);
}
/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
public void WriteMember(object target, CharSpan value, string name)
{
var declaringType = target.GetType();
if (serialization.TryGetScrubOrIgnore(declaringType, typeof(CharSpan), name, out var scrubOrIgnore))
{
if (scrubOrIgnore != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
return;
}
//TODO: support instance scrubbing for CharSpan?
// if (serialization.TryGetScrubOrIgnoreByInstance(value, out scrubOrIgnore))
// {
// if (scrubOrIgnore != ScrubOrIgnore.Ignore)
// {
// WriteRawOrStrictMember(name, "Scrubbed");
// }
//
// return;
// }
//TODO: support converters for CharSpan?
// var converter = VerifierSettings.GetMemberConverter(declaringType, name);
// if (converter is not null)
// {
// value = (string?) converter(target, value);
// if (value is null)
// {
// return;
// }
// }
WritePropertyName(name);
WriteValue(value);
}
void WriteRawOrStrictMember(string name, string value)
{
WritePropertyName(name);
WriteRawValueIfNoStrict(value);
}
void WriteNullMember(string name)
{
if (serialization.TryGetScrubOrIgnoreByName(name, out var scrubOrIgnoreByName))
{
if (scrubOrIgnoreByName != ScrubOrIgnore.Ignore)
{
WriteRawOrStrictMember(name, "Scrubbed");
}
}
else if (!serialization.IgnoreNulls)
{
WritePropertyName(name);
WriteNull();
}
}
void WriteOrSerialize(object value)
{
if (value is string stringValue)
{
WriteValue(stringValue);
return;
}
if (value.GetType().IsPrimitive)
{
WriteValue(value);
return;
}
settings.Serializer.Serialize(this, value);
}
/// <summary>
/// Convenience method that calls <see cref="Serializer" />.<see cref="JsonSerializer.Serialize(TextWriter,object?)" /> passing in the writer instance and <paramref name="value" />
/// </summary>
public void Serialize(object value) =>
settings.Serializer.Serialize(this, value);
public JsonSerializer Serializer => settings.Serializer;
} | VerifyJsonWriter |
csharp | open-telemetry__opentelemetry-dotnet | src/OpenTelemetry/OpenTelemetrySdk.cs | {
"start": 3445,
"end": 3846
} | private sealed class ____ : IOpenTelemetryBuilder
{
public OpenTelemetrySdkBuilder(IServiceCollection services)
{
Debug.Assert(services != null, "services was null");
services!.AddOpenTelemetrySharedProviderBuilderServices();
this.Services = services!;
}
public IServiceCollection Services { get; }
}
}
| OpenTelemetrySdkBuilder |
csharp | dotnet__maui | src/Compatibility/Core/src/WPF/Helpers/UiHelper.cs | {
"start": 189,
"end": 465
} | static class ____
{
public static void ExecuteInUiThread(Action action)
{
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
{
action?.Invoke();
}
else
{
System.Windows.Application.Current.Dispatcher.Invoke(action);
}
}
}
}
| UiHelper |
csharp | PrismLibrary__Prism | src/Maui/Prism.DryIoc.Maui/PrismAppExtensions.cs | {
"start": 90,
"end": 125
} | class ____ DryIoc
/// </summary>
| using |
csharp | cake-build__cake | src/Cake.Common.Tests/Fixtures/Build/ContinuaCIInfoFixture.cs | {
"start": 380,
"end": 6054
} | internal sealed class ____
{
public ICakeEnvironment Environment { get; set; }
public ContinuaCIInfoFixture()
{
Environment = Substitute.For<ICakeEnvironment>();
// ContinuaCIBuildInfo
Environment.GetEnvironmentVariable("ContinuaCI.Build.Id").Returns("99");
Environment.GetEnvironmentVariable("ContinuaCI.Build.Version").Returns("v1.2.3");
Environment.GetEnvironmentVariable("ContinuaCI.Build.StartedBy").Returns("TestTrigger");
Environment.GetEnvironmentVariable("ContinuaCI.Build.IsFeatureBranchBuild").Returns("true");
Environment.GetEnvironmentVariable("ContinuaCI.Build.BuildNumber").Returns("999");
Environment.GetEnvironmentVariable("ContinuaCI.Build.Started").Returns("2015-12-15T22:53:37.847+01:00");
Environment.GetEnvironmentVariable("ContinuaCI.Build.UsesDefaultBranch").Returns("false");
Environment.GetEnvironmentVariable("ContinuaCI.Build.HasNewChanges").Returns("true");
Environment.GetEnvironmentVariable("ContinuaCI.Build.ChangesetCount").Returns("6");
Environment.GetEnvironmentVariable("ContinuaCI.Build.IssueCount").Returns("3");
Environment.GetEnvironmentVariable("ContinuaCI.Build.Elapsed").Returns(TimeSpan.FromMinutes(5).ToString());
Environment.GetEnvironmentVariable("ContinuaCI.Build.TimeOnQueue").Returns("7777");
Environment.GetEnvironmentVariable("ContinuaCI.Build.Repositories").Returns("Repo1,Repo2,Repo3");
Environment.GetEnvironmentVariable("ContinuaCI.Build.RepositoryBranches").Returns("Branch1,Branch2,Branch3");
Environment.GetEnvironmentVariable("ContinuaCI.Build.TriggeringBranch").Returns("Branch2");
Environment.GetEnvironmentVariable("ContinuaCI.Build.ChangesetRevisions").Returns("6,8,65");
Environment.GetEnvironmentVariable("ContinuaCI.Build.ChangesetUserNames").Returns("george,bill");
Environment.GetEnvironmentVariable("ContinuaCI.Build.ChangesetTagNames").Returns("tag1,tag2,tag 3");
// ContinuaCIChangesetInfo
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.Revision").Returns("55");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.Branch").Returns("master");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.Created").Returns("2016-01-02T12:00:16.666+11:00");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.FileCount").Returns("77");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.UserName").Returns("georgedawes");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.TagCount").Returns("2");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.IssueCount").Returns("3");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.TagNames").Returns("the tag,the other tag");
Environment.GetEnvironmentVariable("ContinuaCI.Build.LatestChangeset.IssueNames").Returns("an important issue,another more important issue,a not so important issue");
// ContinuaCIProjectInfo
Environment.GetEnvironmentVariable("ContinuaCI.Project.Name").Returns("the project from hell");
// ContinuaCIConfigurationInfo
Environment.GetEnvironmentVariable("ContinuaCI.Configuration.Name").Returns("The configuration from the end of the universe");
// ContinuaCIEnvironmentInfo
Environment.GetEnvironmentVariables().Returns(new Dictionary<string, string>()
{
{ "ContinuaCI.Variable.TestVar1", "gorgonzola" },
{ "ContinuaCI.Variable.TestVar2", "is" },
{ "ContinuaCI.Variable.TestVarX", "tasty" },
{ "This.Is.A.Dummy", "Init?" },
{ "ContinuaCI.AgentProperty.DotNet.4.0.FrameworkPathX64", @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319" },
{ "ContinuaCI.AgentProperty.MSBuild.4.0.PathX86", @"C:\Windows\Microsoft.NET\Framework\v4.0.30319" },
{ "ContinuaCI.AgentProperty.ServerFileTransport.UNCAvailable", "True" }
});
Environment.GetEnvironmentVariable("ContinuaCI.Version").Returns("v1.6.6.6");
}
public ContinuaCIBuildInfo CreateBuildInfo()
{
return new ContinuaCIBuildInfo(Environment, "ContinuaCI.Build");
}
public ContinuaCIEnvironmentInfo CreateEnvironmentInfo()
{
return new ContinuaCIEnvironmentInfo(Environment);
}
public ContinuaCIProjectInfo CreateProjectInfo()
{
return new ContinuaCIProjectInfo(Environment, "ContinuaCI.Project");
}
public ContinuaCIConfigurationInfo CreateConfigurationInfo()
{
return new ContinuaCIConfigurationInfo(Environment, "ContinuaCI.Configuration");
}
public ContinuaCIChangesetInfo CreateChangesetInfo()
{
return new ContinuaCIChangesetInfo(Environment, "ContinuaCI.Build.LatestChangeset");
}
}
} | ContinuaCIInfoFixture |
csharp | DuendeSoftware__IdentityServer | bff/src/Bff.Blazor/BffBlazorServerOptions.cs | {
"start": 218,
"end": 544
} | public sealed record ____
{
/// <summary>
/// The delay, in milliseconds, between polling requests by the
/// BffServerAuthenticationStateProvider to the /bff/user endpoint. Defaults to 5000
/// ms.
/// </summary>
public int ServerStateProviderPollingInterval { get; set; } = 5000;
}
| BffBlazorServerOptions |
csharp | AutoFixture__AutoFixture | Src/Idioms/CompositeBehaviorExpectation.cs | {
"start": 1033,
"end": 2394
} | class ____
/// the supplied <see cref="IBehaviorExpectation" /> instances.
/// </summary>
/// <param name="behaviorExpectations">The encapsulated behavior expectations.</param>
/// <seealso cref="CompositeBehaviorExpectation(IBehaviorExpectation[])" />
/// <seealso cref="BehaviorExpectations" />
public CompositeBehaviorExpectation(IEnumerable<IBehaviorExpectation> behaviorExpectations)
: this(behaviorExpectations.ToArray())
{
}
/// <summary>
/// Verifies the behavior of the command by delegating the implementation to all
/// <see cref="BehaviorExpectations" />.
/// </summary>
/// <param name="command">The command whose behavior must be examined.</param>
public void Verify(IGuardClauseCommand command)
{
foreach (var be in this.BehaviorExpectations)
{
be.Verify(command);
}
}
/// <summary>
/// Gets the behavior expectations supplied via the constructor.
/// </summary>
/// <seealso cref="CompositeBehaviorExpectation(IBehaviorExpectation[])" />
/// <seealso cref="CompositeBehaviorExpectation(IEnumerable{IBehaviorExpectation})"/>
public IEnumerable<IBehaviorExpectation> BehaviorExpectations { get; }
}
}
| with |
csharp | dotnet__orleans | src/api/AWS/Orleans.Streaming.SQS/Orleans.Streaming.SQS.cs | {
"start": 395,
"end": 575
} | public partial class ____
{
[Redact]
public string ConnectionString { get { throw null; } set { } }
}
}
namespace Orleans.Hosting
{
public static | SqsOptions |
csharp | OrchardCMS__OrchardCore | test/OrchardCore.Tests/Abstractions/Json/Nodes/JArrayTests.cs | {
"start": 104,
"end": 1231
} | public class ____
{
public static IEnumerable<object[]> MergeArrayEntries => [
["[1, 2, 3, 4]", "[4, 5, 6]", null, "[1,2,3,4,4,5,6]"],
["[1, 2, 3, 4]", "[4, 5, 6]", new JsonMergeSettings() { MergeArrayHandling = MergeArrayHandling.Concat }, "[1,2,3,4,4,5,6]"],
["[1, 2, 3, 4]", "[4, 5, 6]", new JsonMergeSettings() { MergeArrayHandling = MergeArrayHandling.Union }, "[1,2,3,4,5,6]"],
["[1, 2, 3, 4]", "[4, 5, 6]", new JsonMergeSettings() { MergeArrayHandling = MergeArrayHandling.Replace }, "[4,5,6]"]
];
[Theory]
[MemberData(nameof(MergeArrayEntries))]
public void MergeArrayShouldRespectJsonMergeSettings(string jsonArrayContent1, string jsonArrayContent2, JsonMergeSettings mergeSettings, string expectedJsonString)
{
// Arrange
var array = JsonNode.Parse(jsonArrayContent1) as JsonArray;
var content = JsonNode.Parse(jsonArrayContent2);
// Act
var result = array.Merge(content, mergeSettings);
// Assert
Assert.NotNull(result);
Assert.Equal(expectedJsonString, result.ToJsonString());
}
}
| JArrayTests |
csharp | EventStore__EventStore | src/KurrentDB.Diagnostics.LogsEndpointPlugin.Tests/LogsEndpointPluginTests.cs | {
"start": 3291,
"end": 3412
} | public class ____ : LogsEndpointPluginFixture {
public UnlicensedFixture() : base(licensed: false) {
}
}
| UnlicensedFixture |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/ErrorPageMiddlewareWebSite/AggregateExceptionController.cs | {
"start": 211,
"end": 892
} | public class ____ : Controller
{
[HttpGet("/AggregateException")]
public IActionResult Index()
{
var firstException = ThrowNullReferenceException();
var secondException = ThrowIndexOutOfRangeException();
Task.WaitAll(firstException, secondException);
return View();
}
private static async Task ThrowNullReferenceException()
{
await Task.Delay(0);
throw new NullReferenceException("Foo cannot be null");
}
private static async Task ThrowIndexOutOfRangeException()
{
await Task.Delay(0);
throw new IndexOutOfRangeException("Index is out of range");
}
}
| AggregateExceptionController |
csharp | grpc__grpc-dotnet | src/Grpc.StatusProto/MetadataExtensions.cs | {
"start": 778,
"end": 3174
} | public static class ____
{
/// <summary>
/// Name of key in the metadata for the binary encoding of <see cref="Google.Rpc.Status"/>.
/// </summary>
public const string StatusDetailsTrailerName = "grpc-status-details-bin";
/// <summary>
/// Get <see cref="Google.Rpc.Status"/> from the metadata with the <c>grpc-status-details-bin</c> key.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="ignoreParseError">If true then <see langword="null"/> is returned on a parsing error,
/// otherwise an error will be thrown if the metadata cannot be parsed.</param>
/// <returns>
/// The <see cref="Google.Rpc.Status"/> or <see langword="null"/> if <c>grpc-status-details-bin</c> was
/// not present or could the data could not be parsed.
/// </returns>
public static Google.Rpc.Status? GetRpcStatus(this Metadata metadata, bool ignoreParseError = false)
{
ArgumentNullThrowHelper.ThrowIfNull(metadata);
var entry = metadata.Get(StatusDetailsTrailerName);
if (entry is null)
{
return null;
}
try
{
return Google.Rpc.Status.Parser.ParseFrom(entry.ValueBytes);
}
catch when (ignoreParseError)
{
// If the message is malformed just report there's no information.
return null;
}
}
/// <summary>
/// Add <see cref="Google.Rpc.Status"/> to the metadata with the <c>grpc-status-details-bin</c> key.
/// An existing status in the metadata will be overwritten.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="status">The status to add.</param>
public static void SetRpcStatus(this Metadata metadata, Google.Rpc.Status status)
{
ArgumentNullThrowHelper.ThrowIfNull(metadata);
ArgumentNullThrowHelper.ThrowIfNull(status);
var entry = metadata.Get(StatusDetailsTrailerName);
while (entry is not null)
{
metadata.Remove(entry);
entry = metadata.Get(StatusDetailsTrailerName);
}
metadata.Add(StatusDetailsTrailerName, status.ToByteArray());
}
}
| MetadataExtensions |
csharp | dotnet__aspnetcore | src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateValidationAttributesOnClasses#ValidatableInfoResolver.g.verified.cs | {
"start": 3864,
"end": 6423
} | class ____ : global::Microsoft.Extensions.Validation.IValidatableInfoResolver
{
public bool TryGetValidatableTypeInfo(global::System.Type type, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo)
{
validatableInfo = null;
if (type == typeof(global::NestedType))
{
validatableInfo = new GeneratedValidatableTypeInfo(
type: typeof(global::NestedType),
members: []
);
return true;
}
if (type == typeof(global::ComplexType))
{
validatableInfo = new GeneratedValidatableTypeInfo(
type: typeof(global::ComplexType),
members: [
new GeneratedValidatablePropertyInfo(
containingType: typeof(global::ComplexType),
propertyType: typeof(int),
name: "X",
displayName: "X"
),
new GeneratedValidatablePropertyInfo(
containingType: typeof(global::ComplexType),
propertyType: typeof(int),
name: "Y",
displayName: "Y"
),
new GeneratedValidatablePropertyInfo(
containingType: typeof(global::ComplexType),
propertyType: typeof(global::NestedType),
name: "ObjectProperty",
displayName: "ObjectProperty"
),
]
);
return true;
}
return false;
}
// No-ops, rely on runtime code for ParameterInfo-based resolution
public bool TryGetValidatableParameterInfo(global::System.Reflection.ParameterInfo parameterInfo, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo)
{
validatableInfo = null;
return false;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
file | GeneratedValidatableInfoResolver |
csharp | dotnet__aspnetcore | src/Components/Analyzers/test/AnalyzerTestBase.cs | {
"start": 268,
"end": 1453
} | public abstract class ____
{
// Test files are copied to both the bin/ and publish/ folders. Use BaseDirectory on or off Helix.
private static readonly string ProjectDirectory = AppContext.BaseDirectory;
public TestSource Read(string source)
{
if (!source.EndsWith(".cs", StringComparison.Ordinal))
{
source += ".cs";
}
var filePath = Path.Combine(ProjectDirectory, "TestFiles", GetType().Name, source);
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"TestFile {source} could not be found at {filePath}.", filePath);
}
var fileContent = File.ReadAllText(filePath);
return TestSource.Read(fileContent);
}
public Project CreateProject(string source)
{
if (!source.EndsWith(".cs", StringComparison.Ordinal))
{
source += ".cs";
}
var read = Read(source);
return DiagnosticProject.Create(GetType().Assembly, new[] { read.Source, });
}
public Task<Compilation> CreateCompilationAsync(string source)
{
return CreateProject(source).GetCompilationAsync();
}
}
| AnalyzerTestBase |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/Filtering/FunctionInvocationFiltering.cs | {
"start": 6156,
"end": 7419
} | private sealed class ____ : IFunctionInvocationFilter
{
public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next)
{
// Example: override kernel arguments
context.Arguments["input"] = "new input";
// This call is required to proceed with next filters in pipeline and actual function.
// Without this call next filters and function won't be invoked.
await next(context);
// Example: get function result value
var value = context.Result!.GetValue<object>();
// Example: get token usage from metadata
var usage = context.Result.Metadata?["Usage"];
// Example: override function result value and metadata
Dictionary<string, object?> metadata = context.Result.Metadata is not null ? new(context.Result.Metadata) : [];
metadata["metadata_key"] = "metadata_value";
context.Result = new FunctionResult(context.Result, "Result from filter")
{
Metadata = metadata
};
}
}
/// <summary>Shows syntax for function filter in streaming scenario.</summary>
| FunctionFilterExample |
csharp | dotnet__efcore | test/EFCore.AspNet.Sqlite.FunctionalTests/AspNetIdentityIntKeySqliteTest.cs | {
"start": 414,
"end": 811
} | public class ____ : AspNetIdentityFixtureBase
{
public TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ListLoggerFactory;
protected override ITestStoreFactory TestStoreFactory
=> SqliteTestStoreFactory.Instance;
protected override string StoreName
=> "AspNetIntKeyIdentity";
}
}
| AspNetIdentityIntKeySqliteFixture |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/CmsKitErrorCodes.cs | {
"start": 881,
"end": 1002
} | public static class ____
{
public const string EntityNotCommentable = "CmsKit:Comments:0001";
}
| Comments |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs | {
"start": 175594,
"end": 175859
} | public enum ____ {
[pbr::OriginalName("Value0")] Value0 = 0,
[pbr::OriginalName("Value1")] Value1 = 1,
[pbr::OriginalName("Value2")] Value2 = 2,
[pbr::OriginalName("Value3")] Value3 = 3,
}
#endregion
#region Messages
public sealed | SomeEnumAsInt |
csharp | reactiveui__ReactiveUI | src/ReactiveUI/ReactiveCommand/ReactiveCommandBase.cs | {
"start": 452,
"end": 3927
} | class ____ <see cref="ReactiveCommand"/> and adds generic type parameters for the parameter values passed
/// into command execution, and the return values of command execution.
/// </para>
/// <para>
/// Because the result type is known by this class, it can implement <see cref="IObservable{T}"/>. However, the implementation
/// is defined as abstract, so subclasses must provide it.
/// </para>
/// <para>
/// Reactive commands encapsulate the behavior of running some execution logic and then surfacing the results on the UI
/// thread. Importantly, no scheduling is performed against input observables (the <c>canExecute</c> and execution pipelines).
/// </para>
/// <para>
/// To create an instance of <c>ReactiveCommand</c>, call one of the static creation methods defined by this class.
/// <see cref="ReactiveCommand.Create"/> can be used when your execution logic is synchronous.
/// ReactiveCommand.CreateFromObservable and
/// ReactiveCommand.CreateFromTask (and overloads) can be used for asynchronous
/// execution logic. Optionally, you can provide an observable that governs the availability of the command for execution,
/// as well as a scheduler to which events will be delivered.
/// </para>
/// <para>
/// The <see cref="CanExecute"/> property provides an observable that can be used to determine whether the command is
/// eligible for execution. The value of this observable is determined by both the <c>canExecute</c> observable provided
/// during command creation, and the current execution status of the command. A command that is already executing will
/// yield <c>false</c> from its <see cref="CanExecute"/> observable regardless of the <c>canExecute</c> observable provided
/// during command creation.
/// </para>
/// <para>
/// The <see cref="IsExecuting"/> property provides an observable whose value indicates whether the command is currently
/// executing. This can be a useful means of triggering UI, such as displaying an activity indicator whilst a command is
/// executing.
/// </para>
/// <para>
/// As discussed above, you are under no obligation to somehow incorporate this into your <c>canExecute</c> observable
/// because that is taken care of for you. That is, if the value of <c>IsExecuting</c> is <c>true</c>, the value of
/// <c>CanExecute</c> will be <c>false</c>. However, if the value of <c>CanExecute</c> is <c>false</c>, that does not imply
/// the value of <c>IsExecuting</c> is <c>true</c>.
/// </para>
/// <para>
/// Any errors in your command's execution logic (including any <c>canExecute</c> observable you choose to provide) will be
/// surfaced via the <see cref="ThrownExceptions"/> observable. This gives you the opportunity to handle the error before
/// it triggers a default handler that tears down the application. For example, you might use this as a means of alerting
/// the user that something has gone wrong executing the command.
/// </para>
/// <para>
/// For the sake of convenience, all <c>ReactiveCommand</c> instances are also implementations of <see cref="ICommand"/>.
/// This allows you to easily integrate instances of <c>ReactiveCommand</c> into platforms that understands <c>ICommand</c>
/// natively (such as WPF and UWP).
/// </para>
/// </remarks>
/// <typeparam name="TParam">
/// The type of parameter values passed in during command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the values that are the result of command execution.
/// </typeparam>
| extends |
csharp | dotnet__orleans | test/Grains/TestGrains/GrainInterfaceHierarchyGrains.cs | {
"start": 2883,
"end": 4306
} | public class ____ : Grain, IDoSomethingCombinedGrain
{
private int A;
private int B;
private int C;
public Task<string> DoIt()
{
return Task.FromResult(GetType().Name);
}
public Task<string> DoMore()
{
return Task.FromResult(GetType().Name);
}
public Task<string> DoThat()
{
return Task.FromResult(GetType().Name);
}
public Task SetA(int a)
{
A = a;
return Task.CompletedTask;
}
public Task IncrementA()
{
A++;
return Task.CompletedTask;
}
public Task<int> GetA()
{
return Task.FromResult(A);
}
public Task SetB(int b)
{
B = b;
return Task.CompletedTask;
}
public Task IncrementB()
{
B++;
return Task.CompletedTask;
}
public Task<int> GetB()
{
return Task.FromResult(B);
}
public Task SetC(int c)
{
C = c;
return Task.CompletedTask;
}
public Task IncrementC()
{
C++;
return Task.CompletedTask;
}
public Task<int> GetC()
{
return Task.FromResult(C);
}
}
}
| DoSomethingCombinedGrain |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests.Provider.OracleOledb/OracleOledb/Curd/OracleOledbInsertOrUpdateIfExistsDoNothingTest.cs | {
"start": 155,
"end": 2721
} | public class ____
{
IFreeSql fsql => g.oracle;
[Fact]
public void InsertOrUpdate_OnlyPrimary()
{
fsql.Delete<tbioudb01>().Where("1=1").ExecuteAffrows();
var iou = fsql.InsertOrUpdate<tbioudb01>().IfExistsDoNothing().SetSource(new tbioudb01 { id = 1 });
var sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOUDB01"" t1
USING (SELECT 1 as ""ID"" FROM dual ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(1, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbioudb01>().IfExistsDoNothing().SetSource(new tbioudb01 { id = 1 });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOUDB01"" t1
USING (SELECT 1 as ""ID"" FROM dual ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(0, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbioudb01>().IfExistsDoNothing().SetSource(new tbioudb01 { id = 2 });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOUDB01"" t1
USING (SELECT 2 as ""ID"" FROM dual ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(1, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbioudb01>().IfExistsDoNothing().SetSource(new[] { new tbioudb01 { id = 1 }, new tbioudb01 { id = 2 }, new tbioudb01 { id = 3 }, new tbioudb01 { id = 4 } });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOUDB01"" t1
USING (SELECT 1 as ""ID"" FROM dual
UNION ALL
SELECT 2 FROM dual
UNION ALL
SELECT 3 FROM dual
UNION ALL
SELECT 4 FROM dual ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(2, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbioudb01>().IfExistsDoNothing().SetSource(new[] { new tbioudb01 { id = 1 }, new tbioudb01 { id = 2 }, new tbioudb01 { id = 3 }, new tbioudb01 { id = 4 } });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOUDB01"" t1
USING (SELECT 1 as ""ID"" FROM dual
UNION ALL
SELECT 2 FROM dual
UNION ALL
SELECT 3 FROM dual
UNION ALL
SELECT 4 FROM dual ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(0, iou.ExecuteAffrows());
}
| OracleOledbInsertOrUpdateIfExistsDoNothingTest |
csharp | GtkSharp__GtkSharp | Source/Libs/CairoSharp/PointD.cs | {
"start": 1470,
"end": 1725
} | public struct ____
{
public PointD (double x, double y)
{
this.x = x;
this.y = y;
}
double x, y;
public double X {
get { return x; }
set { x = value; }
}
public double Y {
get { return y; }
set { y = value; }
}
}
}
| PointD |
csharp | smartstore__Smartstore | src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardCouponCodeConverter.cs | {
"start": 761,
"end": 3926
} | internal class ____ : DefaultTypeConverter
{
public GiftCardCouponCodeConverter()
: base(typeof(object))
{
}
public override bool CanConvertFrom(Type type)
=> type == typeof(string);
public override bool CanConvertTo(Type type)
=> type == typeof(string);
public override object ConvertFrom(CultureInfo culture, object value)
{
if (value is string str)
{
if (str.HasValue())
{
try
{
// Convert either from XML or JSON. Check first character to determine format.
var firstChar = str.Trim()[0];
if (firstChar is '<')
{
// XML
var attributes = new List<GiftCardCouponCode>();
var xel = XElement.Parse(str);
var elements = xel.Descendants("CouponCode");
foreach (var element in elements)
{
var code = element.Attribute("Code")?.Value ?? null;
if (code.HasValue())
{
attributes.Add(new(code));
}
}
return attributes;
}
else if (firstChar is '[')
{
// JSON
return JsonConvert.DeserializeObject<List<string>>(str)
.Select(x => new GiftCardCouponCode(x))
.ToList();
}
}
catch (JsonSerializationException ex)
{
throw new JsonSerializationException("Error while trying to deserialize object from Json: " + str, ex);
}
catch (XmlException ex)
{
throw new XmlException("Error while trying to parse from XML: " + str, ex);
}
catch
{
}
}
return null;
}
return base.ConvertFrom(culture, value);
}
public override object ConvertTo(CultureInfo culture, string format, object value, Type to)
{
if (to != typeof(string))
{
return base.ConvertTo(culture, format, value, to);
}
if (value is not null and IEnumerable<GiftCardCouponCode> attributes)
{
var couponCodes = attributes.Select(x => x.Value);
if (!couponCodes.IsNullOrEmpty())
{
return JsonConvert.SerializeObject(couponCodes);
}
}
return null;
}
}
/// <summary>
/// This | GiftCardCouponCodeConverter |
csharp | dotnet__maui | src/Core/tests/UnitTests/Hosting/HostBuilderLoggingTests.cs | {
"start": 275,
"end": 1263
} | public class ____
{
[Fact]
public void GetValidILoggerByDefault()
{
var builder = MauiApp.CreateBuilder();
var mauiApp = builder.Build();
ILogger logger = mauiApp.Services.GetService<ILogger<HostBuilderLoggingTests>>();
Assert.NotNull(logger);
logger.LogError("An error");
}
[Fact]
public void CanAddLoggingProviders()
{
var loggerProvider = new MyLoggerProvider();
var builder = MauiApp.CreateBuilder();
builder
.Logging
.Services
.AddSingleton<ILoggerProvider>(loggerProvider);
var mauiApp = builder.Build();
ILogger logger = mauiApp.Services.GetService<ILogger<HostBuilderLoggingTests>>();
// When running in parallel "build" might generate messages
// from the dispatcher so let's clear those up before starting our test
loggerProvider.Messages.Clear();
logger.LogError("An error");
Assert.Single(loggerProvider.Messages);
Assert.Equal("An error", loggerProvider.Messages[0]);
}
| HostBuilderLoggingTests |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs | {
"start": 669,
"end": 11313
} | public class ____ : BasePublicController
{
#region Constructors
public OutOfStockSubscriptionController(IProductService productService,
IContextAccessor contextAccessor,
IGroupService groupService,
ITranslationService translationService,
IOutOfStockSubscriptionService outOfStockSubscriptionService,
IProductAttributeFormatter productAttributeFormatter,
IStockQuantityService stockQuantityService,
IMediator mediator,
CustomerSettings customerSettings,
ShoppingCartSettings shoppingCartSettings)
{
_productService = productService;
_contextAccessor = contextAccessor;
_groupService = groupService;
_translationService = translationService;
_outOfStockSubscriptionService = outOfStockSubscriptionService;
_productAttributeFormatter = productAttributeFormatter;
_stockQuantityService = stockQuantityService;
_mediator = mediator;
_customerSettings = customerSettings;
_shoppingCartSettings = shoppingCartSettings;
}
#endregion
#region Fields
private readonly IProductService _productService;
private readonly IContextAccessor _contextAccessor;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;
private readonly IProductAttributeFormatter _productAttributeFormatter;
private readonly IStockQuantityService _stockQuantityService;
private readonly IMediator _mediator;
private readonly CustomerSettings _customerSettings;
private readonly ShoppingCartSettings _shoppingCartSettings;
#endregion
#region Methods
[HttpGet]
// Product details page > out of stock subscribe button
public virtual async Task<IActionResult> SubscribeButton(string productId, string warehouseId)
{
var product = await _productService.GetProductById(productId);
if (product == null)
throw new ArgumentException("No product found with the specified id");
var customer = _contextAccessor.WorkContext.CurrentCustomer;
if (!await _groupService.IsRegistered(customer))
return Content(_translationService.GetResource("OutOfStockSubscriptions.OnlyRegistered"));
if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock)
return Content(_translationService.GetResource("OutOfStockSubscriptions.NotifyMeWhenAvailable"));
warehouseId = _shoppingCartSettings.AllowToSelectWarehouse
? string.IsNullOrEmpty(warehouseId) ? "" : warehouseId
: string.IsNullOrEmpty(_contextAccessor.StoreContext.CurrentStore.DefaultWarehouseId)
? product.WarehouseId
: _contextAccessor.StoreContext.CurrentStore.DefaultWarehouseId;
var subscription = await _outOfStockSubscriptionService
.FindSubscription(customer.Id, product.Id, null, _contextAccessor.StoreContext.CurrentStore.Id,
warehouseId);
return Content(subscription != null
? _translationService.GetResource("OutOfStockSubscriptions.DeleteNotifyWhenAvailable")
: _translationService.GetResource("OutOfStockSubscriptions.NotifyMeWhenAvailable"));
}
[HttpPost]
public virtual async Task<IActionResult> SubscribePopup(ProductModel model)
{
var product = await _productService.GetProductById(model.ProductId);
if (product == null)
throw new ArgumentException("No product found with the specified id");
var customer = _contextAccessor.WorkContext.CurrentCustomer;
var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ? model.WarehouseId :
product.UseMultipleWarehouses ? _contextAccessor.StoreContext.CurrentStore.DefaultWarehouseId :
string.IsNullOrEmpty(_contextAccessor.StoreContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
_contextAccessor.StoreContext.CurrentStore.DefaultWarehouseId;
if (!await _groupService.IsRegistered(customer))
return Json(new {
subscribe = false,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.OnlyRegistered"),
resource = _translationService.GetResource("OutOfStockSubscriptions.OnlyRegisteredText")
});
if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&
product.BackorderModeId == BackorderMode.NoBackorders &&
product.AllowOutOfStockSubscriptions &&
_stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId) <= 0)
{
var subscription = await _outOfStockSubscriptionService
.FindSubscription(customer.Id, product.Id, null, _contextAccessor.StoreContext.CurrentStore.Id, warehouseId);
if (subscription != null)
{
//subscription already exists
//unsubscribe
await _outOfStockSubscriptionService.DeleteSubscription(subscription);
return Json(new {
subscribe = false,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.NotifyMeWhenAvailable"),
resource = _translationService.GetResource("OutOfStockSubscriptions.Unsubscribed")
});
}
//subscription does not exist
//subscribe
subscription = new OutOfStockSubscription {
CustomerId = customer.Id,
ProductId = product.Id,
StoreId = _contextAccessor.StoreContext.CurrentStore.Id,
WarehouseId = warehouseId
};
await _outOfStockSubscriptionService.InsertSubscription(subscription);
return Json(new {
subscribe = true,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.DeleteNotifyWhenAvailable"),
resource = _translationService.GetResource("OutOfStockSubscriptions.Subscribed")
});
}
if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes ||
product.BackorderModeId != BackorderMode.NoBackorders ||
!product.AllowOutOfStockSubscriptions)
return Json(new {
subscribe = false,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.NotifyMeWhenAvailable"),
resource = _translationService.GetResource("OutOfStockSubscriptions.NotAllowed")
});
var attributes = await _mediator.Send(new GetParseProductAttributes
{ Product = product, Attributes = model.Attributes });
var subscriptionAttributes = await _outOfStockSubscriptionService
.FindSubscription(customer.Id, product.Id, attributes, _contextAccessor.StoreContext.CurrentStore.Id, warehouseId);
if (subscriptionAttributes != null)
{
//subscription already exists
//unsubscribe
await _outOfStockSubscriptionService.DeleteSubscription(subscriptionAttributes);
return Json(new {
subscribe = false,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.NotifyMeWhenAvailable"),
resource = _translationService.GetResource("OutOfStockSubscriptions.Unsubscribed")
});
}
subscriptionAttributes = new OutOfStockSubscription {
CustomerId = customer.Id,
ProductId = product.Id,
Attributes = attributes,
AttributeInfo = !attributes.Any()
? ""
: await _productAttributeFormatter.FormatAttributes(product, attributes),
StoreId = _contextAccessor.StoreContext.CurrentStore.Id,
WarehouseId = warehouseId
};
await _outOfStockSubscriptionService.InsertSubscription(subscriptionAttributes);
return Json(new {
subscribe = true,
buttontext = _translationService.GetResource("OutOfStockSubscriptions.DeleteNotifyWhenAvailable"),
resource = _translationService.GetResource("OutOfStockSubscriptions.Subscribed")
});
}
// My account / Out of stock subscriptions
[HttpGet]
public virtual async Task<IActionResult> CustomerSubscriptions(int? pageNumber)
{
if (_customerSettings.HideOutOfStockSubscriptionsTab) return RedirectToRoute("CustomerInfo");
var pageIndex = 0;
if (pageNumber > 0) pageIndex = pageNumber.Value - 1;
const int pageSize = 10;
var customer = _contextAccessor.WorkContext.CurrentCustomer;
var list = await _outOfStockSubscriptionService.GetAllSubscriptionsByCustomerId(customer.Id,
_contextAccessor.StoreContext.CurrentStore.Id, pageIndex, pageSize);
var model = new CustomerOutOfStockSubscriptionsModel();
foreach (var subscription in list)
{
var product = await _productService.GetProductById(subscription.ProductId);
if (product == null) continue;
var subscriptionModel = new CustomerOutOfStockSubscriptionsModel.OutOfStockSubscriptionModel {
Id = subscription.Id,
ProductId = product.Id,
ProductName = product.GetTranslation(x => x.Name, _contextAccessor.WorkContext.WorkingLanguage.Id),
AttributeDescription = !subscription.Attributes.Any()
? ""
: await _productAttributeFormatter.FormatAttributes(product, subscription.Attributes),
SeName = product.GetSeName(_contextAccessor.WorkContext.WorkingLanguage.Id)
};
model.Subscriptions.Add(subscriptionModel);
}
model.PagerModel.LoadPagedList(list);
return View(model);
}
[HttpPost]
public virtual async Task<IActionResult> CustomerSubscriptions(string[] subscriptions)
{
foreach (var id in subscriptions)
{
var subscription = await _outOfStockSubscriptionService.GetSubscriptionById(id);
if (subscription != null && subscription.CustomerId == _contextAccessor.WorkContext.CurrentCustomer.Id)
await _outOfStockSubscriptionService.DeleteSubscription(subscription);
}
return RedirectToRoute("CustomerOutOfStockSubscriptions");
}
#endregion
} | OutOfStockSubscriptionController |
csharp | Antaris__RazorEngine | src/source/RazorEngine.Core/Templating/InstanceContext.cs | {
"start": 200,
"end": 1111
} | public class ____
{
#region Constructor
/// <summary>
/// Initialises a new instance of <see cref="InstanceContext"/>.
/// </summary>
/// <param name="loader">The type loader.</param>
/// <param name="templateType">The template type.</param>
internal InstanceContext(TypeLoader loader, Type templateType)
{
Contract.Requires(loader != null);
Contract.Requires(templateType != null);
Loader = loader;
TemplateType = templateType;
}
#endregion
#region Properties
/// <summary>
/// Gets the type loader.
/// </summary>
public TypeLoader Loader { get; private set; }
/// <summary>
/// Gets the template type.
/// </summary>
public Type TemplateType { get; private set; }
#endregion
}
} | InstanceContext |
csharp | dotnet__orleans | src/Orleans.Serialization/Buffers/ArcBufferWriter.cs | {
"start": 44414,
"end": 46479
} | public struct ____(ArcBuffer slice) : IEnumerable<ReadOnlyMemory<byte>>, IEnumerator<ReadOnlyMemory<byte>>
{
private PageSegmentEnumerator _enumerator = slice.PageSegments;
/// <summary>
/// Gets this instance as an enumerator.
/// </summary>
/// <returns>This instance.</returns>
public readonly MemoryEnumerator GetEnumerator() => this;
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
public ReadOnlyMemory<byte> Current { get; private set; }
/// <inheritdoc/>
readonly object? IEnumerator.Current => Current;
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns><see langword="true"/> if the enumerator was successfully advanced to the next element; <see langword="false"/> if the enumerator has passed the end of the collection.</returns>
public bool MoveNext()
{
if (_enumerator.MoveNext())
{
Current = _enumerator.Current.Memory;
return true;
}
Current = default;
return false;
}
/// <inheritdoc/>
readonly IEnumerator<ReadOnlyMemory<byte>> IEnumerable<ReadOnlyMemory<byte>>.GetEnumerator() => GetEnumerator();
/// <inheritdoc/>
readonly IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc/>
void IEnumerator.Reset()
{
_enumerator = _enumerator.Slice.PageSegments;
Current = default;
}
/// <inheritdoc/>
readonly void IDisposable.Dispose() { }
}
/// <summary>
/// Enumerates over array segments in a <see cref="ArcBuffer"/>.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="ArraySegmentEnumerator"/> type.
/// </remarks>
/// <param name="slice">The slice to enumerate.</param>
| MemoryEnumerator |
csharp | Cysharp__MemoryPack | sandbox/SandboxConsoleApp/ForReadMe.cs | {
"start": 888,
"end": 1320
} | public partial class ____
{
public int Age { get; set; }
public string Name { get; set; }
public Person3()
{
this.Age = 0;
this.Name = "";
}
// If exists multiple constructors, must use [MemoryPackConstructor]
[MemoryPackConstructor]
public Person3(int age, string name)
{
this.Age = age;
this.Name = name;
}
}
[MemoryPackable(GenerateType.Collection)]
| Person3 |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Middleware/Configuration/Consume/IMessageConsumePipeSpecification.cs | {
"start": 490,
"end": 724
} | public interface ____ :
IPipeConfigurator<ConsumeContext>,
ISpecification
{
IMessageConsumePipeSpecification<T> GetMessageSpecification<T>()
where T : class;
}
}
| IMessageConsumePipeSpecification |
csharp | MassTransit__MassTransit | src/MassTransit/Testing/Implementations/AsyncElementList.cs | {
"start": 268,
"end": 6983
} | public abstract class ____<TElement> :
IAsyncElementList<TElement>
where TElement : class, IAsyncListElement
{
readonly Connectable<Channel<TElement>> _channels;
readonly IDictionary<Guid, TElement> _messageLookup;
readonly List<TElement> _messages;
readonly CancellationToken _testCompleted;
readonly TimeSpan _timeout;
protected AsyncElementList(TimeSpan timeout, CancellationToken testCompleted = default)
{
_timeout = timeout;
_testCompleted = testCompleted;
_messages = new List<TElement>();
_messageLookup = new Dictionary<Guid, TElement>();
_channels = new Connectable<Channel<TElement>>();
}
public async IAsyncEnumerable<TElement> SelectAsync(FilterDelegate<TElement> filter,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var channel = Channel.CreateUnbounded<TElement>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false
});
var handle = _channels.Connect(channel);
var returned = new HashSet<Guid>();
try
{
var index = 0;
TElement[] messages;
lock (_messages)
messages = _messages.ToArray();
for (; index < messages.Length; index++)
{
var entry = messages[index];
var elementId = entry.ElementId.Value;
if (filter(entry) && !returned.Contains(elementId))
{
returned.Add(elementId);
yield return entry;
}
}
if (cancellationToken.IsCancellationRequested || _testCompleted.IsCancellationRequested)
yield break;
using var timeout = new CancellationTokenSource(_timeout);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _testCompleted, cancellationToken);
while (!linked.IsCancellationRequested)
{
try
{
await channel.Reader.WaitToReadAsync(linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
if (!channel.Reader.TryRead(out _))
break;
lock (_messages)
messages = _messages.ToArray();
for (; index < messages.Length; index++)
{
var entry = messages[index];
var elementId = entry.ElementId.Value;
if (filter(entry) && !returned.Contains(elementId))
{
returned.Add(elementId);
yield return entry;
}
}
}
}
finally
{
handle.Disconnect();
channel.Writer.TryComplete();
}
}
public async Task<bool> Any(FilterDelegate<TElement> filter, CancellationToken cancellationToken = default)
{
try
{
await foreach (var _ in SelectAsync(filter, cancellationToken).ConfigureAwait(false))
return true;
}
catch (OperationCanceledException)
{
}
return false;
}
public IEnumerable<TElement> Select(FilterDelegate<TElement> filter, CancellationToken cancellationToken = default)
{
lock (_messages)
{
var index = 0;
for (; index < _messages.Count; index++)
{
var entry = _messages[index];
if (filter(entry))
yield return entry;
}
if (cancellationToken.IsCancellationRequested || _testCompleted.IsCancellationRequested)
yield break;
var monitorTimeout = _timeout;
var endTime = DateTime.Now + monitorTimeout;
void Cancel()
{
endTime = DateTime.Now;
lock (_messages)
Monitor.PulseAll(_messages);
}
CancellationTokenRegistration cancellationTokenRegistration = default;
if (cancellationToken.CanBeCanceled)
cancellationTokenRegistration = cancellationToken.Register(() => Cancel());
CancellationTokenRegistration timeoutTokenRegistration = default;
if (_testCompleted.CanBeCanceled)
timeoutTokenRegistration = _testCompleted.Register(() => Cancel());
try
{
while (Monitor.Wait(_messages, monitorTimeout))
{
for (; index < _messages.Count; index++)
{
var element = _messages[index];
if (filter(element))
yield return element;
}
monitorTimeout = endTime - DateTime.Now;
if (monitorTimeout <= TimeSpan.Zero)
break;
if (cancellationToken.IsCancellationRequested || _testCompleted.IsCancellationRequested)
yield break;
}
}
finally
{
cancellationTokenRegistration.Dispose();
timeoutTokenRegistration.Dispose();
}
}
}
protected void Add(TElement context)
{
if (!context.ElementId.HasValue)
return;
lock (_messages)
{
var elementId = context.ElementId.Value;
if (_messageLookup.ContainsKey(elementId))
return;
_messages.Add(context);
_messageLookup.Add(elementId, context);
Monitor.PulseAll(_messages);
}
_channels.ForEach(channel => channel.Writer.TryWrite(context));
}
}
}
| AsyncElementList |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterVerifyTests.cs | {
"start": 4083,
"end": 4669
} | public class ____
{
[Params(2, 10), UsedImplicitly] public int Param;
[Benchmark, BenchmarkCategory("CatA")] public void Base() { }
[Benchmark, BenchmarkCategory("CatB")] public void Foo() { }
[Benchmark, BenchmarkCategory("CatB")] public void Bar() { }
}
[RankColumn, LogicalGroupColumn, BaselineColumn]
[SimpleJob(id: "Job1"), SimpleJob(id: "Job2")]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
| NoBaseline_MethodsParamsJobs_GroupByParams |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/ElectionsService/ElectionsServiceTests.cs | {
"start": 67088,
"end": 68357
} | public class ____ : ElectionsFixture {
public when_electing_a_leader_and_best_candidate_node_is_dead_in_gossip_info_of_leader_of_elections() :
base(NodeFactory(3), NodeFactory(2), NodeFactory(1)) {
_sut.Handle(new GossipMessage.GossipUpdated(new ClusterInfo(
MemberInfoFromVNode(_node, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0),
MemberInfoFromVNode(_nodeTwo, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0),
MemberInfoFromVNode(_nodeThree, _timeProvider.UtcNow, VNodeState.Unknown, false, 0, _epochId, 0))));
_sut.Handle(new ElectionMessage.StartElections());
_sut.Handle(new ElectionMessage.ViewChange(_nodeThree.InstanceId, _nodeThree.HttpEndPoint, 0));
_sut.Handle(new ElectionMessage.PrepareOk(0, _nodeThree.InstanceId, _nodeThree.HttpEndPoint, 10, 0,
_epochId, _nodeThree.InstanceId, 0, 0, 0, 0, new ClusterInfo()));
_publisher.Messages.Clear();
_sut.Handle(new ElectionMessage.Accept(_nodeTwo.InstanceId, _nodeTwo.HttpEndPoint,
_nodeThree.InstanceId, _nodeThree.HttpEndPoint, 0));
}
[Test]
public void no_leader_should_be_elected() {
Assert.AreEqual(0, _publisher.Messages.ToArray().Length);
}
}
| when_electing_a_leader_and_best_candidate_node_is_dead_in_gossip_info_of_leader_of_elections |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/PersonConverter.cs | {
"start": 1489,
"end": 1678
} | public class ____ : CustomCreationConverter<IPerson>
{
public override IPerson Create(Type objectType)
{
return new Employee();
}
}
}
| PersonConverter |
csharp | abpframework__abp | framework/test/Volo.Abp.MongoDB.Tests/Volo/Abp/MongoDB/Uow/UnitOfWork_CancellationToken_Tests.cs | {
"start": 273,
"end": 923
} | public class ____ : TestAppTestBase<AbpMongoDbTestModule>
{
[Fact]
public async Task Should_Cancel_Test()
{
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin(isTransactional: true))
{
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
var cst = new CancellationTokenSource();
cst.Cancel();
await GetRequiredService<IBasicRepository<Person, Guid>>().InsertAsync(new Person(Guid.NewGuid(), "Adam", 42));
await uow.CompleteAsync(cst.Token);
});
}
}
}
| UnitOfWork_CancellationToken_Tests |
csharp | npgsql__npgsql | test/Npgsql.Tests/SecurityTests.cs | {
"start": 361,
"end": 23122
} | public class ____ : TestBase
{
[Test, Description("Establishes an SSL connection, assuming a self-signed server certificate")]
public async Task Basic_ssl()
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.True);
}
[Test, Description("Default user must run with md5 password encryption")]
public async Task Default_user_uses_md5_password()
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.False);
}
[Test, Description("Makes sure a certificate whose root CA isn't known isn't accepted")]
public void Reject_self_signed_certificate([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
SslMode = sslMode,
CheckCertificateRevocation = false,
};
using var _ = CreateTempPool(csb, out var connString);
using var conn = new NpgsqlConnection(connString);
var ex = Assert.Throws<NpgsqlException>(conn.Open)!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
[Test, Description("Makes sure that ssl_renegotiation_limit is always 0, renegotiation is buggy")]
public void No_ssl_renegotiation()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
using var conn = dataSource.OpenConnection();
Assert.That(conn.ExecuteScalar("SHOW ssl_renegotiation_limit"), Is.EqualTo("0"));
conn.ExecuteNonQuery("DISCARD ALL");
Assert.That(conn.ExecuteScalar("SHOW ssl_renegotiation_limit"), Is.EqualTo("0"));
}
[Test, Description("Makes sure that when SSL is disabled IsSecure returns false")]
public void IsSecure_without_ssl()
{
using var dataSource = CreateDataSource(csb => csb.SslMode = SslMode.Disable);
using var conn = dataSource.OpenConnection();
Assert.That(conn.IsSslEncrypted, Is.False);
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void IntegratedSecurity_with_Username()
{
var username = Environment.UserName;
if (username == null)
throw new Exception("Could find username");
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = username,
Password = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void IntegratedSecurity_without_Username()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = null,
Password = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void Connection_database_is_populated_on_Open()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = null,
Password = null,
Database = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
Assert.That(conn.Database, Is.Not.Null);
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/1718")]
public void Bug1718()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
using var conn = dataSource.OpenConnection();
using var tx = conn.BeginTransaction();
using var cmd = CreateSleepCommand(conn, 10000);
var cts = new CancellationTokenSource(1000).Token;
Assert.That(async () => await cmd.ExecuteNonQueryAsync(cts), Throws.Exception
.TypeOf<OperationCanceledException>()
.With.InnerException.TypeOf<PostgresException>()
.With.InnerException.Property(nameof(PostgresException.SqlState)).EqualTo(PostgresErrorCodes.QueryCanceled));
}
[Test]
public void ScramPlus()
{
try
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_scram";
csb.Password = "npgsql_tests_scram";
});
using var conn = dataSource.OpenConnection();
// scram-sha-256-plus only works beginning from PostgreSQL 11
if (conn.PostgreSqlVersion.Major >= 11)
{
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.True);
}
else
{
Assert.That(conn.IsScram, Is.True);
Assert.That(conn.IsScramPlus, Is.False);
}
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("scram-sha-256-plus doesn't seem to be set up");
}
}
[Test]
public void ScramPlus_channel_binding([Values] ChannelBinding channelBinding)
{
try
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_scram";
csb.Password = "npgsql_tests_scram";
csb.ChannelBinding = channelBinding;
});
// scram-sha-256-plus only works beginning from PostgreSQL 11
MinimumPgVersion(dataSource, "11.0");
using var conn = dataSource.OpenConnection();
if (channelBinding == ChannelBinding.Disable)
{
Assert.That(conn.IsScram, Is.True);
Assert.That(conn.IsScramPlus, Is.False);
}
else
{
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.True);
}
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("scram-sha-256-plus doesn't seem to be set up");
}
}
[Test]
public async Task Connect_with_only_ssl_allowed_user([Values] bool multiplexing, [Values] bool keepAlive)
{
if (multiplexing && keepAlive)
{
Assert.Ignore("Multiplexing doesn't support keepalive");
}
try
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Allow;
csb.Username = "npgsql_tests_ssl";
csb.Password = "npgsql_tests_ssl";
csb.Multiplexing = multiplexing;
csb.KeepAlive = keepAlive ? 10 : 0;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only ssl user doesn't seem to be set up");
}
}
[Test]
[Platform(Exclude = "Win", Reason = "Postgresql doesn't close connection correctly on windows which might result in missing error message")]
public async Task Connect_with_only_non_ssl_allowed_user([Values] bool multiplexing, [Values] bool keepAlive)
{
if (multiplexing && keepAlive)
{
Assert.Ignore("Multiplexing doesn't support keepalive");
}
try
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Prefer;
csb.Username = "npgsql_tests_nossl";
csb.Password = "npgsql_tests_nossl";
csb.Multiplexing = multiplexing;
csb.KeepAlive = keepAlive ? 10 : 0;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.False);
}
catch (NpgsqlException ex) when (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && ex.InnerException is IOException)
{
// Windows server to windows client invites races that can cause the socket to be reset before all data can be read.
// https://www.postgresql.org/message-id/flat/90b34057-4176-7bb0-0dbb-9822a5f6425b%40greiz-reinsdorf.de
// https://www.postgresql.org/message-id/flat/16678-253e48d34dc0c376@postgresql.org
Assert.Ignore();
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only nonssl user doesn't seem to be set up");
}
}
[Test]
public async Task DataSource_SslClientAuthenticationOptionsCallback_is_invoked([Values] bool acceptCertificate)
{
var callbackWasInvoked = false;
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = SslMode.Require;
dataSourceBuilder.UseSslClientAuthenticationOptionsCallback(options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) =>
{
callbackWasInvoked = true;
return acceptCertificate;
};
});
await using var dataSource = dataSourceBuilder.Build();
await using var connection = dataSource.CreateConnection();
if (acceptCertificate)
Assert.DoesNotThrowAsync(async () => await connection.OpenAsync());
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await connection.OpenAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
Assert.That(callbackWasInvoked);
}
[Test]
public async Task Connection_SslClientAuthenticationOptionsCallback_is_invoked([Values] bool acceptCertificate)
{
var callbackWasInvoked = false;
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = SslMode.Require;
await using var dataSource = dataSourceBuilder.Build();
await using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) =>
{
callbackWasInvoked = true;
return acceptCertificate;
};
};
if (acceptCertificate)
Assert.DoesNotThrowAsync(async () => await connection.OpenAsync());
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await connection.OpenAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
Assert.That(callbackWasInvoked);
}
[Test]
public void Connect_with_Verify_and_callback_throws([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
using var dataSource = CreateDataSource(csb => csb.SslMode = sslMode);
using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
};
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await connection.OpenAsync())!;
Assert.That(ex.Message, Is.EqualTo(string.Format(NpgsqlStrings.CannotUseSslVerifyWithCustomValidationCallback, sslMode)));
}
[Test]
public void Connect_with_RootCertificate_and_callback_throws()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.RootCertificate = "foo";
});
using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
};
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await connection.OpenAsync())!;
Assert.That(ex.Message, Is.EqualTo(string.Format(NpgsqlStrings.CannotUseSslRootCertificateWithCustomValidationCallback)));
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4305")]
public async Task Bug4305_Secure([Values] bool async)
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_ssl";
csb.Password = "npgsql_tests_ssl";
csb.MaxPoolSize = 1;
});
NpgsqlConnection conn = default!;
try
{
conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only ssl user doesn't seem to be set up");
}
await using var __ = conn;
await using var cmd = conn.CreateCommand();
await using (var tx = await conn.BeginTransactionAsync())
{
var originalConnector = conn.Connector;
cmd.CommandText = "select pg_sleep(30)";
cmd.CommandTimeout = 3;
var ex = async
? Assert.ThrowsAsync<NpgsqlException>(() => cmd.ExecuteNonQueryAsync())!
: Assert.Throws<NpgsqlException>(() => cmd.ExecuteNonQuery())!;
Assert.That(ex.InnerException, Is.TypeOf<TimeoutException>());
await conn.CloseAsync();
await conn.OpenAsync();
Assert.That(conn.Connector, Is.SameAs(originalConnector));
}
cmd.CommandText = "SELECT 1";
if (async)
Assert.DoesNotThrowAsync(async () => await cmd.ExecuteNonQueryAsync());
else
Assert.DoesNotThrow(() => cmd.ExecuteNonQuery());
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4305")]
public async Task Bug4305_not_Secure([Values] bool async)
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Disable;
csb.Username = "npgsql_tests_nossl";
csb.Password = "npgsql_tests_nossl";
csb.MaxPoolSize = 1;
});
NpgsqlConnection conn = default!;
try
{
conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.False);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only nossl user doesn't seem to be set up");
}
await using var __ = conn;
var originalConnector = conn.Connector;
await using var cmd = conn.CreateCommand();
cmd.CommandText = "select pg_sleep(30)";
cmd.CommandTimeout = 3;
var ex = async
? Assert.ThrowsAsync<NpgsqlException>(() => cmd.ExecuteNonQueryAsync())!
: Assert.Throws<NpgsqlException>(() => cmd.ExecuteNonQuery())!;
Assert.That(ex.InnerException, Is.TypeOf<TimeoutException>());
await conn.CloseAsync();
await conn.OpenAsync();
Assert.That(conn.Connector, Is.SameAs(originalConnector));
cmd.CommandText = "SELECT 1";
if (async)
Assert.DoesNotThrowAsync(async () => await cmd.ExecuteNonQueryAsync());
else
Assert.DoesNotThrow(() => cmd.ExecuteNonQuery());
}
[Test]
public async Task Direct_ssl_negotiation()
{
await using var adminConn = await OpenConnectionAsync();
MinimumPgVersion(adminConn, "17.0");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.SslNegotiation = SslNegotiation.Direct;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
[Test]
public void Direct_ssl_requires_correct_sslmode([Values] SslMode sslMode)
{
if (sslMode is SslMode.Disable or SslMode.Allow or SslMode.Prefer)
{
var ex = Assert.Throws<ArgumentException>(() =>
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.SslNegotiation = SslNegotiation.Direct;
});
})!;
Assert.That(ex.Message, Is.EqualTo("SSL Mode has to be Require or higher to be used with direct SSL Negotiation"));
}
else
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.SslNegotiation = SslNegotiation.Direct;
});
}
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_and_ca_cert([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.RootCertificate = "ca.crt";
});
await using var _ = await dataSource.OpenConnectionAsync();
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_check_host([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.Host = "127.0.0.1";
csb.SslMode = sslMode;
csb.RootCertificate = "ca.crt";
});
if (sslMode == SslMode.VerifyCA)
{
await using var _ = await dataSource.OpenConnectionAsync();
}
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await dataSource.OpenConnectionAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_and_multiple_ca_cert([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode, [Values] bool realCaFirst)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
var certificates = new X509Certificate2Collection();
using var realCaCert = X509CertificateLoader.LoadCertificateFromFile("ca.crt");
using var ecdsa = ECDsa.Create();
var req = new CertificateRequest("cn=localhost", ecdsa, HashAlgorithmName.SHA256);
using var unrelatedCaCert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
if (realCaFirst)
{
certificates.Add(realCaCert);
certificates.Add(unrelatedCaCert);
}
else
{
certificates.Add(unrelatedCaCert);
certificates.Add(realCaCert);
}
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = sslMode;
dataSourceBuilder.UseRootCertificates(certificates);
await using var dataSource = dataSourceBuilder.Build();
await using var _ = await dataSource.OpenConnectionAsync();
}
[Test]
[NonParallelizable] // Sets environment variable
public async Task Direct_ssl_via_env_requires_correct_sslmode()
{
await using var adminConn = await OpenConnectionAsync();
MinimumPgVersion(adminConn, "17.0");
// NonParallelizable attribute doesn't work with parameters that well
foreach (var sslMode in new[] { SslMode.Disable, SslMode.Allow, SslMode.Prefer, SslMode.Require })
{
using var _ = SetEnvironmentVariable("PGSSLNEGOTIATION", nameof(SslNegotiation.Direct));
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
});
if (sslMode is SslMode.Disable or SslMode.Allow or SslMode.Prefer)
{
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await dataSource.OpenConnectionAsync())!;
Assert.That(ex.Message, Is.EqualTo("SSL Mode has to be Require or higher to be used with direct SSL Negotiation"));
}
else
{
await using var conn = await dataSource.OpenConnectionAsync();
}
}
}
#region Setup / Teardown / Utils
[OneTimeSetUp]
public void CheckSslSupport()
{
using var conn = OpenConnection();
var sslSupport = (string)conn.ExecuteScalar("SHOW ssl")!;
if (sslSupport == "off")
IgnoreExceptOnBuildServer("SSL support isn't enabled at the backend");
}
#endregion
}
| SecurityTests |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Admin.Application.Contracts/Volo/CmsKit/Admin/Tags/EntityTagSetDto.cs | {
"start": 330,
"end": 1142
} | public class ____ : IValidatableObject
{
public string EntityId { get; set; }
public string EntityType { get; set; }
[Required]
public List<string> Tags { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var l = validationContext.GetRequiredService<IStringLocalizer<AbpValidationResource>>();
foreach (var tag in Tags)
{
if (tag.Length > TagConsts.MaxNameLength)
{
yield return new ValidationResult(
l[
"ThisFieldMustBeAStringWithAMaximumLengthOf{0}",
TagConsts.MaxNameLength
],
new[] { nameof(Tags) }
);
}
}
}
}
| EntityTagSetDto |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/Query/AdHocAdvancedMappingsQueryTestBase.cs | {
"start": 6653,
"end": 8069
} | public enum ____
{
Active = 0,
Removed = 1
}
}
#endregion
#region 17276
[ConditionalFact]
public virtual async Task Expression_tree_constructed_via_interface_works()
{
var contextFactory = await InitializeAsync<Context17276>();
using (var context = contextFactory.CreateContext())
{
var query = Context17276.List(context.RemovableEntities);
}
using (var context = contextFactory.CreateContext())
{
var query = context.Parents
.Where(p => EF.Property<bool>(EF.Property<Context17276.IRemovable>(p, "RemovableEntity"), "IsRemoved"))
.ToList();
}
using (var context = contextFactory.CreateContext())
{
var query = context.RemovableEntities
.Where(p => EF.Property<string>(EF.Property<Context17276.IOwned>(p, "OwnedEntity"), "OwnedValue") == "Abc")
.ToList();
}
using (var context = contextFactory.CreateContext())
{
var specification = new Context17276.Specification<Context17276.Parent>(1);
var entities = context.Set<Context17276.Parent>().Where(specification.Criteria).ToList();
}
}
// Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed.
| CategoryStatus |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterAttributeTest.cs | {
"start": 1446,
"end": 1695
} | private class ____
{
public static Action<IApplicationBuilder> ConfigurePipeline { get; set; }
public void Configure(IApplicationBuilder appBuilder)
{
ConfigurePipeline(appBuilder);
}
}
| Pipeline1 |
csharp | dotnet__efcore | test/EFCore.Cosmos.FunctionalTests/AddHocFullTextSearchCosmosTest.cs | {
"start": 6772,
"end": 8344
} | public class ____
{
public int Id { get; set; }
public string PartitionKey { get; set; } = null!;
public string Name { get; set; } = null!;
public int Number { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultFullTextLanguage("pl-PL");
modelBuilder.Entity<Entity1>(b =>
{
b.ToContainer("Entities");
b.HasPartitionKey(x => x.PartitionKey);
b.Property(x => x.Name).EnableFullTextSearch();
b.HasIndex(x => x.Name).IsFullTextIndex();
});
modelBuilder.Entity<Entity2>(b =>
{
b.ToContainer("Entities");
b.HasPartitionKey(x => x.PartitionKey);
b.Property(x => x.Name).EnableFullTextSearch();
b.HasIndex(x => x.Name).IsFullTextIndex();
});
}
}
#endregion
#region DefaultFullTextSearchLanguageNoMismatchWhenNotSpecified
[ConditionalFact]
public async Task
Explicitly_setting_default_full_text_language_doesnt_clash_with_not_setting_it_on_other_entity_for_the_same_container()
{
var exception =
(await Assert.ThrowsAsync<CosmosException>(()
=> InitializeAsync<ContextDefaultFullTextSearchLanguageNoMismatchWhenNotSpecified>()));
Assert.Contains("The Full Text Policy contains an unsupported language xx-YY.", exception.Message);
}
| Entity2 |
csharp | atata-framework__atata | src/Atata/ScopeSearch/Strategies/IItemElementFindStrategy.cs | {
"start": 19,
"end": 208
} | public interface ____
{
string GetXPathCondition(object parameter, TermOptions termOptions);
T GetParameter<T>(IWebElement element, TermOptions termOptions);
}
| IItemElementFindStrategy |
csharp | dotnet__aspnetcore | src/Http/Routing/src/ShortCircuit/RouteShortCircuitEndpointRouteBuilderExtensions.cs | {
"start": 2089,
"end": 2735
} | private sealed class ____ : IEndpointConventionBuilder
{
private readonly IEndpointConventionBuilder _endpointConventionBuilder;
public EndpointConventionBuilder(IEndpointConventionBuilder endpointConventionBuilder)
{
_endpointConventionBuilder = endpointConventionBuilder;
}
public void Add(Action<EndpointBuilder> convention)
{
_endpointConventionBuilder.Add(convention);
}
public void Finally(Action<EndpointBuilder> finalConvention)
{
_endpointConventionBuilder.Finally(finalConvention);
}
}
}
| EndpointConventionBuilder |
csharp | duplicati__duplicati | Duplicati/Library/RestAPI/UpdatePollThread.cs | {
"start": 1497,
"end": 9260
} | public class ____(Connection connection, EventPollNotify eventPollNotify)
{
private Thread m_thread;
private volatile bool m_terminated = false;
private volatile bool m_forceCheck = false;
private readonly object m_lock = new object();
private AutoResetEvent m_waitSignal;
private double m_downloadProgress;
private bool m_disableChecks = false;
public bool IsUpdateRequested { get; private set; } = false;
public UpdatePollerStates ThreadState { get; private set; }
public double DownloadProgess
{
get { return m_downloadProgress; }
private set
{
var oldv = m_downloadProgress;
m_downloadProgress = value;
if ((int)(oldv * 100) != (int)(value * 100))
eventPollNotify.SignalNewEvent();
}
}
public void Init(bool disableChecks)
{
m_disableChecks = disableChecks;
m_waitSignal = new AutoResetEvent(false);
ThreadState = UpdatePollerStates.Waiting;
m_thread = new Thread(Run)
{
IsBackground = true,
Name = "UpdatePollThread"
};
m_thread.Start();
}
public void CheckNow()
{
lock (m_lock)
{
m_forceCheck = true;
m_waitSignal.Set();
}
}
public void Terminate()
{
lock (m_lock)
{
m_terminated = true;
m_waitSignal.Set();
}
}
public void Reschedule()
{
m_waitSignal.Set();
}
private void Run()
{
// Wait on startup
m_waitSignal.WaitOne(TimeSpan.FromMinutes(1), true);
while (!m_terminated)
{
var nextCheck = connection.ApplicationSettings.NextUpdateCheck;
var maxcheck = TimeSpan.FromDays(7);
try
{
maxcheck = Library.Utility.Timeparser.ParseTimeSpan(connection.ApplicationSettings.UpdateCheckInterval);
}
catch
{
}
// If we have some weirdness, just check now
if (nextCheck - DateTime.UtcNow > maxcheck)
nextCheck = DateTime.UtcNow - TimeSpan.FromSeconds(1);
if (nextCheck < DateTime.UtcNow || m_forceCheck)
{
DateTime started = DateTime.UtcNow;
connection.ApplicationSettings.LastUpdateCheck = started;
nextCheck = connection.ApplicationSettings.NextUpdateCheck;
// If this is not forced, and we have disabled checks, we just update the next check time
if (m_disableChecks && !m_forceCheck)
continue;
lock (m_lock)
m_forceCheck = false;
ThreadState = UpdatePollerStates.Checking;
eventPollNotify.SignalNewEvent();
if (!Enum.TryParse<ReleaseType>(connection.ApplicationSettings.UpdateChannel, true, out var rt))
rt = ReleaseType.Unknown;
// Choose the default channel in case we have unknown
rt = rt == ReleaseType.Unknown ? AutoUpdateSettings.DefaultUpdateChannel : rt;
try
{
var update = UpdaterManager.CheckForUpdate(rt);
if (update != null)
connection.ApplicationSettings.UpdatedVersion = update;
}
catch
{
}
// It could be that we have registered an update from a more unstable channel,
// but the user has switched to a more stable channel.
// In that case we discard the old update to avoid offering it.
if (connection.ApplicationSettings.UpdatedVersion != null)
{
Library.AutoUpdater.ReleaseType updatert;
var updatertstring = connection.ApplicationSettings.UpdatedVersion.ReleaseType;
if (string.Equals(updatertstring, "preview", StringComparison.OrdinalIgnoreCase))
updatertstring = Library.AutoUpdater.ReleaseType.Experimental.ToString();
if (!Enum.TryParse<Library.AutoUpdater.ReleaseType>(updatertstring, true, out updatert))
updatert = Duplicati.Library.AutoUpdater.ReleaseType.Nightly;
if (updatert == Duplicati.Library.AutoUpdater.ReleaseType.Unknown)
updatert = Duplicati.Library.AutoUpdater.ReleaseType.Nightly;
if (updatert > rt)
connection.ApplicationSettings.UpdatedVersion = null;
}
// If the update is the same or older than the current version, we discard it
// NOTE: This check is also inside the UpdaterManager.CheckForUpdate method,
// but we may have a stale version recorded, so we force-clear it here
if (connection.ApplicationSettings.UpdatedVersion != null)
{
if (UpdaterManager.TryParseVersion(connection.ApplicationSettings.UpdatedVersion.Version) <= UpdaterManager.TryParseVersion(UpdaterManager.SelfVersion.Version))
connection.ApplicationSettings.UpdatedVersion = null;
}
var updatedinfo = connection.ApplicationSettings.UpdatedVersion;
if (updatedinfo != null && UpdaterManager.TryParseVersion(updatedinfo.Version) > UpdaterManager.TryParseVersion(UpdaterManager.SelfVersion.Version))
{
var package = updatedinfo.FindPackage();
connection.RegisterNotification(
NotificationType.Information,
"Found update",
updatedinfo.Displayname,
null,
null,
"update:new",
null,
"NewUpdateFound",
null,
(self, all) =>
{
return all.FirstOrDefault(x => x.Action == "update:new") ?? self;
}
);
}
}
DownloadProgess = 0;
if (ThreadState != UpdatePollerStates.Waiting)
{
ThreadState = UpdatePollerStates.Waiting;
eventPollNotify.SignalNewEvent();
}
var waitTime = nextCheck - DateTime.UtcNow;
// Guard against spin-loop
if (waitTime.TotalSeconds < 5)
waitTime = TimeSpan.FromSeconds(5);
// Guard against year-long waits
// A re-check does not cause an update check
if (waitTime.TotalDays > 1)
waitTime = TimeSpan.FromDays(1);
m_waitSignal.WaitOne(waitTime, true);
}
}
}
}
| UpdatePollThread |
csharp | grandnode__grandnode2 | src/Tests/Grand.Business.Common.Tests/Services/Security/AclServiceTest.cs | {
"start": 241,
"end": 1316
} | public class ____
{
private AccessControlConfig _accessControlConfig;
private AclService _aclService;
private CatalogSettings _settings;
[TestInitialize]
public void Init()
{
_settings = new CatalogSettings();
_accessControlConfig = new AccessControlConfig();
_aclService = new AclService(_accessControlConfig);
}
[TestMethod]
public void Authorize_ReturnFalse()
{
Product product = null;
Assert.IsFalse(_aclService.Authorize(product, "id"));
product = new Product {
LimitedToStores = true
};
Assert.IsFalse(_aclService.Authorize(product, "id"));
}
[TestMethod]
public void Authorize_ReturnTrue()
{
var product = new Product {
LimitedToStores = false
};
Assert.IsTrue(_aclService.Authorize(product, "id"));
Assert.IsTrue(_aclService.Authorize(product, ""));
_accessControlConfig.IgnoreStoreLimitations = true;
Assert.IsTrue(_aclService.Authorize(product, "id"));
}
} | AclServiceTest |
csharp | microsoft__semantic-kernel | dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAITextToImageTests.cs | {
"start": 438,
"end": 3546
} | public sealed class ____
{
private readonly IConfigurationRoot _configuration = new ConfigurationBuilder()
.AddJsonFile(path: "testsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile(path: "testsettings.development.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddUserSecrets<OpenAITextToImageTests>()
.Build();
[Theory(Skip = "This test is for manual verification.")]
[InlineData("dall-e-2", 512, 512)]
[InlineData("dall-e-3", 1024, 1024)]
public async Task OpenAITextToImageByModelTestAsync(string modelId, int width, int height)
{
// Arrange
OpenAIConfiguration? openAIConfiguration = this._configuration.GetSection("OpenAITextToImage").Get<OpenAIConfiguration>();
Assert.NotNull(openAIConfiguration);
var kernel = Kernel.CreateBuilder()
.AddOpenAITextToImage(apiKey: openAIConfiguration.ApiKey, modelId: modelId)
.Build();
var service = kernel.GetRequiredService<ITextToImageService>();
// Act
var result = await service.GenerateImageAsync("The sun rises in the east and sets in the west.", width, height);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
[Fact(Skip = "Failing in integration tests pipeline with - HTTP 400 (invalid_request_error: billing_hard_limit_reached) error.")]
public async Task OpenAITextToImageUseDallE2ByDefaultAsync()
{
// Arrange
OpenAIConfiguration? openAIConfiguration = this._configuration.GetSection("OpenAITextToImage").Get<OpenAIConfiguration>();
Assert.NotNull(openAIConfiguration);
var kernel = Kernel.CreateBuilder()
.AddOpenAITextToImage(apiKey: openAIConfiguration.ApiKey)
.Build();
var service = kernel.GetRequiredService<ITextToImageService>();
// Act
var result = await service.GenerateImageAsync("The sun rises in the east and sets in the west.", 256, 256);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
[Fact(Skip = "Failing in integration tests pipeline with - HTTP 400 (invalid_request_error: billing_hard_limit_reached) error.")]
public async Task OpenAITextToImageDalle3GetImagesTestAsync()
{
// Arrange
OpenAIConfiguration? openAIConfiguration = this._configuration.GetSection("OpenAITextToImage").Get<OpenAIConfiguration>();
Assert.NotNull(openAIConfiguration);
var kernel = Kernel.CreateBuilder()
.AddOpenAITextToImage(apiKey: openAIConfiguration.ApiKey, modelId: "dall-e-3")
.Build();
var service = kernel.GetRequiredService<ITextToImageService>();
// Act
var result = await service.GetImageContentsAsync("The sun rises in the east and sets in the west.", new OpenAITextToImageExecutionSettings { Size = (1024, 1024) });
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.NotEmpty(result[0].Uri!.ToString());
}
}
| OpenAITextToImageTests |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/AggregateFluentGraphLookupWithEmployeeCollectionTests.cs | {
"start": 16607,
"end": 17684
} | private class ____ : IEqualityComparer<BsonDocument>
{
private readonly IEqualityComparer<IEnumerable<BsonDocument>> _reportingHierarchyComparer = new EnumerableSetEqualityComparer<BsonDocument>(new EqualsEqualityComparer<BsonDocument>());
public bool Equals(BsonDocument x, BsonDocument y)
{
if (!x.Names.SequenceEqual(y.Names))
{
return false;
}
return
x["_id"].Equals(y["_id"]) &&
x["name"].Equals(y["name"]) &&
object.Equals(x.GetValue("reportsTo", null), y.GetValue("reportsTo", null)) &&
_reportingHierarchyComparer.Equals(x["reportingHierarchy"].AsBsonArray.Cast<BsonDocument>(), y["reportingHierarchy"].AsBsonArray.Cast<BsonDocument>());
}
public int GetHashCode(BsonDocument obj)
{
throw new NotImplementedException();
}
}
}
}
| EmployeeWithReportingHierarchyBsonDocumentEqualityComparer |
csharp | microsoft__FASTER | cs/src/core/VarLen/MemoryFunctions.cs | {
"start": 204,
"end": 3511
} | public class ____<Key, T, Context> : FunctionsBase<Key, Memory<T>, Memory<T>, (IMemoryOwner<T>, int), Context>
where T : unmanaged
{
readonly MemoryPool<T> memoryPool;
/// <summary>
/// Constructor
/// </summary>
/// <param name="memoryPool"></param>
public MemoryFunctions(MemoryPool<T> memoryPool = default)
{
this.memoryPool = memoryPool ?? MemoryPool<T>.Shared;
}
/// <inheritdoc/>
public override bool SingleWriter(ref Key key, ref Memory<T> input, ref Memory<T> src, ref Memory<T> dst, ref (IMemoryOwner<T>, int) output, ref UpsertInfo upsertInfo, WriteReason reason)
{
src.CopyTo(dst);
return true;
}
/// <inheritdoc/>
public override bool ConcurrentWriter(ref Key key, ref Memory<T> input, ref Memory<T> src, ref Memory<T> dst, ref (IMemoryOwner<T>, int) output, ref UpsertInfo upsertInfo)
{
if (dst.Length < src.Length)
{
return false;
}
// Option 1: write the source data, leaving the destination size unchanged. You will need
// to manage the actual space used by the value if you stop here.
src.CopyTo(dst);
// We can adjust the length header on the serialized log, if we wish to.
// This method will also zero out the extra space to retain log scan correctness.
dst.ShrinkSerializedLength(src.Length);
return true;
}
/// <inheritdoc/>
public override bool SingleReader(ref Key key, ref Memory<T> input, ref Memory<T> value, ref (IMemoryOwner<T>, int) dst, ref ReadInfo readInfo)
{
dst.Item1 = memoryPool.Rent(value.Length);
dst.Item2 = value.Length;
value.CopyTo(dst.Item1.Memory);
return true;
}
/// <inheritdoc/>
public override bool ConcurrentReader(ref Key key, ref Memory<T> input, ref Memory<T> value, ref (IMemoryOwner<T>, int) dst, ref ReadInfo readInfo)
{
dst.Item1 = memoryPool.Rent(value.Length);
dst.Item2 = value.Length;
value.CopyTo(dst.Item1.Memory);
return true;
}
/// <inheritdoc/>
public override bool InitialUpdater(ref Key key, ref Memory<T> input, ref Memory<T> value, ref (IMemoryOwner<T>, int) output, ref RMWInfo rmwInfo)
{
input.CopyTo(value);
return true;
}
/// <inheritdoc/>
public override bool CopyUpdater(ref Key key, ref Memory<T> input, ref Memory<T> oldValue, ref Memory<T> newValue, ref (IMemoryOwner<T>, int) output, ref RMWInfo rmwInfo)
{
oldValue.CopyTo(newValue);
return true;
}
/// <inheritdoc/>
public override bool InPlaceUpdater(ref Key key, ref Memory<T> input, ref Memory<T> value, ref (IMemoryOwner<T>, int) output, ref RMWInfo rmwInfo)
{
// The default implementation of IPU simply writes input to destination, if there is space
UpsertInfo upsertInfo = new(ref rmwInfo);
return ConcurrentWriter(ref key, ref input, ref input, ref value, ref output, ref upsertInfo);
}
}
} | MemoryFunctions |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/Dirty/ModelParametersBase.cs | {
"start": 458,
"end": 3374
} | public abstract class ____<TOutput> : ICanSaveModel, IPredictorProducing<TOutput>
{
private const string NormalizerWarningFormat =
"Ignoring integrated normalizer while loading a predictor of type {0}.{1}" +
" Please refer to https://aka.ms/MLNetIssue for assistance with converting legacy models.";
[BestFriend]
private protected readonly IHost Host;
[BestFriend]
private protected ModelParametersBase(IHostEnvironment env, string name)
{
Contracts.CheckValue(env, nameof(env));
env.CheckNonWhiteSpace(name, nameof(name));
Host = env.Register(name);
}
[BestFriend]
private protected ModelParametersBase(IHostEnvironment env, string name, ModelLoadContext ctx)
{
Contracts.CheckValue(env, nameof(env));
env.CheckNonWhiteSpace(name, nameof(name));
Host = env.Register(name);
// *** Binary format ***
// int: sizeof(Float)
// Verify that the Float type matches.
int cbFloat = ctx.Reader.ReadInt32();
#pragma warning disable MSML_NoMessagesForLoadContext // This one is actually useful.
Host.CheckDecode(cbFloat == sizeof(float), "This file was saved by an incompatible version");
#pragma warning restore MSML_NoMessagesForLoadContext
}
void ICanSaveModel.Save(ModelSaveContext ctx) => Save(ctx);
[BestFriend]
private protected virtual void Save(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
SaveCore(ctx);
}
[BestFriend]
private protected virtual void SaveCore(ModelSaveContext ctx)
{
Contracts.AssertValue(ctx);
// *** Binary format ***
// int: sizeof(Float)
// <Derived type stuff>
ctx.Writer.Write(sizeof(float));
}
PredictionKind IPredictor.PredictionKind => PredictionKind;
[BestFriend]
private protected abstract PredictionKind PredictionKind { get; }
/// <summary>
/// This emits a warning if there is Normalizer sub-model.
/// </summary>
[BestFriend]
private protected static bool WarnOnOldNormalizer(ModelLoadContext ctx, Type typePredictor, IChannelProvider provider)
{
Contracts.CheckValue(provider, nameof(provider));
provider.CheckValue(ctx, nameof(ctx));
provider.CheckValue(typePredictor, nameof(typePredictor));
if (!ctx.ContainsModel(@"Normalizer"))
return false;
using (var ch = provider.Start("WarnNormalizer"))
{
ch.Warning(NormalizerWarningFormat, typePredictor, Environment.NewLine);
}
return true;
}
}
}
| ModelParametersBase |
csharp | icsharpcode__ILSpy | ICSharpCode.BamlDecompiler/Baml/BamlRecords.cs | {
"start": 27030,
"end": 27290
} | internal class ____ : BamlRecord
{
public override BamlRecordType Type => BamlRecordType.StaticResourceEnd;
public override void Read(BamlBinaryReader reader)
{
}
public override void Write(BamlBinaryWriter writer)
{
}
}
| StaticResourceEndRecord |
csharp | jellyfin__jellyfin | MediaBrowser.MediaEncoding/Encoder/ApplePlatformHelper.cs | {
"start": 337,
"end": 2661
} | public static class ____
{
private static readonly string[] _av1DecodeBlacklistedCpuClass = ["M1", "M2"];
private static string GetSysctlValue(ReadOnlySpan<byte> name)
{
IntPtr length = IntPtr.Zero;
// Get length of the value
int osStatus = SysctlByName(name, IntPtr.Zero, ref length, IntPtr.Zero, 0);
if (osStatus != 0)
{
throw new NotSupportedException($"Failed to get sysctl value for {System.Text.Encoding.UTF8.GetString(name)} with error {osStatus}");
}
IntPtr buffer = Marshal.AllocHGlobal(length.ToInt32());
try
{
osStatus = SysctlByName(name, buffer, ref length, IntPtr.Zero, 0);
if (osStatus != 0)
{
throw new NotSupportedException($"Failed to get sysctl value for {System.Text.Encoding.UTF8.GetString(name)} with error {osStatus}");
}
return Marshal.PtrToStringAnsi(buffer) ?? string.Empty;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
private static int SysctlByName(ReadOnlySpan<byte> name, IntPtr oldp, ref IntPtr oldlenp, IntPtr newp, uint newlen)
{
return NativeMethods.SysctlByName(name.ToArray(), oldp, ref oldlenp, newp, newlen);
}
/// <summary>
/// Check if the current system has hardware acceleration for AV1 decoding.
/// </summary>
/// <param name="logger">The logger used for error logging.</param>
/// <returns>Boolean indicates the hwaccel support.</returns>
public static bool HasAv1HardwareAccel(ILogger logger)
{
if (!RuntimeInformation.OSArchitecture.Equals(Architecture.Arm64))
{
return false;
}
try
{
string cpuBrandString = GetSysctlValue("machdep.cpu.brand_string"u8);
return !_av1DecodeBlacklistedCpuClass.Any(blacklistedCpuClass => cpuBrandString.Contains(blacklistedCpuClass, StringComparison.OrdinalIgnoreCase));
}
catch (NotSupportedException e)
{
logger.LogError("Error getting CPU brand string: {Message}", e.Message);
}
catch (Exception e)
{
logger.LogError("Unknown error occured: {Exception}", e);
}
return false;
}
| ApplePlatformHelper |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/test/Data.Tests/ProjectableDataLoaderTests.cs | {
"start": 37690,
"end": 38708
} | public class ____(
IServiceProvider services,
List<string> queries,
IBatchScheduler batchScheduler,
DataLoaderOptions options)
: StatefulBatchDataLoader<int, Product[]>(batchScheduler, options)
{
protected override async Task<IReadOnlyDictionary<int, Product[]>> LoadBatchAsync(
IReadOnlyList<int> keys,
DataLoaderFetchContext<Product[]> context,
CancellationToken cancellationToken)
{
var catalogContext = services.GetRequiredService<CatalogContext>();
var query = catalogContext.Brands
.Where(t => keys.Contains(t.Id))
.Select(t => t.Id, t => t.Products, context.GetSelector());
lock (queries)
{
queries.Add(query.ToQueryString());
}
var x = await query.ToDictionaryAsync(t => t.Key, t => t.Value.ToArray(), cancellationToken);
return x;
}
}
}
file | ProductByBrandIdDataLoader2 |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Execution/Processing/Result/ResultBuilder.ObjectResult.cs | {
"start": 61,
"end": 1223
} | partial class ____
{
private readonly ResultPool _resultPool;
private readonly object _objectSync = new();
private ResultBucket<ObjectResult> _objectBucket = null!;
private readonly object _listSync = new();
private ResultBucket<ListResult> _listBucket = null!;
public ObjectResult RentObject(int capacity)
{
while (true)
{
if (_objectBucket.TryPop(out var obj))
{
obj.EnsureCapacity(capacity);
return obj;
}
lock (_objectSync)
{
_objectBucket = _resultPool.GetObjectBucket();
_resultOwner.ObjectBuckets.Add(_objectBucket);
}
}
}
public ListResult RentList(int capacity)
{
while (true)
{
if (_listBucket.TryPop(out var obj))
{
obj.EnsureCapacity(capacity);
return obj;
}
lock (_listSync)
{
_listBucket = _resultPool.GetListBucket();
_resultOwner.ListBuckets.Add(_listBucket);
}
}
}
}
| ResultBuilder |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/MessageUrnSpecs.cs | {
"start": 4157,
"end": 4226
} | public class ____<T>
{
}
[MessageUrn("MyCustomName")]
| G |
csharp | RicoSuter__NJsonSchema | src/NJsonSchema/CompilerFeatures.cs | {
"start": 2779,
"end": 3140
} |
sealed class ____ : Attribute
{ }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif | AllowNullAttribute |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/Formats/Jpg/DCTTests.cs | {
"start": 935,
"end": 14193
} | public class ____ : JpegFixture
{
public FastFloatingPoint(ITestOutputHelper output)
: base(output)
{
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void LLM_TransformIDCT_CompareToNonOptimized(int seed)
{
float[] sourceArray = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed);
Block8x8F srcBlock = Block8x8F.Load(sourceArray);
// reference
Block8x8F expected = ReferenceImplementations.LLM_FloatingPoint_DCT.TransformIDCT(ref srcBlock);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
// Dequantization using unit matrix - no values are upscaled
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// This step is needed to apply adjusting multipliers to the input block
FloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
// IDCT implementation tranforms blocks after transposition
srcBlock.TransposeInPlace();
srcBlock.MultiplyInPlace(ref dequantMatrix);
// IDCT calculation
FloatingPointDCT.TransformIDCT(ref srcBlock);
this.CompareBlocks(expected, srcBlock, 1f);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void LLM_TransformIDCT_CompareToAccurate(int seed)
{
float[] sourceArray = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed);
Block8x8F srcBlock = Block8x8F.Load(sourceArray);
// reference
Block8x8F expected = ReferenceImplementations.AccurateDCT.TransformIDCT(ref srcBlock);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
// Dequantization using unit matrix - no values are upscaled
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// This step is needed to apply adjusting multipliers to the input block
FloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
// IDCT implementation tranforms blocks after transposition
srcBlock.TransposeInPlace();
srcBlock.MultiplyInPlace(ref dequantMatrix);
// IDCT calculation
FloatingPointDCT.TransformIDCT(ref srcBlock);
this.CompareBlocks(expected, srcBlock, 1f);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TransformIDCT(int seed)
{
static void RunTest(string serialized)
{
int seed = FeatureTestRunner.Deserialize<int>(serialized);
Span<float> src = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed);
Block8x8F srcBlock = Block8x8F.Load(src);
float[] expectedDest = new float[64];
float[] temp = new float[64];
// reference
ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D_llm(src, expectedDest, temp);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// Dequantization using unit matrix - no values are upscaled
// as quant matrix is all 1's
// This step is needed to apply adjusting multipliers to the input block
FloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
srcBlock.MultiplyInPlace(ref dequantMatrix);
// testee
// IDCT implementation tranforms blocks after transposition
srcBlock.TransposeInPlace();
FloatingPointDCT.TransformIDCT(ref srcBlock);
float[] actualDest = srcBlock.ToArray();
Assert.Equal(actualDest, expectedDest, new ApproximateFloatComparer(1f));
}
// 4 paths:
// 1. AllowAll - call avx/fma implementation
// 2. DisableFMA - call avx without fma implementation
// 3. DisableAvx - call sse implementation
// 4. DisableHWIntrinsic - call Vector4 fallback implementation
FeatureTestRunner.RunWithHwIntrinsicsFeature(
RunTest,
seed,
HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX | HwIntrinsics.DisableHWIntrinsic);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TranformIDCT_4x4(int seed)
{
Span<float> src = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed, 4, 4);
Block8x8F srcBlock = Block8x8F.Load(src);
float[] expectedDest = new float[64];
float[] temp = new float[64];
// reference
ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D_llm(src, expectedDest, temp);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// Dequantization using unit matrix - no values are upscaled
// as quant matrix is all 1's
// This step is needed to apply adjusting multipliers to the input block
ScaledFloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
// testee
// IDCT implementation tranforms blocks after transposition
srcBlock.TransposeInPlace();
ScaledFloatingPointDCT.TransformIDCT_4x4(ref srcBlock, ref dequantMatrix, NormalizationValue, MaxOutputValue);
Span<float> expectedSpan = expectedDest.AsSpan();
Span<float> actualSpan = srcBlock.ToArray().AsSpan();
// resulting matrix is 4x4
for (int y = 0; y < 4; y++)
{
for (int x = 0; x < 4; x++)
{
AssertScaledElementEquality(expectedSpan.Slice((y * 16) + (x * 2)), actualSpan.Slice((y * 8) + x));
}
}
static void AssertScaledElementEquality(Span<float> expected, Span<float> actual)
{
float average2x2 = 0f;
for (int y = 0; y < 2; y++)
{
int y8 = y * 8;
for (int x = 0; x < 2; x++)
{
float clamped = Numerics.Clamp(expected[y8 + x] + NormalizationValue, 0, MaxOutputValue);
average2x2 += clamped;
}
}
average2x2 = MathF.Round(average2x2 / 4f);
Assert.Equal((int)average2x2, (int)actual[0]);
}
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TranformIDCT_2x2(int seed)
{
Span<float> src = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed, 2, 2);
Block8x8F srcBlock = Block8x8F.Load(src);
float[] expectedDest = new float[64];
float[] temp = new float[64];
// reference
ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D_llm(src, expectedDest, temp);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// Dequantization using unit matrix - no values are upscaled
// as quant matrix is all 1's
// This step is needed to apply adjusting multipliers to the input block
ScaledFloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
// testee
// IDCT implementation tranforms blocks after transposition
srcBlock.TransposeInPlace();
ScaledFloatingPointDCT.TransformIDCT_2x2(ref srcBlock, ref dequantMatrix, NormalizationValue, MaxOutputValue);
Span<float> expectedSpan = expectedDest.AsSpan();
Span<float> actualSpan = srcBlock.ToArray().AsSpan();
// resulting matrix is 2x2
for (int y = 0; y < 2; y++)
{
for (int x = 0; x < 2; x++)
{
AssertScaledElementEquality(expectedSpan.Slice((y * 32) + (x * 4)), actualSpan.Slice((y * 8) + x));
}
}
static void AssertScaledElementEquality(Span<float> expected, Span<float> actual)
{
float average4x4 = 0f;
for (int y = 0; y < 4; y++)
{
int y8 = y * 8;
for (int x = 0; x < 4; x++)
{
float clamped = Numerics.Clamp(expected[y8 + x] + NormalizationValue, 0, MaxOutputValue);
average4x4 += clamped;
}
}
average4x4 = MathF.Round(average4x4 / 16f);
Assert.Equal((int)average4x4, (int)actual[0]);
}
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TranformIDCT_1x1(int seed)
{
Span<float> src = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed, 1, 1);
Block8x8F srcBlock = Block8x8F.Load(src);
float[] expectedDest = new float[64];
float[] temp = new float[64];
// reference
ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D_llm(src, expectedDest, temp);
// testee
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// before applying IDCT
Block8x8F dequantMatrix = CreateBlockFromScalar(1);
// Dequantization using unit matrix - no values are upscaled
// as quant matrix is all 1's
// This step is needed to apply adjusting multipliers to the input block
ScaledFloatingPointDCT.AdjustToIDCT(ref dequantMatrix);
// testee
// IDCT implementation tranforms blocks after transposition
// But DC lays on main diagonal which is not changed by transposition
float actual = ScaledFloatingPointDCT.TransformIDCT_1x1(
srcBlock[0],
dequantMatrix[0],
NormalizationValue,
MaxOutputValue);
float expected = MathF.Round(Numerics.Clamp(expectedDest[0] + NormalizationValue, 0, MaxOutputValue));
Assert.Equal((int)actual, (int)expected);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TransformFDCT(int seed)
{
static void RunTest(string serialized)
{
int seed = FeatureTestRunner.Deserialize<int>(serialized);
Span<float> src = Create8x8RandomFloatData(MinInputValue, MaxInputValue, seed);
Block8x8F block = Block8x8F.Load(src);
float[] expectedDest = new float[64];
float[] temp1 = new float[64];
// reference
ReferenceImplementations.LLM_FloatingPoint_DCT.FDCT2D_llm(src, expectedDest, temp1, downscaleBy8: true);
// testee
// Second transpose call is done by Quantize step
// Do this manually here just to be complient to the reference implementation
FloatingPointDCT.TransformFDCT(ref block);
block.TransposeInPlace();
// Part of the IDCT calculations is fused into the quantization step
// We must multiply input block with adjusted no-quantization matrix
// after applying FDCT
Block8x8F quantMatrix = CreateBlockFromScalar(1);
FloatingPointDCT.AdjustToFDCT(ref quantMatrix);
block.MultiplyInPlace(ref quantMatrix);
float[] actualDest = block.ToArray();
Assert.Equal(expectedDest, actualDest, new ApproximateFloatComparer(1f));
}
// 3 paths:
// 1. AllowAll - call avx implementation
// 2. DisableAvx - call Vector4 implementation
// 3. DisableHWIntrinsic - call scalar fallback implementation
FeatureTestRunner.RunWithHwIntrinsicsFeature(
RunTest,
seed,
HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX | HwIntrinsics.DisableHWIntrinsic);
}
}
}
| FastFloatingPoint |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettings.cs | {
"start": 132,
"end": 259
} | public class ____ : FieldSettings
{
[DefaultValue(true)]
public bool SanitizeHtml { get; set; } = true;
}
| HtmlFieldSettings |
csharp | AutoFixture__AutoFixture | Src/AutoFixture/Dsl/ICustomizationComposer.cs | {
"start": 255,
"end": 358
} | public interface ____<T> : IFactoryComposer<T>, IPostprocessComposer<T>
{
}
} | ICustomizationComposer |
csharp | duplicati__duplicati | Duplicati/Library/Crashlog/CrashlogHelper.cs | {
"start": 1414,
"end": 5743
} | public static class ____
{
/// <summary>
/// The system temp path
/// </summary>
private static readonly string SystemTempPath
#if DEBUG
= Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()?.Location) ?? Path.GetTempPath();
#else
= Path.GetTempPath();
#endif
/// <summary>
/// The default directory to write crashlogs to
/// </summary>
public static string DefaultLogDir { get; set; } = SystemTempPath;
/// <summary>
/// Event to subscribe to for unobserved task exceptions
/// </summary>
public static event Action<Exception>? OnUnobservedTaskException;
/// <summary>
/// Handler for unobserved task exceptions
/// </summary>
/// <param name="sender">Unused sender</param>
/// <param name="e">The exception event args</param>
private static void TaskSchedulerOnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
try
{
OnUnobservedTaskException?.Invoke(e.Exception);
}
catch
{
}
}
/// <summary>
/// Wraps a method in a try-catch block and logs any exceptions to a file
/// </summary>
/// <typeparam name="T">The return type of the method</typeparam>
/// <param name="method">The method to wrap</param>
/// <returns>The result of the method</returns>
public static T WrapWithCrashLog<T>(Func<T> method)
{
try
{
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
return method();
}
catch (Exception ex)
{
LogCrashException(ex);
throw;
}
finally
{
TaskScheduler.UnobservedTaskException -= TaskSchedulerOnUnobservedTaskException;
}
}
/// <summary>
/// Wraps a method in a try-catch block and logs any exceptions to a file
/// </summary>
/// <typeparam name="T">The return type of the method</typeparam>
/// <param name="method">The method to wrap</param>
/// <returns>The result of the method</returns>
public static async Task<T> WrapWithCrashLog<T>(Func<Task<T>> method)
{
try
{
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
return await method().ConfigureAwait(false);
}
catch (Exception ex)
{
LogCrashException(ex);
throw;
}
finally
{
TaskScheduler.UnobservedTaskException -= TaskSchedulerOnUnobservedTaskException;
}
}
/// <summary>
/// The application name
/// </summary>
private static readonly string ApplicationName = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name ?? Guid.NewGuid().ToString()[..8];
/// <summary>
/// Gets the path to the crashlog file
/// </summary>
/// <returns>The path to the crashlog file</returns>
private static string GetLogFilePath()
{
var logdir = string.IsNullOrWhiteSpace(DefaultLogDir)
? SystemTempPath
: DefaultLogDir;
return Path.Combine(logdir, $"{ApplicationName}-crashlog.txt");
}
/// <summary>
/// Gets the last crashlog, if any
/// </summary>
/// <returns>The last crashlog, or null if none</returns>
public static string? GetLastCrashLog()
{
try
{
var path = GetLogFilePath();
if (!File.Exists(path))
return null;
return File.ReadAllText(path);
}
catch
{
return null;
}
}
/// <summary>
/// Logs the exception to a file
/// </summary>
/// <param name="ex">The exception to log</param>
public static void LogCrashException(Exception ex)
{
try
{
Console.WriteLine("Crash! {0}{1}", Environment.NewLine, ex);
}
catch
{
}
try
{
File.WriteAllText(GetLogFilePath(), ex.ToString());
}
catch (Exception writeex)
{
try
{
Console.WriteLine("Failed to write crashlog: {0}", writeex);
}
catch
{
}
}
}
}
| CrashlogHelper |
csharp | dotnet__efcore | src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.ExecuteUpdate.cs | {
"start": 50983,
"end": 51368
} | private sealed class ____(
SqlParameterExpression parameterExpression,
IComplexProperty firstComplexProperty)
: Expression
{
public SqlParameterExpression ParameterExpression { get; } = parameterExpression;
public List<IComplexProperty> ComplexPropertyChain { get; } = [firstComplexProperty];
}
}
| ParameterBasedComplexPropertyChainExpression |
csharp | dotnetcore__WTM | test/WalkingTec.Mvvm.Core.Test/SchoolTop.cs | {
"start": 214,
"end": 961
} | public class ____ : TopBasePoco
{
[Display(Name = "学校编码")]
[Required(ErrorMessage = "{0}是必填项")]
[RegularExpression("^[0-9]{3,3}$", ErrorMessage = "{0}必须是3位数字")]
public string SchoolCode { get; set; }
[Display(Name = "学校名称")]
[StringLength(50, ErrorMessage = "{0}最多输入{1}个字符")]
[Required(ErrorMessage = "{0}是必填项")]
public string SchoolName { get; set; }
[Display(Name = "学校类型")]
[Required(ErrorMessage = "{0}是必填项")]
public SchoolTypeEnum? SchoolType { get; set; }
[Display(Name = "备注")]
[Required]
public string Remark { get; set; }
[Display(Name = "专业")]
public List<MajorTop> Majors { get; set; }
}
}
| SchoolTop |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Composite/Directives/InaccessibleDescriptorExtensions.cs | {
"start": 1786,
"end": 2096
} | enum ____ {
/// ADMIN @inaccessible
/// USER
/// GUEST
/// }
/// </code>
/// </para>
/// <para>
/// <see href="https://graphql.github.io/composite-schemas-spec/draft/#sec--inaccessible"/>
/// </para>
/// </summary>
/// <param name="descriptor">
/// The | UserType |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Tools/MSBuild/MSBuildSettingsTests.cs | {
"start": 8234,
"end": 8554
} | public sealed class ____
{
[Fact]
public void Should_Be_False_By_Default()
{
// Given
var settings = new MSBuildSettings();
// Then
Assert.False(settings.Restore);
}
}
| TheRestoreProperty |
csharp | AutoMapper__AutoMapper | src/UnitTests/AttributeBasedMaps.cs | {
"start": 10084,
"end": 11134
} | public class ____ : IValueResolver<Source, Dest, int>
{
public int Resolve(Source source, Dest destination, int destMember, ResolutionContext context)
{
return source.Value + 5;
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.AddMaps(typeof(When_specifying_source_member_name_via_attributes));
});
[Fact]
public void Should_map_attribute_value()
{
var source = new Source
{
Value = 6
};
var dest = Mapper.Map<Dest>(source);
dest.OtherValue.ShouldBe(11);
}
[Fact]
public void Should_validate_successfully()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => AssertConfigurationIsValid<Source, Dest>());
}
}
| MyValueResolver |
csharp | dotnet__maui | src/Core/src/Converters/FlexEnumsConverters.cs | {
"start": 7880,
"end": 9930
} | public class ____ : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
=> sourceType == typeof(string) || sourceType == typeof(float);
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
=> destinationType == typeof(string);
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is float floatValue)
{
return (FlexBasis)floatValue;
}
var strValue = value?.ToString();
if (strValue != null)
{
strValue = strValue.Trim();
if (strValue.Equals("auto", StringComparison.OrdinalIgnoreCase))
{
return FlexBasis.Auto;
}
if (ParsePercentage(strValue, out float relflex))
{
return new FlexBasis(relflex / 100, isRelative: true);
}
if (float.TryParse(strValue, NumberStyles.Number, CultureInfo.InvariantCulture, out float flex))
{
return new FlexBasis(flex);
}
}
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", strValue, typeof(FlexBasis)));
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (value is not FlexBasis basis)
{
throw new NotSupportedException();
}
if (basis.IsAuto)
{
return "auto";
}
if (basis.IsRelative)
{
return $"{(basis.Length * 100).ToString(CultureInfo.InvariantCulture)}%";
}
return $"{basis.Length.ToString(CultureInfo.InvariantCulture)}";
}
static bool ParsePercentage(string strValue, out float relflex)
{
if (!strValue.EndsWith("%", StringComparison.OrdinalIgnoreCase))
{
relflex = default;
return false;
}
var value =
#if NETSTANDARD2_0 // sigh
strValue.Substring(0, strValue.Length - 1);
#else
strValue.AsSpan(0, strValue.Length - 1);
#endif
return float.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out relflex);
}
}
} | FlexBasisTypeConverter |
csharp | unoplatform__uno | src/Uno.UI.Composition/Generated/3.0.0.0/Microsoft.UI.Composition/Visual.cs | {
"start": 259,
"end": 11063
} | public partial class ____ : global::Microsoft.UI.Composition.CompositionObject
{
// Skipping already declared property TransformMatrix
// Skipping already declared property Size
// Skipping already declared property Scale
// Skipping already declared property RotationAxis
// Skipping already declared property RotationAngleInDegrees
// Skipping already declared property RotationAngle
// Skipping already declared property Orientation
// Skipping already declared property Opacity
// Skipping already declared property Offset
// Skipping already declared property IsVisible
// Skipping already declared property CompositeMode
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || false || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__NETSTD_REFERENCE__")]
public global::Microsoft.UI.Composition.CompositionClip Clip
{
get
{
throw new global::System.NotImplementedException("The member CompositionClip Visual.Clip is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=CompositionClip%20Visual.Clip");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "CompositionClip Visual.Clip");
}
}
#endif
// Skipping already declared property CenterPoint
#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::Microsoft.UI.Composition.CompositionBorderMode BorderMode
{
get
{
throw new global::System.NotImplementedException("The member CompositionBorderMode Visual.BorderMode is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=CompositionBorderMode%20Visual.BorderMode");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "CompositionBorderMode Visual.BorderMode");
}
}
#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::Microsoft.UI.Composition.CompositionBackfaceVisibility BackfaceVisibility
{
get
{
throw new global::System.NotImplementedException("The member CompositionBackfaceVisibility Visual.BackfaceVisibility is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=CompositionBackfaceVisibility%20Visual.BackfaceVisibility");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "CompositionBackfaceVisibility Visual.BackfaceVisibility");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || false || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 AnchorPoint
{
get
{
throw new global::System.NotImplementedException("The member Vector2 Visual.AnchorPoint is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20Visual.AnchorPoint");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "Vector2 Visual.AnchorPoint");
}
}
#endif
// Skipping already declared property Parent
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 RelativeSizeAdjustment
{
get
{
throw new global::System.NotImplementedException("The member Vector2 Visual.RelativeSizeAdjustment is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20Visual.RelativeSizeAdjustment");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "Vector2 Visual.RelativeSizeAdjustment");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector3 RelativeOffsetAdjustment
{
get
{
throw new global::System.NotImplementedException("The member Vector3 Visual.RelativeOffsetAdjustment is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector3%20Visual.RelativeOffsetAdjustment");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "Vector3 Visual.RelativeOffsetAdjustment");
}
}
#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::Microsoft.UI.Composition.Visual ParentForTransform
{
get
{
throw new global::System.NotImplementedException("The member Visual Visual.ParentForTransform is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Visual%20Visual.ParentForTransform");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "Visual Visual.ParentForTransform");
}
}
#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 bool IsHitTestVisible
{
get
{
throw new global::System.NotImplementedException("The member bool Visual.IsHitTestVisible is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20Visual.IsHitTestVisible");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "bool Visual.IsHitTestVisible");
}
}
#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 bool IsPixelSnappingEnabled
{
get
{
throw new global::System.NotImplementedException("The member bool Visual.IsPixelSnappingEnabled is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20Visual.IsPixelSnappingEnabled");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Composition.Visual", "bool Visual.IsPixelSnappingEnabled");
}
}
#endif
// Forced skipping of method Microsoft.UI.Composition.Visual.IsPixelSnappingEnabled.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RelativeSizeAdjustment.get
// Forced skipping of method Microsoft.UI.Composition.Visual.IsHitTestVisible.get
// Forced skipping of method Microsoft.UI.Composition.Visual.IsHitTestVisible.set
// Forced skipping of method Microsoft.UI.Composition.Visual.IsPixelSnappingEnabled.get
// Forced skipping of method Microsoft.UI.Composition.Visual.IsVisible.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RelativeOffsetAdjustment.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RelativeSizeAdjustment.set
// Forced skipping of method Microsoft.UI.Composition.Visual.BackfaceVisibility.set
// Forced skipping of method Microsoft.UI.Composition.Visual.AnchorPoint.set
// Forced skipping of method Microsoft.UI.Composition.Visual.BackfaceVisibility.get
// Forced skipping of method Microsoft.UI.Composition.Visual.AnchorPoint.get
// Forced skipping of method Microsoft.UI.Composition.Visual.BorderMode.get
// Forced skipping of method Microsoft.UI.Composition.Visual.BorderMode.set
// Forced skipping of method Microsoft.UI.Composition.Visual.CenterPoint.get
// Forced skipping of method Microsoft.UI.Composition.Visual.CenterPoint.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Clip.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Clip.set
// Forced skipping of method Microsoft.UI.Composition.Visual.CompositeMode.get
// Forced skipping of method Microsoft.UI.Composition.Visual.CompositeMode.set
// Forced skipping of method Microsoft.UI.Composition.Visual.IsVisible.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Offset.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Offset.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Opacity.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Opacity.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Orientation.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Orientation.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Parent.get
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAngle.get
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAngle.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAngleInDegrees.get
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAngleInDegrees.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAxis.get
// Forced skipping of method Microsoft.UI.Composition.Visual.RotationAxis.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Scale.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Scale.set
// Forced skipping of method Microsoft.UI.Composition.Visual.Size.get
// Forced skipping of method Microsoft.UI.Composition.Visual.Size.set
// Forced skipping of method Microsoft.UI.Composition.Visual.TransformMatrix.get
// Forced skipping of method Microsoft.UI.Composition.Visual.TransformMatrix.set
// Forced skipping of method Microsoft.UI.Composition.Visual.ParentForTransform.get
// Forced skipping of method Microsoft.UI.Composition.Visual.ParentForTransform.set
// Forced skipping of method Microsoft.UI.Composition.Visual.RelativeOffsetAdjustment.get
}
}
| Visual |
csharp | dotnet__aspnetcore | src/Mvc/test/Mvc.IntegrationTests/ValidationWithRecordIntegrationTests.cs | {
"start": 80222,
"end": 82392
} | private record ____(int Property1)
{
public RecursiveModel Property2 { get; set; }
public RecursiveModel Property3 => new RecursiveModel(Property1);
}
[Fact]
public async Task Validation_InifnitelyRecursiveModel_ValidationOnTopLevelParameter()
{
// Arrange
var parameterInfo = GetType().GetMethod(nameof(Validation_InifnitelyRecursiveModel_ValidationOnTopLevelParameterMethod), BindingFlags.NonPublic | BindingFlags.Static)
.GetParameters()
.First();
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider.GetMetadataForParameter(parameterInfo);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(modelMetadataProvider);
var parameter = new ParameterDescriptor()
{
Name = parameterInfo.Name,
ParameterType = parameterInfo.ParameterType,
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = new QueryString("?Property1=8");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext, modelMetadataProvider, modelMetadata);
// Assert
Assert.True(modelBindingResult.IsModelSet);
var model = Assert.IsType<RecursiveModel>(modelBindingResult.Model);
Assert.Equal(8, model.Property1);
Assert.True(modelState.IsValid);
Assert.Equal(ModelValidationState.Valid, modelState.ValidationState);
var entry = Assert.Single(modelState, e => e.Key == "Property1").Value;
Assert.Equal("8", entry.AttemptedValue);
Assert.Equal("8", entry.RawValue);
Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
}
private static void Validation_InifnitelyRecursiveModel_ValidationOnTopLevelParameterMethod([Required] RecursiveModel model) { }
#pragma warning disable CS8907 // Parameter is unread. Did you forget to use it to initialize the property with that name?
| RecursiveModel |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Serialization/ShouldSerializeTests.cs | {
"start": 1770,
"end": 10888
} | public class ____
{
public A A { get; set; }
public virtual bool ShouldSerializeA()
{
return false;
}
}
[Test]
public void VirtualShouldSerializeSimple()
{
string json = JsonConvert.SerializeObject(new B());
Assert.AreEqual("{}", json);
}
[Test]
public void VirtualShouldSerialize()
{
var setFoo = new Foo2()
{
name = Guid.NewGuid().ToString(),
myBar = new Bar2()
{
name = Guid.NewGuid().ToString(),
myBaz = new Baz1[]
{
new Baz1()
{
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]
{
new Frob1 { name = Guid.NewGuid().ToString() }
}
},
new Baz1()
{
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]
{
new Frob1 { name = Guid.NewGuid().ToString() }
}
},
new Baz1()
{
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]
{
new Frob1 { name = Guid.NewGuid().ToString() }
}
},
}
}
};
var setFooJson = Serialize(setFoo);
var deserializedSetFoo = JsonConvert.DeserializeObject<Foo2>(setFooJson);
Assert.AreEqual(setFoo.name, deserializedSetFoo.name);
Assert.IsNotNull(deserializedSetFoo.myBar);
Assert.AreEqual(setFoo.myBar.name, deserializedSetFoo.myBar.name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz);
Assert.AreEqual(setFoo.myBar.myBaz.Length, deserializedSetFoo.myBar.myBaz.Length);
Assert.AreEqual(setFoo.myBar.myBaz[0].name, deserializedSetFoo.myBar.myBaz[0].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[0].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[0].myFrob[0].name, deserializedSetFoo.myBar.myBaz[0].myFrob[0].name);
Assert.AreEqual(setFoo.myBar.myBaz[1].name, deserializedSetFoo.myBar.myBaz[1].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[2].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[1].myFrob[0].name, deserializedSetFoo.myBar.myBaz[1].myFrob[0].name);
Assert.AreEqual(setFoo.myBar.myBaz[2].name, deserializedSetFoo.myBar.myBaz[2].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[2].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[2].myFrob[0].name, deserializedSetFoo.myBar.myBaz[2].myFrob[0].name);
Assert.AreEqual(true, setFoo.myBar.ShouldSerializemyBazCalled);
}
private string Serialize(Foo2 f)
{
//Code copied from JsonConvert.SerializeObject(), with addition of trace writing
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault();
var traceWriter = new MemoryTraceWriter();
jsonSerializer.TraceWriter = traceWriter;
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.None;
jsonSerializer.Serialize(jsonWriter, f, typeof(Foo2));
}
return sw.ToString();
}
[Test]
public void ShouldSerializeTest()
{
ShouldSerializeTestClass c = new ShouldSerializeTestClass();
c.Name = "James";
c.Age = 27;
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""Age"": 27
}", json);
c._shouldSerializeName = true;
json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""James"",
""Age"": 27
}", json);
ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
Assert.AreEqual("James", deserialized.Name);
Assert.AreEqual(27, deserialized.Age);
}
[Test]
public void ShouldSerializeExample()
{
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
StringAssert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
[Test]
public void SpecifiedTest()
{
SpecifiedTestClass c = new SpecifiedTestClass();
c.Name = "James";
c.Age = 27;
c.NameSpecified = false;
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""Age"": 27
}", json);
SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
Assert.IsNull(deserialized.Name);
Assert.IsFalse(deserialized.NameSpecified);
Assert.IsFalse(deserialized.WeightSpecified);
Assert.IsFalse(deserialized.HeightSpecified);
Assert.IsFalse(deserialized.FavoriteNumberSpecified);
Assert.AreEqual(27, deserialized.Age);
c.NameSpecified = true;
c.WeightSpecified = true;
c.HeightSpecified = true;
c.FavoriteNumber = 23;
json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""James"",
""Age"": 27,
""Weight"": 0,
""Height"": 0,
""FavoriteNumber"": 23
}", json);
deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
Assert.AreEqual("James", deserialized.Name);
Assert.IsTrue(deserialized.NameSpecified);
Assert.IsTrue(deserialized.WeightSpecified);
Assert.IsTrue(deserialized.HeightSpecified);
Assert.IsTrue(deserialized.FavoriteNumberSpecified);
Assert.AreEqual(27, deserialized.Age);
Assert.AreEqual(23, deserialized.FavoriteNumber);
}
// [Test]
// public void XmlSerializerSpecifiedTrueTest()
// {
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
// StringWriter sw = new StringWriter();
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
// Console.WriteLine(sw.ToString());
// string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
//<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
// <FirstOrder>First</FirstOrder>
//</OptionalOrder>";
// OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
// Console.WriteLine(o.FirstOrder);
// Console.WriteLine(o.FirstOrderSpecified);
// }
// [Test]
// public void XmlSerializerSpecifiedFalseTest()
// {
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
// StringWriter sw = new StringWriter();
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
// Console.WriteLine(sw.ToString());
// // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
// //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
// // <FirstOrder>First</FirstOrder>
// //</OptionalOrder>";
// // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
// // Console.WriteLine(o.FirstOrder);
// // Console.WriteLine(o.FirstOrderSpecified);
// }
| B |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Models/Catalog/ProductReviewModel.cs | {
"start": 1681,
"end": 2215
} | public class ____ : BaseModel
{
[GrandResourceDisplayName("Reviews.Fields.Title")]
public string Title { get; set; }
[GrandResourceDisplayName("Reviews.Fields.ReviewText")]
public string ReviewText { get; set; }
[GrandResourceDisplayName("Reviews.Fields.Rating")]
public int Rating { get; set; }
public bool DisplayCaptcha { get; set; }
public bool CanCurrentCustomerLeaveReview { get; set; }
public bool SuccessfullyAdded { get; set; }
public string Result { get; set; }
} | AddProductReviewModel |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Base.UnitTests/Data/DefaultValueConverterTests.cs | {
"start": 5920,
"end": 6005
} | private enum ____
{
Foo,
Bar,
}
| TestEnum |
csharp | dotnet__aspnetcore | src/Shared/PropertyHelper/PropertyHelper.cs | {
"start": 22699,
"end": 23054
} | internal static class ____
{
/// <summary>
/// Invoked as part of <see cref="MetadataUpdateHandlerAttribute" /> contract for hot reload.
/// </summary>
public static void ClearCache(Type[]? _)
{
PropertiesCache.Clear();
VisiblePropertiesCache.Clear();
}
}
}
| MetadataUpdateHandler |
csharp | HangfireIO__Hangfire | src/Hangfire.Core/Common/ExpressionUtil/ExpressionFingerprintChain.cs | {
"start": 1444,
"end": 2693
} | class ____ into expressions. (Occasionally there will be a NULL
// in the fingerprint chain, which depending on context can denote a static member, a null Conversion
// in a BinaryExpression, and so forth.)
//
// "Hello " + "world" -> OP_ADD, CONST:string, NULL, CONST:string
// "Hello " + {model} -> OP_ADD, CONST:string, NULL, PARAM_0:string
//
// These string concatenations have different fingerprints since the inputs are provided differently:
// one is a constant, the other is a parameter.
//
// ({model} ?? "sample").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string
// ({model} ?? "other sample").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string
//
// These expressions have the same fingerprint since all constants of the same underlying type are
// treated equally.
//
// It's also important that the fingerprints don't reference the actual Expression objects that were
// used to generate them, as the fingerprints will be cached, and caching a fingerprint that references
// an Expression will root the Expression (and any objects it references).
[ExcludeFromCodeCoverage]
| recurses |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Configuration/SagaConfigurationObserver_Specs.cs | {
"start": 2202,
"end": 3473
} | class ____ :
ISagaConfigurationObserver
{
public SagaConfigurationObserver()
{
SagaTypes = new HashSet<Type>();
StateMachineTypes = new HashSet<Type>();
MessageTypes = new HashSet<Tuple<Type, Type>>();
}
public HashSet<Type> SagaTypes { get; }
public HashSet<Type> StateMachineTypes { get; }
public HashSet<Tuple<Type, Type>> MessageTypes { get; }
void ISagaConfigurationObserver.SagaConfigured<TSaga>(ISagaConfigurator<TSaga> configurator)
{
SagaTypes.Add(typeof(TSaga));
}
public void StateMachineSagaConfigured<TInstance>(ISagaConfigurator<TInstance> configurator, SagaStateMachine<TInstance> stateMachine)
where TInstance : class, ISaga, SagaStateMachineInstance
{
StateMachineTypes.Add(stateMachine.GetType());
}
void ISagaConfigurationObserver.SagaMessageConfigured<TSaga, TMessage>(ISagaMessageConfigurator<TSaga, TMessage> configurator)
{
MessageTypes.Add(Tuple.Create(typeof(TSaga), typeof(TMessage)));
}
}
}
}
| SagaConfigurationObserver |
csharp | dotnet__efcore | src/Shared/DisposableExtensions.cs | {
"start": 208,
"end": 649
} | internal static class ____
{
public static ValueTask DisposeAsyncIfAvailable(this IDisposable? disposable)
{
switch (disposable)
{
case null:
return default;
case IAsyncDisposable asyncDisposable:
return asyncDisposable.DisposeAsync();
default:
disposable.Dispose();
return default;
}
}
}
| DisposableExtensions |
csharp | smartstore__Smartstore | src/Smartstore.Modules/Smartstore.WebApi/Controllers/Checkout/OrderNotesController.cs | {
"start": 260,
"end": 3399
} | public class ____ : WebApiController<OrderNote>
{
private readonly Lazy<IMessageFactory> _messageFactory;
public OrderNotesController(Lazy<IMessageFactory> messageFactory)
{
_messageFactory = messageFactory;
}
[HttpGet("OrderNotes"), ApiQueryable]
[Permission(Permissions.Order.Read)]
public IQueryable<OrderNote> Get()
{
return Entities.AsNoTracking();
}
[HttpGet("OrderNotes({key})"), ApiQueryable]
[Permission(Permissions.Order.Read)]
public SingleResult<OrderNote> Get(int key)
{
return GetById(key);
}
[HttpGet("OrderNotes({key})/Order"), ApiQueryable]
[Permission(Permissions.Order.Read)]
public SingleResult<Order> GetOrder(int key)
{
return GetRelatedEntity(key, x => x.Order);
}
/// <param name="notifyCustomer">
/// A value indicating whether to send a notification to the customer about the new order note.
/// Only applicable if **DisplayToCustomer** is true.
/// </param>
[HttpPost]
[Permission(Permissions.Order.Update)]
public async Task<IActionResult> Post(
[FromBody] OrderNote entity,
[FromQuery] bool notifyCustomer = false)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (entity == null)
{
return BadRequest($"Missing or invalid API request body for {nameof(OrderNote)} entity.");
}
if (entity.Note.IsEmpty())
{
return BadRequest("Missing or empty order note text.");
}
var order = await Db.Orders
.Include(x => x.Customer)
.FindByIdAsync(entity.OrderId);
if (order == null)
{
return NotFound(entity.OrderId, nameof(Order));
}
try
{
order.OrderNotes.Add(entity);
await Db.SaveChangesAsync();
if (entity.DisplayToCustomer && notifyCustomer)
{
await _messageFactory.Value.SendNewOrderNoteAddedCustomerNotificationAsync(entity, order.CustomerLanguageId);
}
return Created(entity);
}
catch (Exception ex)
{
return ErrorResult(ex);
}
}
[HttpPut]
[Permission(Permissions.Order.Update)]
public Task<IActionResult> Put(int key, Delta<OrderNote> model)
{
return PutAsync(key, model);
}
[HttpPatch]
[Permission(Permissions.Order.Update)]
public Task<IActionResult> Patch(int key, Delta<OrderNote> model)
{
return PatchAsync(key, model);
}
[HttpDelete]
[Permission(Permissions.Order.Update)]
public Task<IActionResult> Delete(int key)
{
return DeleteAsync(key);
}
}
}
| OrderNotesController |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Adapters/src/Adapters.OpenApi.Core/Diagnostics/IOpenApiDiagnosticEventListener.cs | {
"start": 94,
"end": 332
} | interface ____ the DI container to
/// listen to diagnostic events. Multiple implementations can be registered,
/// and they will all be called in the registration order.
/// </summary>
/// <seealso cref="OpenApiDiagnosticEventListener"/>
| in |
csharp | dotnetcore__Util | src/Util.Tenants/Resolvers/QueryStringTenantResolver.cs | {
"start": 83,
"end": 500
} | public class ____ : TenantResolverBase {
/// <summary>
/// 解析租户标识
/// </summary>
protected override Task<string> Resolve( HttpContext context ) {
var key = GetTenantKey( context );
var tenantId = context.Request.Query[key].FirstOrDefault();
GetLog( context ).LogTrace( $"执行查询字符串租户解析器,{key}={tenantId}" );
return Task.FromResult( tenantId );
}
} | QueryStringTenantResolver |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/ManyToManyFieldsLoadSqlServerTest.cs | {
"start": 12517,
"end": 13594
} | public class ____ : ManyToManyFieldsLoadFixtureBase, ITestSqlLoggerFactory
{
public TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ListLoggerFactory;
protected override ITestStoreFactory TestStoreFactory
=> SqlServerTestStoreFactory.Instance;
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
base.OnModelCreating(modelBuilder, context);
modelBuilder
.Entity<JoinOneSelfPayload>()
.Property(e => e.Payload)
.HasDefaultValueSql("GETUTCDATE()");
modelBuilder
.SharedTypeEntity<Dictionary<string, object>>("JoinOneToThreePayloadFullShared")
.IndexerProperty<string>("Payload")
.HasDefaultValue("Generated");
modelBuilder
.Entity<JoinOneToThreePayloadFull>()
.Property(e => e.Payload)
.HasDefaultValue("Generated");
}
}
}
| ManyToManyFieldsLoadSqlServerFixture |
csharp | dotnet__machinelearning | test/Microsoft.ML.Tokenizers.Tests/PreTokenizerTests.cs | {
"start": 362,
"end": 2751
} | public class ____
{
public static IEnumerable<object[]> PreTokenizerData
{
get
{
yield return new object[]
{
PreTokenizer.CreateWordOrNonWord(),
"How are you doing?",
new (int Offset, int Length)[] { (0, 3), (4, 3), (8, 3), (12, 5), (17, 1), }
};
yield return new object[]
{
PreTokenizer.CreateWordOrNonWord(),
"I_am_Just_Fine!",
new (int Offset, int Length)[] { (0, 14), (14, 1) }
};
yield return new object[]
{
PreTokenizer.CreateWhiteSpace(),
"Hello, how are you doing?!",
new (int Offset, int Length)[] { (0, 6), (7, 3), (11, 3), (15, 3), (19, 7) }
};
yield return new object[]
{
new SpacePreTokenizer(),
"How are you doing?!",
new (int Offset, int Length)[] { (0, 3), (4, 3), (11, 3), (15, 7) }
};
yield return new object[]
{
new SpacePreTokenizer(),
new string(' ', 100),
new (int Offset, int Length)[] { }
};
}
}
[Theory]
[MemberData(nameof(PreTokenizerData))]
public void TestPreTokenizer(PreTokenizer preTokenizer, string text, (int Offset, int Length)[] splits)
{
(int Offset, int Length)[] splitParts = preTokenizer.PreTokenize(text).ToArray<(int Offset, int Length)>();
Assert.Equal(splits, splitParts);
// Empty tokenizer which tokenize all parts as unknown tokens.
Tokenizer tokenizer = BpeTests.CreateEmptyBpe(normalizer: null, preTokenizer: preTokenizer);
IReadOnlyList<EncodedToken> encoding = tokenizer.EncodeToTokens(text, out _);
Assert.True(encoding.Count >= splitParts.Length, $"Expected to have {encoding.Count} >= {splitParts.Length}");
}
[Fact]
public void TestWordOrNonWordPreTokenizer()
{
Assert.Empty(PreTokenizer.CreateWordOrNonWord().PreTokenize((string)null!));
}
| PreTokenizersTests |
csharp | dotnet__machinelearning | src/Microsoft.ML.EntryPoints/ScoreModel.cs | {
"start": 2318,
"end": 2548
} | public sealed class ____
{
[Argument(ArgumentType.Required, HelpText = "The predictor model to turn into a transform", SortOrder = 1)]
public PredictorModel PredictorModel;
}
| ModelInput |
csharp | dotnet__aspnetcore | src/Hosting/Server.IntegrationTesting/src/Common/DeploymentParameters.cs | {
"start": 330,
"end": 6828
} | public class ____
{
public DeploymentParameters()
{
EnvironmentVariables["ASPNETCORE_DETAILEDERRORS"] = "true";
var configAttribute = Assembly.GetCallingAssembly().GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttribute != null && !string.IsNullOrEmpty(configAttribute.Configuration))
{
Configuration = configAttribute.Configuration;
}
}
public DeploymentParameters(TestVariant variant)
{
EnvironmentVariables["ASPNETCORE_DETAILEDERRORS"] = "true";
var configAttribute = Assembly.GetCallingAssembly().GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttribute != null && !string.IsNullOrEmpty(configAttribute.Configuration))
{
Configuration = configAttribute.Configuration;
}
ServerType = variant.Server;
TargetFramework = variant.Tfm;
ApplicationType = variant.ApplicationType;
RuntimeArchitecture = variant.Architecture;
HostingModel = variant.HostingModel;
}
/// <summary>
/// Creates an instance of <see cref="DeploymentParameters"/>.
/// </summary>
/// <param name="applicationPath">Source code location of the target location to be deployed.</param>
/// <param name="serverType">Where to be deployed on.</param>
/// <param name="runtimeFlavor">Flavor of the clr to run against.</param>
/// <param name="runtimeArchitecture">Architecture of the runtime to be used.</param>
public DeploymentParameters(
string applicationPath,
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture runtimeArchitecture)
{
ArgumentException.ThrowIfNullOrEmpty(applicationPath);
if (!Directory.Exists(applicationPath))
{
throw new DirectoryNotFoundException($"Application path {applicationPath} does not exist.");
}
ApplicationPath = applicationPath;
ApplicationName = new DirectoryInfo(ApplicationPath).Name;
ServerType = serverType;
RuntimeFlavor = runtimeFlavor;
EnvironmentVariables["ASPNETCORE_DETAILEDERRORS"] = "true";
var configAttribute = Assembly.GetCallingAssembly().GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttribute != null && !string.IsNullOrEmpty(configAttribute.Configuration))
{
Configuration = configAttribute.Configuration;
}
}
public DeploymentParameters(DeploymentParameters parameters)
{
foreach (var propertyInfo in typeof(DeploymentParameters).GetProperties())
{
if (propertyInfo.CanWrite)
{
propertyInfo.SetValue(this, propertyInfo.GetValue(parameters));
}
}
foreach (var kvp in parameters.EnvironmentVariables)
{
EnvironmentVariables.Add(kvp);
}
foreach (var kvp in parameters.PublishEnvironmentVariables)
{
PublishEnvironmentVariables.Add(kvp);
}
}
public ApplicationPublisher ApplicationPublisher { get; set; }
public ServerType ServerType { get; set; }
public RuntimeFlavor RuntimeFlavor { get; set; }
public RuntimeArchitecture RuntimeArchitecture { get; set; } = RuntimeArchitectures.Current;
/// <summary>
/// Suggested base url for the deployed application. The final deployed url could be
/// different than this. Use <see cref="DeploymentResult.ApplicationBaseUri"/> for the
/// deployed url.
/// </summary>
public string ApplicationBaseUriHint { get; set; }
public bool RestoreDependencies { get; set; }
/// <summary>
/// Scheme used by the deployed application if <see cref="ApplicationBaseUriHint"/> is empty.
/// </summary>
public string Scheme { get; set; } = Uri.UriSchemeHttp;
public string EnvironmentName { get; set; }
public string ServerConfigTemplateContent { get; set; }
public string ServerConfigLocation { get; set; }
public string SiteName { get; set; } = "HttpTestSite";
public string ApplicationPath { get; set; }
/// <summary>
/// Gets or sets the name of the application. This is used to execute the application when deployed.
/// Defaults to the file name of <see cref="ApplicationPath"/>.
/// </summary>
public string ApplicationName { get; set; }
public string TargetFramework { get; set; }
/// <summary>
/// Configuration under which to build (ex: Release or Debug)
/// </summary>
public string Configuration { get; set; } = "Debug";
/// <summary>
/// Space separated command line arguments to be passed to dotnet-publish
/// </summary>
public string AdditionalPublishParameters { get; set; }
/// <summary>
/// To publish the application before deployment.
/// </summary>
public bool PublishApplicationBeforeDeployment { get; set; }
public bool PreservePublishedApplicationForDebugging { get; set; }
public bool StatusMessagesEnabled { get; set; } = true;
public ApplicationType ApplicationType { get; set; }
public string PublishedApplicationRootPath { get; set; }
public HostingModel HostingModel { get; set; }
/// <summary>
/// Environment variables to be set before starting the host.
/// Not applicable for IIS Scenarios.
/// </summary>
public IDictionary<string, string> EnvironmentVariables { get; } = new Dictionary<string, string>();
/// <summary>
/// Environment variables used when invoking dotnet publish.
/// </summary>
public IDictionary<string, string> PublishEnvironmentVariables { get; } = new Dictionary<string, string>();
/// <summary>
/// For any application level cleanup to be invoked after performing host cleanup.
/// </summary>
public Action<DeploymentParameters> UserAdditionalCleanup { get; set; }
/// <summary>
/// Timeout for publish
/// </summary>
public TimeSpan? PublishTimeout { get; set; }
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Variation] :: ServerType={0}, Runtime={1}, Arch={2}, BaseUrlHint={3}, Publish={4}, HostingModel={5}",
ServerType,
RuntimeFlavor,
RuntimeArchitecture,
ApplicationBaseUriHint,
PublishApplicationBeforeDeployment,
HostingModel);
}
}
| DeploymentParameters |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/Automation/AutomationElementIdentifiers.cs | {
"start": 200,
"end": 647
} | public static class ____
{
/// <summary>
/// Identifies the bounding rectangle automation property. The bounding rectangle property
/// value is returned by the <see cref="AutomationPeer.GetBoundingRectangle"/> method.
/// </summary>
public static AutomationProperty BoundingRectangleProperty { get; } = new AutomationProperty();
/// <summary>
/// Identifies the | AutomationElementIdentifiers |
csharp | smartstore__Smartstore | src/Smartstore/Utilities/Html/CodeFormatter/CodeFormat.cs | {
"start": 1209,
"end": 5884
} | partial class ____ : SourceFormat
{
/// <summary>
/// Must be overridden to provide a list of keywords defined in
/// each language.
/// </summary>
/// <remarks>
/// Keywords must be separated with spaces.
/// </remarks>
protected abstract string Keywords
{
get;
}
/// <summary>
/// Can be overridden to provide a list of preprocessors defined in
/// each language.
/// </summary>
/// <remarks>
/// Preprocessors must be separated with spaces.
/// </remarks>
protected virtual string Preprocessors => "";
/// <summary>
/// Must be overridden to provide a regular expression string
/// to match strings literals.
/// </summary>
protected abstract string StringRegex
{
get;
}
/// <summary>
/// Must be overridden to provide a regular expression string
/// to match comments.
/// </summary>
protected abstract string CommentRegex
{
get;
}
/// <summary>
/// Determines if the language is case sensitive.
/// </summary>
/// <value><b>true</b> if the language is case sensitive, <b>false</b>
/// otherwise. The default is true.</value>
/// <remarks>
/// A case-insensitive language formatter must override this
/// property to return false.
/// </remarks>
public virtual bool CaseSensitive => true;
/// <summary/>
protected CodeFormat()
{
// generate the keyword and preprocessor regexes from the keyword lists
Regex r;
r = new Regex(@"\w+|-\w+|#\w+|@@\w+|#(?:\\(?:s|w)(?:\*|\+)?\w+)+|@\\w\*+");
string regKeyword = r.Replace(Keywords, @"(?<=^|\W)$0(?=\W)");
string regPreproc = r.Replace(Preprocessors, @"(?<=^|\s)$0(?=\s|$)");
r = new Regex(@" +");
regKeyword = r.Replace(regKeyword, @"|");
regPreproc = r.Replace(regPreproc, @"|");
if (regPreproc.Length == 0)
{
regPreproc = "(?!.*)_{37}(?<!.*)"; //use something quite impossible...
}
// build a master regex with capturing groups
var regAll = new StringBuilder(1000);
regAll.Append('(');
regAll.Append(CommentRegex);
regAll.Append(")|(");
regAll.Append(StringRegex);
if (regPreproc.Length > 0)
{
regAll.Append(")|(");
regAll.Append(regPreproc);
}
regAll.Append(")|(");
regAll.Append(regKeyword);
regAll.Append(')');
RegexOptions caseInsensitive = CaseSensitive ? 0 : RegexOptions.IgnoreCase;
CodeRegex = new Regex(regAll.ToString(), RegexOptions.Singleline | caseInsensitive);
}
/// <summary>
/// Called to evaluate the HTML fragment corresponding to each
/// matching token in the code.
/// </summary>
/// <param name="match">The <see cref="Match"/> resulting from a
/// single regular expression match.</param>
/// <returns>A string containing the HTML code fragment.</returns>
protected override string MatchEval(Match match)
{
if (match.Groups[1].Success) //comment
{
var reader = new StringReader(match.ToString());
string line;
var sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
if (sb.Length > 0)
{
sb.Append('\n');
}
sb.Append("<span class=\"rem\">");
sb.Append(line);
sb.Append("</span>");
}
return sb.ToString();
}
if (match.Groups[2].Success) //string literal
{
return "<span class=\"str\">" + match.ToString() + "</span>";
}
if (match.Groups[3].Success) //preprocessor keyword
{
return "<span class=\"preproc\">" + match.ToString() + "</span>";
}
if (match.Groups[4].Success) //keyword
{
return "<span class=\"kwrd\">" + match.ToString() + "</span>";
}
System.Diagnostics.Debug.Assert(false, "None of the above!");
return ""; //none of the above
}
}
}
| CodeFormat |
csharp | dotnet__efcore | src/EFCore/Infrastructure/IAnnotatable.cs | {
"start": 409,
"end": 764
} | interface ____ typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see>
/// for more information and examples.
/// </remarks>
| is |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckMvc/CheckWebGlobalNamespace.dtos.cs | {
"start": 54075,
"end": 54272
} | public partial class ____
{
public TypeA()
{
Bar = new List<TypeB>{};
}
public virtual List<TypeB> Bar { get; set; }
}
[Serializable]
| TypeA |
csharp | dotnet__aspnetcore | src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs | {
"start": 108933,
"end": 110712
} | private class ____
{
public int ProductId { get; set; }
public string Name { get; }
public IList<string> Aliases { get; }
}
[Theory]
[InlineData("?parameter.ProductId=10")]
[InlineData("?parameter.ProductId=10¶meter.Name=Camera")]
[InlineData("?parameter.ProductId=10¶meter.Name=Camera¶meter.Aliases[0]=Camera1")]
public async Task ComplexTypeModelBinder_BindsSettableProperties(string queryString)
{
// Arrange
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(Product)
};
// Need to have a key here so that the ComplexTypeModelBinder will recurse to bind elements.
var testContext = GetTestContext(request =>
{
request.QueryString = new QueryString(queryString);
SetJsonBodyContent(request, AddressBodyContent);
});
var metadata = GetMetadata(testContext, parameter);
var modelBinder = GetModelBinder(testContext, parameter, metadata);
var valueProvider = await CompositeValueProvider.CreateAsync(testContext);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
testContext,
modelBinder,
valueProvider,
parameter,
metadata,
value: null);
// Assert
Assert.True(modelBindingResult.IsModelSet);
var model = Assert.IsType<Product>(modelBindingResult.Model);
Assert.NotNull(model);
Assert.Equal(10, model.ProductId);
Assert.Null(model.Name);
Assert.Null(model.Aliases);
}
| Product |
csharp | unoplatform__uno | src/Uno.UI.RemoteControl/external/Microsoft.IO.RecyclableMemoryStream/RecyclableMemoryStreamManager.cs | {
"start": 2448,
"end": 5153
} | public partial class ____
{
/// <summary>
/// Maximum length of a single array.
/// </summary>
/// <remarks>See documentation at https://docs.microsoft.com/dotnet/api/system.array?view=netcore-3.1
/// </remarks>
internal const int MaxArrayLength = 0X7FFFFFC7;
/// <summary>
/// Default block size, in bytes.
/// </summary>
public const int DefaultBlockSize = 128 * 1024;
/// <summary>
/// Default large buffer multiple, in bytes.
/// </summary>
public const int DefaultLargeBufferMultiple = 1024 * 1024;
/// <summary>
/// Default maximum buffer size, in bytes.
/// </summary>
public const int DefaultMaximumBufferSize = 128 * 1024 * 1024;
// 0 to indicate unbounded
private const long DefaultMaxSmallPoolFreeBytes = 0L;
private const long DefaultMaxLargePoolFreeBytes = 0L;
private readonly long[] largeBufferFreeSize;
private readonly long[] largeBufferInUseSize;
private readonly ConcurrentStack<byte[]>[] largePools;
private readonly ConcurrentStack<byte[]> smallPool;
private long smallPoolFreeSize;
private long smallPoolInUseSize;
internal readonly Options options;
/// <summary>
/// Settings for controlling the behavior of RecyclableMemoryStream
/// </summary>
public Options Settings => this.options;
/// <summary>
/// Number of bytes in small pool not currently in use.
/// </summary>
public long SmallPoolFreeSize => this.smallPoolFreeSize;
/// <summary>
/// Number of bytes currently in use by stream from the small pool.
/// </summary>
public long SmallPoolInUseSize => this.smallPoolInUseSize;
/// <summary>
/// Number of bytes in large pool not currently in use.
/// </summary>
public long LargePoolFreeSize
{
get
{
long sum = 0;
foreach (long freeSize in this.largeBufferFreeSize)
{
sum += freeSize;
}
return sum;
}
}
/// <summary>
/// Number of bytes currently in use by streams from the large pool.
/// </summary>
public long LargePoolInUseSize
{
get
{
long sum = 0;
foreach (long inUseSize in this.largeBufferInUseSize)
{
sum += inUseSize;
}
return sum;
}
}
/// <summary>
/// How many blocks are in the small pool.
/// </summary>
public long SmallBlocksFree => this.smallPool.Count;
/// <summary>
/// How many buffers are in the large pool.
/// </summary>
public long LargeBuffersFree
{
get
{
long free = 0;
foreach (var pool in this.largePools)
{
free += pool.Count;
}
return free;
}
}
/// <summary>
/// Parameters for customizing the behavior of <see cref="RecyclableMemoryStreamManager"/>
/// </summary>
| RecyclableMemoryStreamManager |
csharp | dotnet__machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/TimeSeries/LocalizeRootCause.cs | {
"start": 133,
"end": 4806
} | public static class ____
{
// In the root cause detection input, this string identifies an aggregation as opposed to a dimension value"
private static string AGG_SYMBOL = "##SUM##";
public static void Example()
{
// Create a new ML context, for ML.NET operations. It can be used for
// exception tracking and logging, as well as the source of randomness.
var mlContext = new MLContext();
// Create an root cause localization input instance.
DateTime timestamp = GetTimestamp();
var data = new RootCauseLocalizationInput(timestamp, GetAnomalyDimension(), new List<MetricSlice>() { new MetricSlice(timestamp, GetPoints()) }, AggregateType.Sum, AGG_SYMBOL);
// Get the root cause localization result.
RootCause prediction = mlContext.AnomalyDetection.LocalizeRootCause(data);
// Print the localization result.
int count = 0;
foreach (RootCauseItem item in prediction.Items)
{
count++;
Console.WriteLine($"Root cause item #{count} ...");
Console.WriteLine($"Score: {item.Score}, Path: {String.Join(" ", item.Path)}, Direction: {item.Direction}, Dimension:{String.Join(" ", item.Dimension)}");
}
//Item #1 ...
//Score: 0.26670448876705927, Path: DataCenter, Direction: Up, Dimension:[Country, UK] [DeviceType, ##SUM##] [DataCenter, DC1]
}
private static List<TimeSeriesPoint> GetPoints()
{
List<TimeSeriesPoint> points = new List<TimeSeriesPoint>();
Dictionary<string, Object> dic1 = new Dictionary<string, Object>();
dic1.Add("Country", "UK");
dic1.Add("DeviceType", "Laptop");
dic1.Add("DataCenter", "DC1");
points.Add(new TimeSeriesPoint(200, 100, true, dic1));
Dictionary<string, Object> dic2 = new Dictionary<string, Object>();
dic2.Add("Country", "UK");
dic2.Add("DeviceType", "Mobile");
dic2.Add("DataCenter", "DC1");
points.Add(new TimeSeriesPoint(1000, 100, true, dic2));
Dictionary<string, Object> dic3 = new Dictionary<string, Object>();
dic3.Add("Country", "UK");
dic3.Add("DeviceType", AGG_SYMBOL);
dic3.Add("DataCenter", "DC1");
points.Add(new TimeSeriesPoint(1200, 200, true, dic3));
Dictionary<string, Object> dic4 = new Dictionary<string, Object>();
dic4.Add("Country", "UK");
dic4.Add("DeviceType", "Laptop");
dic4.Add("DataCenter", "DC2");
points.Add(new TimeSeriesPoint(100, 100, false, dic4));
Dictionary<string, Object> dic5 = new Dictionary<string, Object>();
dic5.Add("Country", "UK");
dic5.Add("DeviceType", "Mobile");
dic5.Add("DataCenter", "DC2");
points.Add(new TimeSeriesPoint(200, 200, false, dic5));
Dictionary<string, Object> dic6 = new Dictionary<string, Object>();
dic6.Add("Country", "UK");
dic6.Add("DeviceType", AGG_SYMBOL);
dic6.Add("DataCenter", "DC2");
points.Add(new TimeSeriesPoint(300, 300, false, dic6));
Dictionary<string, Object> dic7 = new Dictionary<string, Object>();
dic7.Add("Country", "UK");
dic7.Add("DeviceType", AGG_SYMBOL);
dic7.Add("DataCenter", AGG_SYMBOL);
points.Add(new TimeSeriesPoint(1500, 500, true, dic7));
Dictionary<string, Object> dic8 = new Dictionary<string, Object>();
dic8.Add("Country", "UK");
dic8.Add("DeviceType", "Laptop");
dic8.Add("DataCenter", AGG_SYMBOL);
points.Add(new TimeSeriesPoint(300, 200, true, dic8));
Dictionary<string, Object> dic9 = new Dictionary<string, Object>();
dic9.Add("Country", "UK");
dic9.Add("DeviceType", "Mobile");
dic9.Add("DataCenter", AGG_SYMBOL);
points.Add(new TimeSeriesPoint(1200, 300, true, dic9));
return points;
}
private static Dictionary<string, Object> GetAnomalyDimension()
{
Dictionary<string, Object> dim = new Dictionary<string, Object>();
dim.Add("Country", "UK");
dim.Add("DeviceType", AGG_SYMBOL);
dim.Add("DataCenter", AGG_SYMBOL);
return dim;
}
private static DateTime GetTimestamp()
{
return new DateTime(2020, 3, 23, 0, 0, 0);
}
}
}
| LocalizeRootCause |
csharp | dotnet__orleans | src/api/Orleans.Runtime/Orleans.Runtime.cs | {
"start": 3911,
"end": 5022
} | partial class ____
{
public const bool DEFAULT_ANCHORING_FILTER_ENABLED = true;
public const int DEFAULT_MAX_EDGE_COUNT = 10000;
public const int DEFAULT_MAX_UNPROCESSED_EDGES = 100000;
public static readonly System.TimeSpan DEFAULT_MAXIMUM_ROUND_PERIOD;
public static readonly System.TimeSpan DEFAULT_MINUMUM_ROUND_PERIOD;
public const double DEFAULT_PROBABILISTIC_FILTERING_MAX_ALLOWED_ERROR = 0.01D;
public static readonly System.TimeSpan DEFAULT_RECOVERY_PERIOD;
public bool AnchoringFilterEnabled { get { throw null; } set { } }
public int MaxEdgeCount { get { throw null; } set { } }
public System.TimeSpan MaxRoundPeriod { get { throw null; } set { } }
public int MaxUnprocessedEdges { get { throw null; } set { } }
public System.TimeSpan MinRoundPeriod { get { throw null; } set { } }
public double ProbabilisticFilteringMaxAllowedErrorRate { get { throw null; } set { } }
public System.TimeSpan RecoveryPeriod { get { throw null; } set { } }
}
| ActivationRepartitionerOptions |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryCrudTests.References.cs | {
"start": 2614,
"end": 3712
} | public class ____ : ServiceStack.AuditBase
{
[AutoIncrement] public int Id { get; set; }
[References(typeof(Job))] public int JobId { get; set; }
[References(typeof(Contact))] public int ContactId { get; set; }
[Reference] public Job Position { get; set; }
[Reference] public Contact Applicant { get; set; }
public DateTime AppliedDate { get; set; }
[Reference] public List<JobApplicationAttachment> Attachments { get; set; }
[Reference, Ref(Model = nameof(PhoneScreen), RefId = nameof(Id))]
public PhoneScreen PhoneScreen { get; set; }
public JobApplicationStatus ApplicationStatus { get; set; }
}
[Icon(Svg =
"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 15 15'><path fill='currentColor' d='M0 4.5V0h1v4.5a1.5 1.5 0 1 0 3 0v-3a.5.5 0 0 0-1 0V5H2V1.5a1.5 1.5 0 1 1 3 0v3a2.5 2.5 0 0 1-5 0Z'/><path fill='currentColor' fill-rule='evenodd' d='M12.5 0H6v4.5A3.5 3.5 0 0 1 2.5 8H1v5.5A1.5 1.5 0 0 0 2.5 15h10a1.5 1.5 0 0 0 1.5-1.5v-12A1.5 1.5 0 0 0 12.5 0ZM11 4H7v1h4V4Zm0 3H7v1h4V7Zm-7 3h7v1H4v-1Z' clip-rule='evenodd'/></svg>")]
| JobApplication |
csharp | nunit__nunit | src/NUnitFramework/testdata/FailingActionAttributeOnFixtureFixture.cs | {
"start": 404,
"end": 754
} | public sealed class ____
{
[ExceptionThrowingAction]
[Test]
public void Test1()
{
Assert.Pass("Test passed");
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
| FailingActionAttributeOnTestFixture |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/Model/Pfa/ICanSavePfa.cs | {
"start": 1737,
"end": 2107
} | internal interface ____ : ISaveAsPfa, IDataTransform
{
}
/// <summary>
/// This <see cref="ISchemaBindableMapper"/> is savable as a PFA. Note that this is
/// typically called within an <see cref="IDataScorerTransform"/> that is wrapping
/// this mapper, and has already been bound to it.
/// </summary>
[BestFriend]
| ITransformCanSavePfa |
csharp | EventStore__EventStore | src/KurrentDB.Common/Utils/NumberExtensions.cs | {
"start": 232,
"end": 1264
} | public static class ____ {
public static long RoundDownToMultipleOf(this long x, int multiple) {
return (x / multiple) * multiple;
}
public static long RoundUpToMultipleOf(this long x, int multiple) {
var ret = x.RoundDownToMultipleOf(multiple);
if (ret != x) {
ret += multiple;
}
return ret;
}
public static int RoundDownToMultipleOf(this int x, int multiple) {
return (x / multiple) * multiple;
}
public static int RoundUpToMultipleOf(this int x, int multiple) {
var ret = x.RoundDownToMultipleOf(multiple);
if (ret != x) {
ret += multiple;
}
return ret;
}
public static long ScaleByWeight(this long x, int weight, int totalWeight) {
if (totalWeight <= 0)
throw new ArgumentOutOfRangeException(nameof(totalWeight));
if (weight < 0 || weight > totalWeight)
throw new ArgumentOutOfRangeException(nameof(weight));
return (long)((double)x * weight / totalWeight);
}
public static long ScaleByPercent(this long x, int percent) =>
ScaleByWeight(x, percent, 100);
}
| NumberExtensions |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Email.Core/Services/DefaultEmailProviderResolver.cs | {
"start": 127,
"end": 1298
} | public class ____ : IEmailProviderResolver
{
private readonly EmailOptions _emailOptions;
private readonly IServiceProvider _serviceProvider;
private readonly EmailProviderOptions _providerOptions;
public DefaultEmailProviderResolver(
IOptions<EmailOptions> emailOptions,
IOptions<EmailProviderOptions> providerOptions,
IServiceProvider serviceProvider)
{
_emailOptions = emailOptions.Value;
_serviceProvider = serviceProvider;
_providerOptions = providerOptions.Value;
}
public ValueTask<IEmailProvider> GetAsync(string name = null)
{
if (string.IsNullOrEmpty(name))
{
name = _emailOptions.DefaultProviderName;
}
if (!string.IsNullOrEmpty(name))
{
if (_providerOptions.Providers.TryGetValue(name, out var providerType))
{
return ValueTask.FromResult(_serviceProvider.CreateInstance<IEmailProvider>(providerType.Type));
}
throw new InvalidEmailProviderException(name);
}
return ValueTask.FromResult<IEmailProvider>(null);
}
}
| DefaultEmailProviderResolver |
csharp | DapperLib__Dapper | benchmarks/Dapper.Tests.Performance/PetaPoco/PetaPoco.cs | {
"start": 2572,
"end": 16606
} | public class ____ : IDisposable
{
public Database(DbConnection connection)
{
_sharedConnection = connection;
_connectionString = connection.ConnectionString;
_sharedConnectionDepth = 2; // Prevent closing external connection
CommonConstruct();
}
public Database(string connectionString, string providerName)
{
_connectionString = connectionString;
_providerName = providerName;
CommonConstruct();
}
public Database(string connectionStringName)
{
// Use first?
if (connectionStringName == string.Empty)
connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
// Work out connection string and provider name
var providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
else
{
throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'");
}
// Store factory and connection string
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = providerName;
CommonConstruct();
}
private
// Common initialization
void CommonConstruct()
{
_transactionDepth = 0;
EnableAutoSelect = true;
EnableNamedParams = true;
ForceDateTimesToUtc = true;
if (_providerName != null)
_factory = DbProviderFactories.GetFactory(_providerName);
if (_connectionString?.IndexOf("Allow User Variables=true") >= 0 && IsMySql())
_paramPrefix = "?";
}
// Automatically close one open shared connection
public void Dispose()
{
if (_sharedConnectionDepth > 0)
CloseSharedConnection();
}
// Who are we talking too?
private bool IsMySql() { return string.Compare(_providerName, "MySql.Data.MySqlClient", true) == 0; }
private bool IsSqlServer() { return string.Compare(_providerName, "System.Data.SqlClient", true) == 0; }
// Open a connection (can be nested)
public void OpenSharedConnection()
{
if (_sharedConnectionDepth == 0)
{
_sharedConnection = _factory.CreateConnection();
_sharedConnection.ConnectionString = _connectionString;
_sharedConnection.Open();
}
_sharedConnectionDepth++;
}
// Close a previously opened connection
public void CloseSharedConnection()
{
_sharedConnectionDepth--;
if (_sharedConnectionDepth == 0)
{
_sharedConnection.Dispose();
_sharedConnection = null;
}
}
// Helper to create a transaction scope
public Transaction Transaction => new Transaction(this);
// Use by derived repo generated by T4 templates
public virtual void OnBeginTransaction() { }
public virtual void OnEndTransaction() { }
// Start a new transaction, can be nested, every call must be
// matched by a call to AbortTransaction or CompleteTransaction
// Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics
public void BeginTransaction()
{
_transactionDepth++;
if (_transactionDepth == 1)
{
OpenSharedConnection();
_transaction = _sharedConnection.BeginTransaction();
_transactionCancelled = false;
OnBeginTransaction();
}
}
private
// Internal helper to cleanup transaction stuff
void CleanupTransaction()
{
OnEndTransaction();
if (_transactionCancelled)
_transaction.Rollback();
else
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
CloseSharedConnection();
}
// Abort the entire outer most transaction scope
public void AbortTransaction()
{
_transactionCancelled = true;
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
// Complete the transaction
public void CompleteTransaction()
{
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
// Helper to handle named parameters from object properties
private static readonly Regex rxParams = new Regex(@"(?<!@)@\w+", RegexOptions.Compiled);
public static string ProcessParams(string _sql, object[] args_src, List<object> args_dest)
{
return rxParams.Replace(_sql, m =>
{
string param = m.Value.Substring(1);
if (int.TryParse(param, out int paramIndex))
{
// Numbered parameter
if (paramIndex < 0 || paramIndex >= args_src.Length)
throw new ArgumentOutOfRangeException(string.Format("Parameter '@{0}' specified but only {1} parameters supplied (in `{2}`)", paramIndex, args_src.Length, _sql));
args_dest.Add(args_src[paramIndex]);
}
else
{
// Look for a property on one of the arguments with this name
bool found = false;
foreach (var o in args_src)
{
var pi = o.GetType().GetProperty(param);
if (pi != null)
{
args_dest.Add(pi.GetValue(o, null));
found = true;
break;
}
}
if (!found)
throw new ArgumentException(string.Format("Parameter '@{0}' specified but none of the passed arguments have a property with this name (in '{1}')", param, _sql));
}
return "@" + (args_dest.Count - 1).ToString();
}
);
}
// Add a parameter to a DB command
private static void AddParam(DbCommand cmd, object item, string ParameterPrefix)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
p.Size = 4000;
p.Value = item;
}
else
{
p.Value = item;
}
}
cmd.Parameters.Add(p);
}
// Create a command
public DbCommand CreateCommand(DbConnection connection, string sql, params object[] args)
{
if (EnableNamedParams)
{
// Perform named argument replacements
var new_args = new List<object>();
sql = ProcessParams(sql, args, new_args);
args = new_args.ToArray();
}
// If we're in MySQL "Allow User Variables", we need to fix up parameter prefixes
if (_paramPrefix == "?")
{
// Convert "@parameter" -> "?parameter"
Regex paramReg = new Regex(@"(?<!@)@\w+");
sql = paramReg.Replace(sql, m => "?" + m.Value.Substring(1));
// Convert @@uservar -> @uservar and @@@systemvar -> @@systemvar
sql = sql.Replace("@@", "@");
}
// Save the last sql and args
_lastSql = sql;
_lastArgs = args;
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
cmd.Transaction = _transaction;
foreach (var item in args)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
p.Size = 4000;
p.Value = item;
}
else
{
p.Value = item;
}
}
cmd.Parameters.Add(p);
}
return cmd;
}
// Override this to log/capture exceptions
public virtual void OnException(Exception x)
{
System.Diagnostics.Debug.WriteLine(x.ToString());
System.Diagnostics.Debug.WriteLine(LastCommand);
}
// Execute a non-query command
public int Execute(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
return cmd.ExecuteNonQuery();
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public int Execute(Sql sql)
{
return Execute(sql.SQL, sql.Arguments);
}
// Execute and cast a scalar property
public T ExecuteScalar<T>(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
object val = cmd.ExecuteScalar();
return (T)Convert.ChangeType(val, typeof(T));
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public T ExecuteScalar<T>(Sql sql)
{
return ExecuteScalar<T>(sql.SQL, sql.Arguments);
}
private readonly Regex rxSelect = new Regex(@"^\s*SELECT\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
private string AddSelectClause<T>(string sql)
{
// Already present?
if (rxSelect.IsMatch(sql))
return sql;
// Get the poco data for this type
var pd = PocoData.ForType(typeof(T));
return string.Format("SELECT {0} FROM {1} {2}", pd.QueryColumns, pd.TableName, sql);
}
public bool EnableAutoSelect { get; set; }
public bool EnableNamedParams { get; set; }
public bool ForceDateTimesToUtc { get; set; }
// Return a typed list of pocos
public List<T> Fetch<T>(string sql, params object[] args) where T : new()
{
// Auto select clause?
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
using (var r = cmd.ExecuteReader())
{
var l = new List<T>();
var pd = PocoData.ForType(typeof(T));
var factory = pd.GetFactory<T>(sql + "-" + _sharedConnection.ConnectionString + ForceDateTimesToUtc.ToString(), ForceDateTimesToUtc, r);
while (r.Read())
{
l.Add(factory(r));
}
return l;
}
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
// Optimized version when only needing a single | Database |
csharp | jellyfin__jellyfin | MediaBrowser.Controller/Net/WebSocketMessages/Inbound/ScheduledTasksInfoStartMessage.cs | {
"start": 271,
"end": 844
} | public class ____ : InboundWebSocketMessage<string>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTasksInfoStartMessage"/> class.
/// </summary>
/// <param name="data">The timing data encoded as $initialDelay,$interval.</param>
public ScheduledTasksInfoStartMessage(string data)
: base(data)
{
}
/// <inheritdoc />
[DefaultValue(SessionMessageType.ScheduledTasksInfoStart)]
public override SessionMessageType MessageType => SessionMessageType.ScheduledTasksInfoStart;
}
| ScheduledTasksInfoStartMessage |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Media/Effects/ExposureEffect.cs | {
"start": 513,
"end": 1487
} | public sealed class ____ : PipelineEffect
{
private double amount;
/// <summary>
/// Gets or sets the amount of exposure to apply to the background (defaults to 0, should be in the [-2, 2] range).
/// </summary>
public double Amount
{
get => this.amount;
set => this.amount = Math.Clamp(value, -2, 2);
}
/// <summary>
/// Gets the unique id for the effect, if <see cref="PipelineEffect.IsAnimatable"/> is set.
/// </summary>
internal string? Id { get; private set; }
/// <inheritdoc/>
public override PipelineBuilder AppendToBuilder(PipelineBuilder builder)
{
if (IsAnimatable)
{
builder = builder.Exposure((float)Amount, out string id);
Id = id;
return builder;
}
return builder.Exposure((float)Amount);
}
}
} | ExposureEffect |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.