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 | RicoSuter__NJsonSchema | src/NJsonSchema/Infrastructure/DynamicApis.cs | {
"start": 3564,
"end": 7365
} | enum ____ loaded)
// NOTE: we can't use All or -1 since those weren't in the 4.0 version of the enum, but we
// still want to enable additional decompression methods like Brotli (and potentially
// additional ones in the future) if the loaded httpclient supports it.
// while the existing values would allow doing a Sum, we still bitwise or to be defensive about
// potential additions in the future of values like "GZipOrDeflate"
var calculatedAllValue = Enum.GetValues(DecompressionMethodsType!)
.Cast<int>()
.Where(val => val > 0) // filter to only positive so we're not including All or None
.Aggregate(0, (accumulated, newValue) => accumulated | newValue);
return calculatedAllValue;
}
/// <summary>
/// Handle cases of specs in subdirectories having external references to specs also in subdirectories
/// </summary>
/// <param name="fullPath"></param>
/// <param name="jsonPath"></param>
/// <returns></returns>
public static string HandleSubdirectoryRelativeReferences(string fullPath, string jsonPath)
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(fullPath)))
{
var fileName = Path.GetFileName(fullPath);
var directoryName = Path.GetDirectoryName(fullPath)!;
var folderName = directoryName.Replace("\\", "/").Split('/').Last();
var parentDirectory = Directory.GetParent(directoryName);
if (!string.IsNullOrWhiteSpace(parentDirectory?.FullName))
{
foreach (string subDir in Directory.GetDirectories(parentDirectory!.FullName))
{
var expectedDir = Path.Combine(subDir, folderName);
var expectedFile = Path.Combine(expectedDir, fileName);
if (Directory.Exists(expectedDir))
{
fullPath = Path.Combine(expectedDir, fileName);
break;
}
}
}
}
if (!File.Exists(fullPath))
{
var fileDir = Path.GetDirectoryName(fullPath);
if (Directory.Exists(fileDir))
{
var fileName = Path.GetFileName(fullPath);
foreach (var subDir in Directory.GetDirectories(fileDir))
{
var expectedFile = Path.Combine(subDir, fileName);
if (File.Exists(expectedFile) && File.ReadAllText(expectedFile).Contains(jsonPath.Split('/').Last()))
{
fullPath = Path.Combine(subDir, fileName);
break;
}
}
}
}
return fullPath;
}
catch
{
return fullPath;
}
}
private static Type? TryLoadType(params string[] typeNames)
{
foreach (var typeName in typeNames)
{
try
{
var type = Type.GetType(typeName, false);
if (type != null)
{
return type;
}
}
catch
{
}
}
return null;
}
}
} | was |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine/CommandLineResources.Designer.cs | {
"start": 675,
"end": 2189
} | internal class ____ {
private static System.Resources.ResourceManager resourceMan;
private static System.Globalization.CultureInfo resourceCulture;
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal CommandLineResources() {
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Resources.ResourceManager ResourceManager {
get {
if (object.Equals(null, resourceMan)) {
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("ChilliCream.Nitro.CommandLine.CommandLineResources", typeof(CommandLineResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string RootCommand_Description {
get {
return ResourceManager.GetString("RootCommand_Description", resourceCulture);
}
}
}
}
| CommandLineResources |
csharp | dotnet__extensions | test/Libraries/Microsoft.Extensions.AI.Tests/Functions/AIFunctionFactoryTest.cs | {
"start": 46944,
"end": 47051
} | private sealed class ____;
private static int TestStaticMethod(int a, int b) => a + b;
| MyArgumentType |
csharp | unoplatform__uno | src/Uno.UI.Runtime.Skia.X11/X11_Bindings/x11bindings_X11Structs.cs | {
"start": 36169,
"end": 36557
} | public enum ____
{
USPosition = (1 << 0),
USSize = (1 << 1),
PPosition = (1 << 2),
PSize = (1 << 3),
PMinSize = (1 << 4),
PMaxSize = (1 << 5),
PResizeInc = (1 << 6),
PAspect = (1 << 7),
PAllHints = (PPosition | PSize | PMinSize | PMaxSize | PResizeInc | PAspect),
PBaseSize = (1 << 8),
PWinGravity = (1 << 9),
}
[StructLayout(LayoutKind.Sequential)]
| XSizeHintsFlags |
csharp | louthy__language-ext | LanguageExt.Tests/Multiplicable.cs | {
"start": 233,
"end": 497
} | public class ____
{
[Fact]
public void OptionalNumericMultiply()
{
var x = Some(10);
var y = Some(20);
var z = product<TInt, int>(x, y);
Assert.True(z == 200);
}
}
}
| Multiplicable |
csharp | grandnode__grandnode2 | src/Core/Grand.Domain/Courses/CourseLesson.cs | {
"start": 34,
"end": 1328
} | public class ____ : BaseEntity
{
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the short description
/// </summary>
public string ShortDescription { get; set; }
/// <summary>
/// Gets or sets the description
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the display order
/// </summary>
public int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets the course ident
/// </summary>
public string CourseId { get; set; }
/// <summary>
/// Gets or sets the subject ident
/// </summary>
public string SubjectId { get; set; }
/// <summary>
/// Gets or sets the video file
/// </summary>
public string VideoFile { get; set; }
/// <summary>
/// Gets or sets the attachment ident
/// </summary>
public string AttachmentId { get; set; }
/// <summary>
/// Gets or sets the picture
/// </summary>
public string PictureId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is published
/// </summary>
public bool Published { get; set; }
} | CourseLesson |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/DataAnnotationTestBase.cs | {
"start": 66866,
"end": 67181
} | public class ____
{
[Key]
public int UserUId { get; set; }
[InverseProperty(nameof(Relation.AccountManager))]
public virtual ICollection<Relation> AccountManagerRelations { get; set; }
public virtual ICollection<Relation> SalesManagerRelations { get; set; }
}
| User |
csharp | simplcommerce__SimplCommerce | src/SimplCommerce.Infrastructure/ValidationException.cs | {
"start": 159,
"end": 762
} | public class ____ : Exception
{
public ValidationException(Type target, IList<ValidationResult> validationResults)
{
TargetType = target;
ValidationResults = validationResults;
}
public IList<ValidationResult> ValidationResults { get; }
public Type TargetType { get; }
public override string Message
{
get
{
return string.Concat(TargetType.ToString(), ": ", string.Join(';', ValidationResults.Select(x => $"{x.ErrorMessage}")));
}
}
}
}
| ValidationException |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding101OneToOneNrtTestBase.cs | {
"start": 14379,
"end": 14746
} | public class ____ : BlogContext0
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Blog>()
.HasOne(e => e.Header)
.WithOne()
.HasForeignKey<BlogHeader>(e => e.BlogId)
.IsRequired();
}
| BlogContext1 |
csharp | dotnet__orleans | src/Orleans.Streaming/PersistentStreams/PersistentStreamPullingAgent.cs | {
"start": 31212,
"end": 35955
} | record ____ there was a delivery failure
if (isDeliveryError)
{
await streamFailureHandler.OnDeliveryFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing | ConfigureAwaitOptions.ContinueOnCapturedContext);
}
else
{
await streamFailureHandler.OnSubscriptionFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing | ConfigureAwaitOptions.ContinueOnCapturedContext);
}
// if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription
if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid))
{
try
{
// notify consumer of faulted subscription, if we can.
await DeliverErrorToConsumer(
consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing | ConfigureAwaitOptions.ContinueOnCapturedContext);
// mark subscription as faulted.
await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId);
}
finally
{
// remove subscription
RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId);
}
return true;
}
return false;
}
private static async Task<ISet<PubSubSubscriptionState>> PubsubRegisterProducer(IStreamPubSub pubSub, QualifiedStreamId streamId,
GrainId meAsStreamProducer, ILogger logger)
{
try
{
var streamData = await pubSub.RegisterProducer(streamId, meAsStreamProducer);
return streamData;
}
catch (Exception e)
{
LogErrorRegisterAsStreamProducer(logger, e);
throw;
}
}
private async Task RegisterAsStreamProducer(QualifiedStreamId streamId, StreamSequenceToken streamStartToken)
{
try
{
if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetrieveNewStream");
ISet<PubSubSubscriptionState> streamData = null;
await AsyncExecutorWithRetries.ExecuteWithRetries(
async i => { streamData =
await PubsubRegisterProducer(pubSub, streamId, GrainId, logger); },
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !IsShutdown,
Timeout.InfiniteTimeSpan,
deliveryBackoffProvider);
LogDebugGotBackSubscribers(streamData.Count, streamId);
var addSubscriptionTasks = new List<Task>(streamData.Count);
foreach (PubSubSubscriptionState item in streamData)
{
addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, item.FilterData, streamStartToken));
}
await Task.WhenAll(addSubscriptionTasks);
}
catch (Exception exc)
{
// RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
LogErrorIgnoredRegisterAsStreamProducer(exc);
throw;
}
}
private bool ShouldDeliverBatch(StreamId streamId, IBatchContainer batchContainer, string filterData)
{
if (this.streamFilter is NoOpStreamFilter)
return true;
try
{
foreach (var evt in batchContainer.GetEvents<object>())
{
if (this.streamFilter.ShouldDeliver(streamId, evt.Item1, filterData))
return true;
}
return false;
}
catch (Exception exc)
{
LogWarningFilterEvaluation(streamFilter.GetType().Name, filterData, streamId, exc);
}
return true;
}
private readonly | that |
csharp | unoplatform__uno | src/Uno.Foundation/Generated/2.0.0.0/Windows.Foundation.Metadata/ExperimentalAttribute.cs | {
"start": 262,
"end": 557
} | public partial class ____ : global::System.Attribute
{
// Skipping already declared method Windows.Foundation.Metadata.ExperimentalAttribute.ExperimentalAttribute()
// Forced skipping of method Windows.Foundation.Metadata.ExperimentalAttribute.ExperimentalAttribute()
}
}
| ExperimentalAttribute |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Aggregate.cs | {
"start": 4787,
"end": 5668
} | internal sealed class ____<TSource, TAccumulate, TResult> : Producer<TResult, Aggregate<TSource, TAccumulate, TResult>._>
{
private readonly IObservable<TSource> _source;
private readonly TAccumulate _seed;
private readonly Func<TAccumulate, TSource, TAccumulate> _accumulator;
private readonly Func<TAccumulate, TResult> _resultSelector;
public Aggregate(IObservable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector)
{
_source = source;
_seed = seed;
_accumulator = accumulator;
_resultSelector = resultSelector;
}
protected override _ CreateSink(IObserver<TResult> observer) => new(this, observer);
protected override void Run(_ sink) => sink.Run(_source);
| Aggregate |
csharp | dotnet__aspire | src/Aspire.Hosting.Azure/Provisioning/Internal/IProvisioningServices.cs | {
"start": 6551,
"end": 6741
} | internal interface ____
{
/// <summary>
/// Gets the token credential for Azure authentication.
/// </summary>
TokenCredential TokenCredential { get; }
}
| ITokenCredentialProvider |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Meetings/Infrastructure/Domain/MeetingGroups/MeetingGroupsEntityTypeConfiguration.cs | {
"start": 316,
"end": 2096
} | internal class ____ : IEntityTypeConfiguration<MeetingGroup>
{
public void Configure(EntityTypeBuilder<MeetingGroup> builder)
{
builder.ToTable("MeetingGroups", "meetings");
builder.HasKey(x => x.Id);
builder.Property<string>("_name").HasColumnName("Name");
builder.Property<string>("_description").HasColumnName("Description");
builder.Property<MemberId>("_creatorId").HasColumnName("CreatorId");
builder.Property<DateTime>("_createDate").HasColumnName("CreateDate");
builder.Property<DateTime?>("_paymentDateTo").HasColumnName("PaymentDateTo");
builder.OwnsOne<MeetingGroupLocation>("_location", b =>
{
b.Property(p => p.City).HasColumnName("LocationCity");
b.Property(p => p.CountryCode).HasColumnName("LocationCountryCode");
});
builder.OwnsMany<MeetingGroupMember>("_members", y =>
{
y.WithOwner().HasForeignKey("MeetingGroupId");
y.ToTable("MeetingGroupMembers", "meetings");
y.Property<MemberId>("MemberId");
y.Property<MeetingGroupId>("MeetingGroupId");
y.Property<DateTime>("JoinedDate").HasColumnName("JoinedDate");
y.HasKey("MemberId", "MeetingGroupId", "JoinedDate");
y.Property<DateTime?>("_leaveDate").HasColumnName("LeaveDate");
y.Property<bool>("_isActive").HasColumnName("IsActive");
y.OwnsOne<MeetingGroupMemberRole>("_role", b =>
{
b.Property<string>(x => x.Value).HasColumnName("RoleCode");
});
});
}
}
}
| MeetingGroupsEntityTypeConfiguration |
csharp | dotnet__aspnetcore | src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/SqlServer/00000000000000_CreateIdentitySchema.Designer.cs | {
"start": 474,
"end": 10498
} | partial class ____
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| CreateIdentitySchema |
csharp | dotnet__aspnetcore | src/Http/WebUtilities/src/MultipartReader.cs | {
"start": 401,
"end": 5837
} | public class ____
{
/// <summary>
/// Gets the default value for <see cref="HeadersCountLimit"/>.
/// Defaults to 16.
/// </summary>
public const int DefaultHeadersCountLimit = 16;
/// <summary>
/// Gets the default value for <see cref="HeadersLengthLimit"/>.
/// Defaults to 16,384 bytes, which is approximately 16KB.
/// </summary>
public const int DefaultHeadersLengthLimit = 1024 * 16;
private const int DefaultBufferSize = 1024 * 4;
private readonly BufferedReadStream _stream;
private readonly MultipartBoundary _boundary;
private MultipartReaderStream? _currentStream;
/// <summary>
/// Initializes a new instance of <see cref="MultipartReader"/>.
/// </summary>
/// <param name="boundary">The multipart boundary.</param>
/// <param name="stream">The <see cref="Stream"/> containing multipart data.</param>
public MultipartReader(string boundary, Stream stream)
: this(boundary, stream, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of <see cref="MultipartReader"/>.
/// </summary>
/// <param name="boundary">The multipart boundary.</param>
/// <param name="stream">The <see cref="Stream"/> containing multipart data.</param>
/// <param name="bufferSize">The minimum buffer size to use.</param>
public MultipartReader(string boundary, Stream stream, int bufferSize)
{
ArgumentNullException.ThrowIfNull(boundary);
ArgumentNullException.ThrowIfNull(stream);
if (bufferSize < boundary.Length + 8) // Size of the boundary + leading and trailing CRLF + leading and trailing '--' markers.
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "Insufficient buffer space, the buffer must be larger than the boundary: " + boundary);
}
_stream = new BufferedReadStream(stream, bufferSize);
boundary = HeaderUtilities.RemoveQuotes(new StringSegment(boundary)).ToString();
_boundary = new MultipartBoundary(boundary);
}
/// <summary>
/// The limit for the number of headers to read.
/// </summary>
public int HeadersCountLimit { get; set; } = DefaultHeadersCountLimit;
/// <summary>
/// The combined size limit for headers per multipart section.
/// </summary>
public int HeadersLengthLimit { get; set; } = DefaultHeadersLengthLimit;
/// <summary>
/// The optional limit for the body length of each multipart section.
/// The hosting server is responsible for limiting the overall body length.
/// </summary>
public long? BodyLengthLimit { get; set; }
/// <summary>
/// Reads the next <see cref="MultipartSection"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.
/// The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns></returns>
public async Task<MultipartSection?> ReadNextSectionAsync(CancellationToken cancellationToken = new CancellationToken())
{
// Only occurs on first call
// This stream will drain any preamble data and remove the first boundary marker.
_currentStream ??= new MultipartReaderStream(_stream, _boundary) { LengthLimit = HeadersLengthLimit };
// Drain the prior section.
await _currentStream.DrainAsync(cancellationToken);
// If we're at the end return null
if (_currentStream.FinalBoundaryFound)
{
// There may be trailer data after the last boundary.
await _stream.DrainAsync(HeadersLengthLimit, cancellationToken);
return null;
}
var headers = await ReadHeadersAsync(cancellationToken);
_boundary.ExpectLeadingCrlf();
_currentStream = new MultipartReaderStream(_stream, _boundary) { LengthLimit = BodyLengthLimit };
long? baseStreamOffset = _stream.CanSeek ? (long?)_stream.Position : null;
return new MultipartSection() { Headers = headers, Body = _currentStream, BaseStreamOffset = baseStreamOffset };
}
private async Task<Dictionary<string, StringValues>> ReadHeadersAsync(CancellationToken cancellationToken)
{
int totalSize = 0;
var accumulator = new KeyValueAccumulator();
var line = await _stream.ReadLineAsync(HeadersLengthLimit, cancellationToken);
while (!string.IsNullOrEmpty(line))
{
if (HeadersLengthLimit - totalSize < line.Length)
{
throw new InvalidDataException($"Multipart headers length limit {HeadersLengthLimit} exceeded.");
}
totalSize += line.Length;
int splitIndex = line.IndexOf(':');
if (splitIndex <= 0)
{
throw new InvalidDataException($"Invalid header line: {line}");
}
var name = line.Substring(0, splitIndex);
var value = line.Substring(splitIndex + 1, line.Length - splitIndex - 1).Trim();
accumulator.Append(name, value);
if (accumulator.KeyCount > HeadersCountLimit)
{
throw new InvalidDataException($"Multipart headers count limit {HeadersCountLimit} exceeded.");
}
line = await _stream.ReadLineAsync(HeadersLengthLimit - totalSize, cancellationToken);
}
return accumulator.GetResults();
}
}
| MultipartReader |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Controls.UnitTests/TabControlTests.cs | {
"start": 583,
"end": 27946
} | public class ____ : ScopedTestBase
{
static TabControlTests()
{
RuntimeHelpers.RunClassConstructor(typeof(RelativeSource).TypeHandle);
}
[Fact]
public void First_Tab_Should_Be_Selected_By_Default()
{
TabItem selected;
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
(selected = new TabItem
{
Name = "first",
Content = "foo",
}),
new TabItem
{
Name = "second",
Content = "bar",
},
}
};
target.ApplyTemplate();
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(selected, target.SelectedItem);
}
[Fact]
public void Pre_Selecting_TabItem_Should_Set_SelectedContent_After_It_Was_Added()
{
const string secondContent = "Second";
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem { Header = "First"},
new TabItem { Header = "Second", Content = secondContent, IsSelected = true }
},
};
ApplyTemplate(target);
Assert.Equal(secondContent, target.SelectedContent);
}
[Fact]
public void Logical_Children_Should_Be_TabItems()
{
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem
{
Content = "foo"
},
new TabItem
{
Content = "bar"
},
}
};
Assert.Equal(target.Items, target.GetLogicalChildren().ToList());
target.ApplyTemplate();
Assert.Equal(target.Items, target.GetLogicalChildren().ToList());
}
[Fact]
public void Removal_Should_Set_First_Tab()
{
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem
{
Name = "first",
Content = "foo",
},
new TabItem
{
Name = "second",
Content = "bar",
},
new TabItem
{
Name = "3rd",
Content = "barf",
},
}
};
Prepare(target);
target.SelectedItem = target.Items[1];
var item = Assert.IsType<TabItem>(target.Items[1]);
Assert.Same(item, target.SelectedItem);
Assert.Equal(item.Content, target.SelectedContent);
target.Items.RemoveAt(1);
item = Assert.IsType<TabItem>(target.Items[0]);
Assert.Same(item, target.SelectedItem);
Assert.Equal(item.Content, target.SelectedContent);
}
[Fact]
public void Removal_Should_Set_New_Item0_When_Item0_Selected()
{
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem
{
Name = "first",
Content = "foo",
},
new TabItem
{
Name = "second",
Content = "bar",
},
new TabItem
{
Name = "3rd",
Content = "barf",
},
}
};
Prepare(target);
target.SelectedItem = target.Items[0];
var item = Assert.IsType<TabItem>(target.Items[0]);
Assert.Same(item, target.SelectedItem);
Assert.Equal(item.Content, target.SelectedContent);
target.Items.RemoveAt(0);
item = Assert.IsType<TabItem>(target.Items[0]);
Assert.Same(item, target.SelectedItem);
Assert.Equal(item.Content, target.SelectedContent);
}
[Fact]
public void Removal_Should_Set_New_Item0_When_Item0_Selected_With_DataTemplate()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
var collection = new ObservableCollection<Item>()
{
new Item("first"),
new Item("second"),
new Item("3rd"),
};
var target = new TabControl
{
Template = TabControlTemplate(),
ItemsSource = collection,
};
Prepare(target);
target.SelectedItem = collection[0];
Assert.Same(collection[0], target.SelectedItem);
Assert.Equal(collection[0], target.SelectedContent);
collection.RemoveAt(0);
Assert.Same(collection[0], target.SelectedItem);
Assert.Equal(collection[0], target.SelectedContent);
}
[Fact]
public void TabItem_Templates_Should_Be_Set_Before_TabItem_ApplyTemplate()
{
var template = new FuncControlTemplate<TabItem>((x, __) => new Decorator());
TabControl target;
var root = new TestRoot
{
Styles =
{
new Style(x => x.OfType<TabItem>())
{
Setters =
{
new Setter(TemplatedControl.TemplateProperty, template)
}
}
},
Child = (target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem
{
Name = "first",
Content = "foo",
},
new TabItem
{
Name = "second",
Content = "bar",
},
new TabItem
{
Name = "3rd",
Content = "barf",
},
},
})
};
var collection = target.Items.Cast<TabItem>().ToList();
Assert.Same(collection[0].Template, template);
Assert.Same(collection[1].Template, template);
Assert.Same(collection[2].Template, template);
}
[Fact]
public void DataContexts_Should_Be_Correctly_Set()
{
var items = new object[]
{
"Foo",
new Item("Bar"),
new TextBlock { Text = "Baz" },
new TabItem { Content = "Qux" },
new TabItem { Content = new TextBlock { Text = "Bob" } }
};
var target = new TabControl
{
Template = TabControlTemplate(),
DataContext = "Base",
DataTemplates =
{
new FuncDataTemplate<Item>((x, __) => new Button { Content = x })
},
ItemsSource = items,
};
ApplyTemplate(target);
target.ContentPart.UpdateChild();
var dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal(items[0], dataContext);
target.SelectedIndex = 1;
target.ContentPart.UpdateChild();
dataContext = ((Button)target.ContentPart.Child).DataContext;
Assert.Equal(items[1], dataContext);
target.SelectedIndex = 2;
target.ContentPart.UpdateChild();
dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal("Base", dataContext);
target.SelectedIndex = 3;
target.ContentPart.UpdateChild();
dataContext = ((TextBlock)target.ContentPart.Child).DataContext;
Assert.Equal("Qux", dataContext);
target.SelectedIndex = 4;
target.ContentPart.UpdateChild();
dataContext = target.ContentPart.DataContext;
Assert.Equal("Base", dataContext);
}
/// <summary>
/// Non-headered control items should result in TabItems with empty header.
/// </summary>
/// <remarks>
/// If a TabControl is created with non IHeadered controls as its items, don't try to
/// display the control in the header: if the control is part of the header then
/// *that* control would also end up in the content region, resulting in dual-parentage
/// breakage.
/// </remarks>
[Fact]
public void Non_IHeadered_Control_Items_Should_Be_Ignored()
{
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TextBlock { Text = "foo" },
new TextBlock { Text = "bar" },
},
};
ApplyTemplate(target);
var logicalChildren = target.GetLogicalChildren();
var result = logicalChildren
.OfType<TabItem>()
.Select(x => x.Header)
.ToList();
Assert.Equal(new object[] { null, null }, result);
}
[Fact]
public void Should_Handle_Changing_To_TabItem_With_Null_Content()
{
TabControl target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem { Header = "Foo" },
new TabItem { Header = "Foo", Content = new Decorator() },
new TabItem { Header = "Baz" },
},
};
ApplyTemplate(target);
target.SelectedIndex = 2;
var page = (TabItem)target.SelectedItem;
Assert.Null(page.Content);
}
[Fact]
public void DataTemplate_Created_Content_Should_Be_Logical_Child_After_ApplyTemplate()
{
TabControl target = new TabControl
{
Template = TabControlTemplate(),
ContentTemplate = new FuncDataTemplate<string>((x, _) =>
new TextBlock { Tag = "bar", Text = x }),
ItemsSource = new[] { "Foo" },
};
var root = new TestRoot(target);
ApplyTemplate(target);
target.ContentPart.UpdateChild();
var content = Assert.IsType<TextBlock>(target.ContentPart.Child);
Assert.Equal("bar", content.Tag);
Assert.Same(target, content.GetLogicalParent());
Assert.Single(target.GetLogicalChildren(), content);
}
[Fact]
public void SelectedContentTemplate_Updates_After_New_ContentTemplate()
{
TabControl target = new TabControl
{
Template = TabControlTemplate(),
ItemsSource = new[] { "Foo" },
};
var root = new TestRoot(target);
ApplyTemplate(target);
((ContentPresenter)target.ContentPart).UpdateChild();
Assert.Equal(null, Assert.IsType<TextBlock>(target.ContentPart.Child).Tag);
target.ContentTemplate = new FuncDataTemplate<string>((x, _) =>
new TextBlock { Tag = "bar", Text = x });
Assert.Equal("bar", Assert.IsType<TextBlock>(target.ContentPart.Child).Tag);
}
[Fact]
public void Previous_ContentTemplate_Is_Not_Reused_When_TabItem_Changes()
{
using var app = UnitTestApplication.Start(TestServices.StyledWindow);
int templatesBuilt = 0;
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
TabItemFactory("First tab content"),
TabItemFactory("Second tab content"),
},
};
var root = new TestRoot(target);
ApplyTemplate(target);
target.SelectedIndex = 0;
target.SelectedIndex = 1;
Assert.Equal(2, templatesBuilt);
TabItem TabItemFactory(object content) => new()
{
Content = content,
ContentTemplate = new FuncDataTemplate<object>((actual, ns) =>
{
Assert.Equal(content, actual);
templatesBuilt++;
return new Border();
})
};
}
[Fact]
public void Should_Not_Propagate_DataContext_To_TabItem_Content()
{
var dataContext = "DataContext";
var tabItem = new TabItem();
var target = new TabControl
{
Template = TabControlTemplate(),
DataContext = dataContext,
Items = { tabItem }
};
ApplyTemplate(target);
Assert.NotEqual(dataContext, tabItem.Content);
}
[Fact]
public void Can_Have_Empty_Tab_Control()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<TabControl Name='tabs' ItemsSource='{Binding Tabs}'/>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var tabControl = window.FindControl<TabControl>("tabs");
tabControl.DataContext = new { Tabs = new List<string>() };
window.ApplyTemplate();
Assert.Equal(0, tabControl.ItemsSource.Count());
}
}
[Fact]
public void Should_Have_Initial_SelectedValue()
{
var xaml = @"
<TabControl
xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'
x:DataType='TabItem'
x:Name='tabs'
Tag='World'
SelectedValue='{Binding $self.Tag}'
SelectedValueBinding='{Binding Header}'>
<TabItem Header='Hello'/>
<TabItem Header='World'/>
</TabControl>";
var tabControl = (TabControl)AvaloniaRuntimeXamlLoader.Load(xaml);
Assert.Equal("World", tabControl.SelectedValue);
Assert.Equal(1, tabControl.SelectedIndex);
}
[Fact]
public void Tab_Navigation_Should_Move_To_First_TabItem_When_No_Anchor_Element_Selected()
{
var services = TestServices.StyledWindow.With(
keyboardDevice: () => new KeyboardDevice());
using var app = UnitTestApplication.Start(services);
var target = new TabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem { Header = "foo" },
new TabItem { Header = "bar" },
new TabItem { Header = "baz" },
}
};
var button = new Button
{
Content = "Button",
[DockPanel.DockProperty] = Dock.Top,
};
var root = new TestRoot
{
Child = new DockPanel
{
Children =
{
button,
target,
}
}
};
var navigation = new KeyboardNavigationHandler();
navigation.SetOwner(root);
root.LayoutManager.ExecuteInitialLayoutPass();
button.Focus();
RaiseKeyEvent(button, Key.Tab);
var item = target.ContainerFromIndex(0);
Assert.Same(item, root.FocusManager.GetFocusedElement());
}
[Fact]
public void Tab_Navigation_Should_Move_To_Anchor_TabItem()
{
var services = TestServices.StyledWindow.With(
keyboardDevice: () => new KeyboardDevice());
using var app = UnitTestApplication.Start(services);
var target = new TestTabControl
{
Template = TabControlTemplate(),
Items =
{
new TabItem { Header = "foo" },
new TabItem { Header = "bar" },
new TabItem { Header = "baz" },
}
};
var button = new Button
{
Content = "Button",
[DockPanel.DockProperty] = Dock.Top,
};
var root = new TestRoot
{
Width = 1000,
Height = 1000,
Child = new DockPanel
{
Children =
{
button,
target,
}
}
};
var navigation = new KeyboardNavigationHandler();
navigation.SetOwner(root);
root.LayoutManager.ExecuteInitialLayoutPass();
button.Focus();
target.Selection.AnchorIndex = 1;
RaiseKeyEvent(button, Key.Tab);
var item = target.ContainerFromIndex(1);
Assert.Same(item, root.FocusManager.GetFocusedElement());
RaiseKeyEvent(item, Key.Tab);
Assert.Same(button, root.FocusManager.GetFocusedElement());
target.Selection.AnchorIndex = 2;
RaiseKeyEvent(button, Key.Tab);
item = target.ContainerFromIndex(2);
Assert.Same(item, root.FocusManager.GetFocusedElement());
}
[Fact]
public void TabItem_Header_Should_Be_Settable_By_Style_When_DataContext_Is_Set()
{
var tabItem = new TabItem
{
DataContext = "Some DataContext"
};
_ = new TestRoot
{
Styles =
{
new Style(x => x.OfType<TabItem>())
{
Setters =
{
new Setter(HeaderedContentControl.HeaderProperty, "Header from style")
}
}
},
Child = tabItem
};
Assert.Equal("Header from style", tabItem.Header);
}
[Fact]
public void TabItem_TabStripPlacement_Should_Be_Correctly_Set()
{
var items = new object[]
{
"Foo",
new TabItem { Content = new TextBlock { Text = "Baz" } }
};
var target = new TabControl
{
Template = TabControlTemplate(),
DataContext = "Base",
ItemsSource = items
};
ApplyTemplate(target);
var result = target.GetLogicalChildren()
.OfType<TabItem>()
.ToList();
Assert.Collection(
result,
x => Assert.Equal(Dock.Top, x.TabStripPlacement),
x => Assert.Equal(Dock.Top, x.TabStripPlacement)
);
target.TabStripPlacement = Dock.Right;
result = target.GetLogicalChildren()
.OfType<TabItem>()
.ToList();
Assert.Collection(
result,
x => Assert.Equal(Dock.Right, x.TabStripPlacement),
x => Assert.Equal(Dock.Right, x.TabStripPlacement)
);
}
[Fact]
public void TabItem_TabStripPlacement_Should_Be_Correctly_Set_For_New_Items()
{
var items = new object[]
{
"Foo",
new TabItem { Content = new TextBlock { Text = "Baz" } }
};
var target = new TabControl
{
Template = TabControlTemplate(),
DataContext = "Base"
};
ApplyTemplate(target);
target.ItemsSource = items;
var result = target.GetLogicalChildren()
.OfType<TabItem>()
.ToList();
Assert.Collection(
result,
x => Assert.Equal(Dock.Top, x.TabStripPlacement),
x => Assert.Equal(Dock.Top, x.TabStripPlacement)
);
target.TabStripPlacement = Dock.Right;
result = target.GetLogicalChildren()
.OfType<TabItem>()
.ToList();
Assert.Collection(
result,
x => Assert.Equal(Dock.Right, x.TabStripPlacement),
x => Assert.Equal(Dock.Right, x.TabStripPlacement)
);
}
[Theory]
[InlineData(Key.A, 1)]
[InlineData(Key.L, 2)]
[InlineData(Key.D, 0)]
public void Should_TabControl_Recognizes_AccessKey(Key accessKey, int selectedTabIndex)
{
var ah = new AccessKeyHandler();
var kd = new KeyboardDevice();
using (UnitTestApplication.Start(TestServices.StyledWindow
.With(
accessKeyHandler: ah,
keyboardDevice: () => kd)
))
{
var impl = CreateMockTopLevelImpl();
var tabControl = new TabControl()
{
Template = TabControlTemplate(),
Items =
{
new TabItem
{
Header = "General",
},
new TabItem { Header = "_Arch" },
new TabItem { Header = "_Leaf"},
new TabItem { Header = "_Disabled", IsEnabled = false },
}
};
kd.SetFocusedElement((TabItem)tabControl.Items[selectedTabIndex], NavigationMethod.Unspecified, KeyModifiers.None);
var root = new TestTopLevel(impl.Object)
{
Template = CreateTemplate(),
Content = tabControl,
};
root.ApplyTemplate();
root.Presenter.UpdateChild();
ApplyTemplate(tabControl);
KeyDown(root, Key.LeftAlt);
KeyDown(root, accessKey, KeyModifiers.Alt);
KeyUp(root, accessKey, KeyModifiers.Alt);
KeyUp(root, Key.LeftAlt);
Assert.Equal(selectedTabIndex, tabControl.SelectedIndex);
}
static FuncControlTemplate<TestTopLevel> CreateTemplate()
{
return new FuncControlTemplate<TestTopLevel>((x, scope) =>
new ContentPresenter
{
Name = "PART_ContentPresenter",
[~ContentPresenter.ContentProperty] = new TemplateBinding(ContentControl.ContentProperty),
[~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(ContentControl.ContentTemplateProperty)
}.RegisterInNameScope(scope));
}
static Mock<ITopLevelImpl> CreateMockTopLevelImpl(bool setupProperties = false)
{
var topLevel = new Mock<ITopLevelImpl>();
if (setupProperties)
topLevel.SetupAllProperties();
topLevel.Setup(x => x.RenderScaling).Returns(1);
topLevel.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
return topLevel;
}
static void KeyDown(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
{
target.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = key,
KeyModifiers = modifiers,
});
}
static void KeyUp(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
{
target.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyUpEvent,
Key = key,
KeyModifiers = modifiers,
});
}
}
private static IControlTemplate TabControlTemplate()
{
return new FuncControlTemplate<TabControl>((parent, scope) =>
new StackPanel
{
Children =
{
new ItemsPresenter
{
Name = "PART_ItemsPresenter",
}.RegisterInNameScope(scope),
new ContentPresenter
{
Name = "PART_SelectedContentHost",
[~ContentPresenter.ContentProperty] = new TemplateBinding(TabControl.SelectedContentProperty),
[~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(TabControl.SelectedContentTemplateProperty),
}.RegisterInNameScope(scope)
}
});
}
private static IControlTemplate TabItemTemplate()
{
return new FuncControlTemplate<TabItem>((parent, scope) =>
new ContentPresenter
{
Name = "PART_ContentPresenter",
[~ContentPresenter.ContentProperty] = new TemplateBinding(TabItem.HeaderProperty),
[~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(TabItem.HeaderTemplateProperty),
RecognizesAccessKey = true,
}.RegisterInNameScope(scope));
}
| TabControlTests |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/Conventions/StringObjectIdGeneratorConventionsTests.cs | {
"start": 854,
"end": 2517
} | public class ____
{
private StringObjectIdIdGeneratorConvention _subject;
public StringObjectIdIdGeneratorConventionsTests()
{
_subject = new StringObjectIdIdGeneratorConvention();
}
[Fact]
public void TestDoesNotSetWhenNoIdExists()
{
var classMap = new BsonClassMap<TestClass>(cm =>
{ });
_subject.PostProcess(classMap);
}
[Fact]
public void TestDoesNotSetWhenTypeIsntString()
{
var classMap = new BsonClassMap<TestClass>(cm =>
{
cm.MapIdMember(x => x.OId);
});
_subject.PostProcess(classMap);
Assert.Null(classMap.IdMemberMap.IdGenerator);
}
[Fact]
public void TestDoesNotSetWhenStringIsNotRepresentedAsObjectId()
{
var classMap = new BsonClassMap<TestClass>(cm =>
{
cm.MapIdMember(x => x.String);
});
_subject.PostProcess(classMap);
Assert.Null(classMap.IdMemberMap.IdGenerator);
}
[Fact]
public void TestSetsWhenIdIsStringAndRepresentedAsAnObjectId()
{
var classMap = new BsonClassMap<TestClass>(cm =>
{
cm.MapIdMember(x => x.String).SetSerializer(new StringSerializer(BsonType.ObjectId));
});
_subject.PostProcess(classMap);
Assert.NotNull(classMap.IdMemberMap.IdGenerator);
Assert.IsType<StringObjectIdGenerator>(classMap.IdMemberMap.IdGenerator);
}
| StringObjectIdIdGeneratorConventionsTests |
csharp | mysql-net__MySqlConnector | tests/Conformance.Tests/GetValueConversionTests.cs | {
"start": 128,
"end": 48286
} | public class ____ : GetValueConversionTestBase<SelectValueFixture>
{
public GetValueConversionTests(SelectValueFixture fixture)
: base(fixture)
{
}
// GetBoolean allows conversions from any integral type and decimal for backwards compatibility
public override void GetBoolean_throws_for_maximum_Byte() => TestGetValue(DbType.Byte, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_Byte_with_GetFieldValue() => TestGetValue(DbType.Byte, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_Byte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Byte, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_Int16() => TestGetValue(DbType.Int16, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_Int32() => TestGetValue(DbType.Int32, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_Int64() => TestGetValue(DbType.Int64, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_SByte() => TestGetValue(DbType.SByte, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_UInt16() => TestGetValue(DbType.UInt16, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_UInt32() => TestGetValue(DbType.UInt32, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_UInt64() => TestGetValue(DbType.UInt64, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_maximum_Decimal() => TestGetValue(DbType.Decimal, ValueKind.Maximum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_maximum_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.Maximum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_maximum_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.Maximum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_minimum_Byte() => TestGetValue(DbType.Byte, ValueKind.Minimum, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_minimum_Byte_with_GetFieldValue() => TestGetValue(DbType.Byte, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_minimum_Byte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Byte, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_minimum_Int16() => TestGetValue(DbType.Int16, ValueKind.Minimum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_minimum_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_minimum_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_minimum_Int32() => TestGetValue(DbType.Int32, ValueKind.Minimum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_minimum_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_minimum_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_minimum_Int64() => TestGetValue(DbType.Int64, ValueKind.Minimum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_minimum_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_minimum_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_minimum_SByte() => TestGetValue(DbType.SByte, ValueKind.Minimum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_minimum_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_minimum_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_minimum_UInt16() => TestGetValue(DbType.UInt16, ValueKind.Minimum, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_minimum_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_minimum_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_minimum_UInt32() => TestGetValue(DbType.UInt32, ValueKind.Minimum, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_minimum_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_minimum_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_minimum_UInt64() => TestGetValue(DbType.UInt64, ValueKind.Minimum, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_minimum_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_minimum_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_minimum_Decimal() => TestGetValue(DbType.Decimal, ValueKind.Minimum, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_minimum_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.Minimum, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_minimum_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.Minimum, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_Byte() => TestGetValue(DbType.Byte, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_Byte_with_GetFieldValue() => TestGetValue(DbType.Byte, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_Byte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Byte, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_Int16() => TestGetValue(DbType.Int16, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_Int32() => TestGetValue(DbType.Int32, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_Int64() => TestGetValue(DbType.Int64, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_SByte() => TestGetValue(DbType.SByte, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_UInt16() => TestGetValue(DbType.UInt16, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_UInt32() => TestGetValue(DbType.UInt32, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_UInt64() => TestGetValue(DbType.UInt64, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_one_Decimal() => TestGetValue(DbType.Decimal, ValueKind.One, x => x.GetBoolean(0), true);
public override void GetBoolean_throws_for_one_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.One, x => x.GetFieldValue<bool>(0), true);
public override Task GetBoolean_throws_for_one_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.One, x => x.GetFieldValueAsync<bool>(0), true);
public override void GetBoolean_throws_for_zero_Byte() => TestGetValue(DbType.Byte, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_Byte_with_GetFieldValue() => TestGetValue(DbType.Byte, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_Byte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Byte, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_Int16() => TestGetValue(DbType.Int16, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_Int32() => TestGetValue(DbType.Int32, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_Int64() => TestGetValue(DbType.Int64, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_SByte() => TestGetValue(DbType.SByte, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_UInt16() => TestGetValue(DbType.UInt16, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_UInt32() => TestGetValue(DbType.UInt32, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_UInt64() => TestGetValue(DbType.UInt64, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
public override void GetBoolean_throws_for_zero_Decimal() => TestGetValue(DbType.Decimal, ValueKind.Zero, x => x.GetBoolean(0), false);
public override void GetBoolean_throws_for_zero_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.Zero, x => x.GetFieldValue<bool>(0), false);
public override Task GetBoolean_throws_for_zero_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.Zero, x => x.GetFieldValueAsync<bool>(0), false);
// BOOL columns can be coerced to integers: https://github.com/mysql-net/MySqlConnector/issues/782
public override void GetByte_throws_for_minimum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_minimum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_minimum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_one_Boolean() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_maximum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_maximum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_maximum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetInt16_throws_for_minimum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetInt16(0), (short) 0);
public override void GetInt16_throws_for_minimum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValue<short>(0), (short) 0);
public override Task GetInt16_throws_for_minimum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValueAsync<short>(0), (short) 0);
public override void GetInt16_throws_for_zero_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetInt16(0), (short) 0);
public override void GetInt16_throws_for_zero_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValue<short>(0), (short) 0);
public override Task GetInt16_throws_for_zero_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValueAsync<short>(0), (short) 0);
public override void GetInt16_throws_for_one_Boolean() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetInt16(0), (short) 1);
public override void GetInt16_throws_for_one_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetFieldValue<short>(0), (short) 1);
public override Task GetInt16_throws_for_one_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.One, x => x.GetFieldValueAsync<short>(0), (short) 1);
public override void GetInt16_throws_for_maximum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetInt16(0), (short) 1);
public override void GetInt16_throws_for_maximum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValue<short>(0), (short) 1);
public override Task GetInt16_throws_for_maximum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValueAsync<short>(0), (short) 1);
public override void GetInt32_throws_for_minimum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetInt32(0), 0);
public override void GetInt32_throws_for_minimum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValue<int>(0), 0);
public override Task GetInt32_throws_for_minimum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValueAsync<int>(0), 0);
public override void GetInt32_throws_for_zero_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetInt32(0), 0);
public override void GetInt32_throws_for_zero_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValue<int>(0), 0);
public override Task GetInt32_throws_for_zero_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValueAsync<int>(0), 0);
public override void GetInt32_throws_for_one_Boolean() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetInt32(0), 1);
public override void GetInt32_throws_for_one_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetFieldValue<int>(0), 1);
public override Task GetInt32_throws_for_one_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.One, x => x.GetFieldValueAsync<int>(0), 1);
public override void GetInt32_throws_for_maximum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetInt32(0), 1);
public override void GetInt32_throws_for_maximum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValue<int>(0), 1);
public override Task GetInt32_throws_for_maximum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValueAsync<int>(0), 1);
public override void GetInt64_throws_for_minimum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetInt64(0), 0L);
public override void GetInt64_throws_for_minimum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValue<long>(0), 0L);
public override Task GetInt64_throws_for_minimum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Minimum, x => x.GetFieldValueAsync<long>(0), 0L);
public override void GetInt64_throws_for_zero_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetInt64(0), 0L);
public override void GetInt64_throws_for_zero_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValue<long>(0), 0L);
public override Task GetInt64_throws_for_zero_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Zero, x => x.GetFieldValueAsync<long>(0), 0L);
public override void GetInt64_throws_for_one_Boolean() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetInt64(0), 1L);
public override void GetInt64_throws_for_one_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.One, x => x.GetFieldValue<long>(0), 1L);
public override Task GetInt64_throws_for_one_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.One, x => x.GetFieldValueAsync<long>(0), 1L);
public override void GetInt64_throws_for_maximum_Boolean() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetInt64(0), 1L);
public override void GetInt64_throws_for_maximum_Boolean_with_GetFieldValue() => TestGetValue(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValue<long>(0), 1L);
public override Task GetInt64_throws_for_maximum_Boolean_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Boolean, ValueKind.Maximum, x => x.GetFieldValueAsync<long>(0), 1L);
// GetByte allows integral conversions
public override void GetByte_throws_for_maximum_Int16() => TestException(DbType.Int16, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Int16_with_GetFieldValue() => TestException(DbType.Int16, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_Int16_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int16, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Int32() => TestException(DbType.Int32, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Int32_with_GetFieldValue() => TestException(DbType.Int32, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_Int32_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int32, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Int64() => TestException(DbType.Int64, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Int64_with_GetFieldValue() => TestException(DbType.Int64, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_Int64_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int64, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_SByte() => TestGetValue(DbType.SByte, ValueKind.Maximum, x => x.GetByte(0), (byte) 127);
public override void GetByte_throws_for_maximum_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), (byte) 127);
public override Task GetByte_throws_for_maximum_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), (byte) 127);
public override void GetByte_throws_for_maximum_UInt16() => TestException(DbType.UInt16, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_UInt16_with_GetFieldValue() => TestException(DbType.UInt16, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_UInt16_with_GetFieldValueAsync() => TestExceptionAsync(DbType.UInt16, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_UInt32() => TestException(DbType.UInt32, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_UInt32_with_GetFieldValue() => TestException(DbType.UInt32, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_UInt32_with_GetFieldValueAsync() => TestExceptionAsync(DbType.UInt32, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_UInt64() => TestException(DbType.UInt64, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_UInt64_with_GetFieldValue() => TestException(DbType.UInt64, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_UInt64_with_GetFieldValueAsync() => TestExceptionAsync(DbType.UInt64, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Decimal() => TestException(DbType.Decimal, ValueKind.Maximum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_maximum_Decimal_with_GetFieldValue() => TestException(DbType.Decimal, ValueKind.Maximum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_maximum_Decimal_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Decimal, ValueKind.Maximum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int16() => TestException(DbType.Int16, ValueKind.Minimum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int16_with_GetFieldValue() => TestException(DbType.Int16, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_minimum_Int16_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int16, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int32() => TestException(DbType.Int32, ValueKind.Minimum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int32_with_GetFieldValue() => TestException(DbType.Int32, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_minimum_Int32_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int32, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int64() => TestException(DbType.Int64, ValueKind.Minimum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_Int64_with_GetFieldValue() => TestException(DbType.Int64, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_minimum_Int64_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Int64, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_SByte() => TestException(DbType.SByte, ValueKind.Minimum, x => x.GetByte(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_SByte_with_GetFieldValue() => TestException(DbType.SByte, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), typeof(OverflowException));
public override Task GetByte_throws_for_minimum_SByte_with_GetFieldValueAsync() => TestExceptionAsync(DbType.SByte, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), typeof(OverflowException));
public override void GetByte_throws_for_minimum_UInt16() => TestGetValue(DbType.UInt16, ValueKind.Minimum, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_minimum_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_minimum_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_minimum_UInt32() => TestGetValue(DbType.UInt32, ValueKind.Minimum, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_minimum_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_minimum_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_minimum_UInt64() => TestGetValue(DbType.UInt64, ValueKind.Minimum, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_minimum_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_minimum_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_minimum_Decimal() => TestGetValue(DbType.Decimal, ValueKind.Minimum, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_minimum_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.Minimum, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_minimum_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.Minimum, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_one_Int16() => TestGetValue(DbType.Int16, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_Int32() => TestGetValue(DbType.Int32, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_Int64() => TestGetValue(DbType.Int64, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_SByte() => TestGetValue(DbType.SByte, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_UInt16() => TestGetValue(DbType.UInt16, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_UInt32() => TestGetValue(DbType.UInt32, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_UInt64() => TestGetValue(DbType.UInt64, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_one_Decimal() => TestGetValue(DbType.Decimal, ValueKind.One, x => x.GetByte(0), (byte) 1);
public override void GetByte_throws_for_one_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.One, x => x.GetFieldValue<byte>(0), (byte) 1);
public override Task GetByte_throws_for_one_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.One, x => x.GetFieldValueAsync<byte>(0), (byte) 1);
public override void GetByte_throws_for_zero_Int16() => TestGetValue(DbType.Int16, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_Int16_with_GetFieldValue() => TestGetValue(DbType.Int16, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_Int16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int16, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_Int32() => TestGetValue(DbType.Int32, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_Int32_with_GetFieldValue() => TestGetValue(DbType.Int32, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_Int32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int32, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_Int64() => TestGetValue(DbType.Int64, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_Int64_with_GetFieldValue() => TestGetValue(DbType.Int64, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_Int64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Int64, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_SByte() => TestGetValue(DbType.SByte, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_SByte_with_GetFieldValue() => TestGetValue(DbType.SByte, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_SByte_with_GetFieldValueAsync() => TestGetValueAsync(DbType.SByte, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt16() => TestGetValue(DbType.UInt16, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt16_with_GetFieldValue() => TestGetValue(DbType.UInt16, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_UInt16_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt16, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt32() => TestGetValue(DbType.UInt32, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt32_with_GetFieldValue() => TestGetValue(DbType.UInt32, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_UInt32_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt32, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt64() => TestGetValue(DbType.UInt64, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_UInt64_with_GetFieldValue() => TestGetValue(DbType.UInt64, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_UInt64_with_GetFieldValueAsync() => TestGetValueAsync(DbType.UInt64, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
public override void GetByte_throws_for_zero_Decimal() => TestGetValue(DbType.Decimal, ValueKind.Zero, x => x.GetByte(0), (byte) 0);
public override void GetByte_throws_for_zero_Decimal_with_GetFieldValue() => TestGetValue(DbType.Decimal, ValueKind.Zero, x => x.GetFieldValue<byte>(0), (byte) 0);
public override Task GetByte_throws_for_zero_Decimal_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Decimal, ValueKind.Zero, x => x.GetFieldValueAsync<byte>(0), (byte) 0);
// the minimum date permitted by MySQL is 1000-01-01; override the minimum value for DateTime tests
public override void GetDateTime_for_minimum_Date() => TestGetValue(DbType.Date, ValueKind.Minimum, x => x.GetDateTime(0), new DateTime(1000, 1, 1));
public override void GetDateTime_for_minimum_Date_with_GetFieldValue() => TestGetValue(DbType.Date, ValueKind.Minimum, x => x.GetFieldValue<DateTime>(0), new DateTime(1000, 1, 1));
public override Task GetDateTime_for_minimum_Date_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Date, ValueKind.Minimum, x => x.GetFieldValueAsync<DateTime>(0), new DateTime(1000, 1, 1));
public override void GetDateTime_for_minimum_DateTime() => TestGetValue(DbType.Date, ValueKind.Minimum, x => x.GetDateTime(0), new DateTime(1000, 1, 1));
public override void GetDateTime_for_minimum_DateTime_with_GetFieldValue() => TestGetValue(DbType.Date, ValueKind.Minimum, x => x.GetFieldValue<DateTime>(0), new DateTime(1000, 1, 1));
public override Task GetDateTime_for_minimum_DateTime_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Date, ValueKind.Minimum, x => x.GetFieldValueAsync<DateTime>(0), new DateTime(1000, 1, 1));
// GetDecimal() allows conversions from float/double
public override void GetDecimal_throws_for_zero_Single() => TestGetValue(DbType.Single, ValueKind.Zero, x => x.GetDecimal(0), 0m);
public override void GetDecimal_throws_for_zero_Single_with_GetFieldValue() => TestGetValue(DbType.Single, ValueKind.Zero, x => x.GetFieldValue<decimal>(0), 0m);
public override Task GetDecimal_throws_for_zero_Single_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Single, ValueKind.Zero, x => x.GetFieldValueAsync<decimal>(0), 0m);
public override void GetDecimal_throws_for_one_Single() => TestGetValue(DbType.Single, ValueKind.One, x => x.GetDecimal(0), 1m);
public override void GetDecimal_throws_for_one_Single_with_GetFieldValue() => TestGetValue(DbType.Single, ValueKind.One, x => x.GetFieldValue<decimal>(0), 1m);
public override Task GetDecimal_throws_for_one_Single_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Single, ValueKind.One, x => x.GetFieldValueAsync<decimal>(0), 1m);
public override void GetDecimal_throws_for_minimum_Single() => TestGetValue(DbType.Single, ValueKind.Minimum, x => x.GetDecimal(0), 0m);
public override void GetDecimal_throws_for_minimum_Single_with_GetFieldValue() => TestGetValue(DbType.Single, ValueKind.Minimum, x => x.GetFieldValue<decimal>(0), 0m);
public override Task GetDecimal_throws_for_minimum_Single_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Single, ValueKind.Minimum, x => x.GetFieldValueAsync<decimal>(0), 0m);
public override void GetDecimal_throws_for_maximum_Single() => TestException(DbType.Single, ValueKind.Maximum, x => x.GetDecimal(0), typeof(OverflowException));
public override void GetDecimal_throws_for_maximum_Single_with_GetFieldValue() => TestException(DbType.Single, ValueKind.Maximum, x => x.GetFieldValue<decimal>(0), typeof(OverflowException));
public override Task GetDecimal_throws_for_maximum_Single_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Single, ValueKind.Maximum, x => x.GetFieldValueAsync<decimal>(0), typeof(OverflowException));
public override void GetDecimal_throws_for_zero_Double() => TestGetValue(DbType.Double, ValueKind.Zero, x => x.GetDecimal(0), 0m);
public override void GetDecimal_throws_for_zero_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.Zero, x => x.GetFieldValue<decimal>(0), 0m);
public override Task GetDecimal_throws_for_zero_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.Zero, x => x.GetFieldValueAsync<decimal>(0), 0m);
public override void GetDecimal_throws_for_one_Double() => TestGetValue(DbType.Double, ValueKind.One, x => x.GetDecimal(0), 1m);
public override void GetDecimal_throws_for_one_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.One, x => x.GetFieldValue<decimal>(0), 1m);
public override Task GetDecimal_throws_for_one_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.One, x => x.GetFieldValueAsync<decimal>(0), 1m);
public override void GetDecimal_throws_for_minimum_Double() => TestGetValue(DbType.Double, ValueKind.Minimum, x => x.GetDecimal(0), 0m);
public override void GetDecimal_throws_for_minimum_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.Minimum, x => x.GetFieldValue<decimal>(0), 0m);
public override Task GetDecimal_throws_for_minimum_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.Minimum, x => x.GetFieldValueAsync<decimal>(0), 0m);
public override void GetDecimal_throws_for_maximum_Double() => TestException(DbType.Double, ValueKind.Maximum, x => x.GetDecimal(0), typeof(OverflowException));
public override void GetDecimal_throws_for_maximum_Double_with_GetFieldValue() => TestException(DbType.Double, ValueKind.Maximum, x => x.GetFieldValue<decimal>(0), typeof(OverflowException));
public override Task GetDecimal_throws_for_maximum_Double_with_GetFieldValueAsync() => TestExceptionAsync(DbType.Double, ValueKind.Maximum, x => x.GetFieldValueAsync<decimal>(0), typeof(OverflowException));
// The GetFloat() implementation allows for conversions from double to float.
// The minimum tests for float and double do not test for the smallest possible value (as the tests for integer values do),
// but test for the largest value smaller than 0 (Epsilon).
// If double.Epsilon is converted to float, it will result in 0.
public override void GetFloat_throws_for_minimum_Double() => TestGetValue(DbType.Double, ValueKind.Minimum, x => x.GetFloat(0), 0);
public override void GetFloat_throws_for_minimum_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.Minimum, x => x.GetFieldValue<float>(0), 0);
public override Task GetFloat_throws_for_minimum_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.Minimum, x => x.GetFieldValueAsync<float>(0), 0);
public override void GetFloat_throws_for_one_Double() => TestGetValue(DbType.Double, ValueKind.One, x => x.GetFloat(0), 1);
public override void GetFloat_throws_for_one_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.One, x => x.GetFieldValue<float>(0), 1);
public override Task GetFloat_throws_for_one_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.One, x => x.GetFieldValueAsync<float>(0), 1);
public override void GetFloat_throws_for_zero_Double() => TestGetValue(DbType.Double, ValueKind.Zero, x => x.GetFloat(0), 0);
public override void GetFloat_throws_for_zero_Double_with_GetFieldValue() => TestGetValue(DbType.Double, ValueKind.Zero, x => x.GetFieldValue<float>(0), 0);
public override Task GetFloat_throws_for_zero_Double_with_GetFieldValueAsync() => TestGetValueAsync(DbType.Double, ValueKind.Zero, x => x.GetFieldValueAsync<float>(0), 0);
}
| GetValueConversionTests |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ViewFeatures/test/ViewComponents/ViewComponentConventionsTest.cs | {
"start": 4900,
"end": 4962
} | internal class ____ : ViewComponent
{
}
| InternalClass |
csharp | aspnetboilerplate__aspnetboilerplate | test/Abp.TestBase.Tests/Application/Services/ServiceWithDifferentInputs_Tests.cs | {
"start": 1380,
"end": 1465
} | public class ____
{
}
#endregion
}
}
| MyEmptyDto |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Media/Fields/Anchor.cs | {
"start": 236,
"end": 342
} | public class ____
{
public float X { get; set; } = 0.5f;
public float Y { get; set; } = 0.5f;
}
| Anchor |
csharp | npgsql__efcore.pg | test/EFCore.PG.FunctionalTests/QueryExpressionInterceptionNpgsqlTestBase.cs | {
"start": 1427,
"end": 1726
} | public class ____ : InterceptionNpgsqlFixtureBase
{
protected override string StoreName
=> "QueryExpressionInterception";
protected override bool ShouldSubscribeToDiagnosticListener
=> false;
}
}
| InterceptionNpgsqlFixture |
csharp | dotnet__aspnetcore | src/SignalR/server/Core/src/HubConnectionHandler.cs | {
"start": 2402,
"end": 15502
} | class ____ typically created via dependency injection.</remarks>
public HubConnectionHandler(HubLifetimeManager<THub> lifetimeManager,
IHubProtocolResolver protocolResolver,
IOptions<HubOptions> globalHubOptions,
IOptions<HubOptions<THub>> hubOptions,
ILoggerFactory loggerFactory,
IUserIdProvider userIdProvider,
IServiceScopeFactory serviceScopeFactory
)
{
_protocolResolver = protocolResolver;
_lifetimeManager = lifetimeManager;
_loggerFactory = loggerFactory;
_hubOptions = hubOptions.Value;
_globalHubOptions = globalHubOptions.Value;
_logger = loggerFactory.CreateLogger<HubConnectionHandler<THub>>();
_userIdProvider = userIdProvider;
_enableDetailedErrors = false;
bool disableImplicitFromServiceParameters;
List<IHubFilter>? hubFilters = null;
if (_hubOptions.UserHasSetValues)
{
_maximumMessageSize = _hubOptions.MaximumReceiveMessageSize;
_enableDetailedErrors = _hubOptions.EnableDetailedErrors ?? _enableDetailedErrors;
_maxParallelInvokes = _hubOptions.MaximumParallelInvocationsPerClient;
disableImplicitFromServiceParameters = _hubOptions.DisableImplicitFromServicesParameters;
_statefulReconnectBufferSize = _hubOptions.StatefulReconnectBufferSize;
if (_hubOptions.HubFilters != null)
{
hubFilters = new List<IHubFilter>(_hubOptions.HubFilters);
}
}
else
{
_maximumMessageSize = _globalHubOptions.MaximumReceiveMessageSize;
_enableDetailedErrors = _globalHubOptions.EnableDetailedErrors ?? _enableDetailedErrors;
_maxParallelInvokes = _globalHubOptions.MaximumParallelInvocationsPerClient;
disableImplicitFromServiceParameters = _globalHubOptions.DisableImplicitFromServicesParameters;
_statefulReconnectBufferSize = _globalHubOptions.StatefulReconnectBufferSize;
if (_globalHubOptions.HubFilters != null)
{
hubFilters = new List<IHubFilter>(_globalHubOptions.HubFilters);
}
}
_dispatcher = new DefaultHubDispatcher<THub>(
serviceScopeFactory,
new HubContext<THub>(lifetimeManager),
_enableDetailedErrors,
disableImplicitFromServiceParameters,
new Logger<DefaultHubDispatcher<THub>>(loggerFactory),
hubFilters,
lifetimeManager);
}
/// <inheritdoc />
public override async Task OnConnectedAsync(ConnectionContext connection)
{
// We check to see if HubOptions<THub> are set because those take precedence over global hub options.
// Then set the keepAlive and handshakeTimeout values to the defaults in HubOptionsSetup when they were explicitly set to null.
var supportedProtocols = _hubOptions.SupportedProtocols ?? _globalHubOptions.SupportedProtocols;
if (supportedProtocols == null || supportedProtocols.Count == 0)
{
throw new InvalidOperationException("There are no supported protocols");
}
var handshakeTimeout = _hubOptions.HandshakeTimeout ?? _globalHubOptions.HandshakeTimeout ?? HubOptionsSetup.DefaultHandshakeTimeout;
var contextOptions = new HubConnectionContextOptions()
{
KeepAliveInterval = _hubOptions.KeepAliveInterval ?? _globalHubOptions.KeepAliveInterval ?? HubOptionsSetup.DefaultKeepAliveInterval,
ClientTimeoutInterval = _hubOptions.ClientTimeoutInterval ?? _globalHubOptions.ClientTimeoutInterval ?? HubOptionsSetup.DefaultClientTimeoutInterval,
StreamBufferCapacity = _hubOptions.StreamBufferCapacity ?? _globalHubOptions.StreamBufferCapacity ?? HubOptionsSetup.DefaultStreamBufferCapacity,
MaximumReceiveMessageSize = _maximumMessageSize,
TimeProvider = TimeProvider,
MaximumParallelInvocations = _maxParallelInvokes,
StatefulReconnectBufferSize = _statefulReconnectBufferSize,
};
Log.ConnectedStarting(_logger);
var connectionContext = new HubConnectionContext(connection, contextOptions, _loggerFactory)
{
OriginalActivity = Activity.Current,
};
var resolvedSupportedProtocols = (supportedProtocols as IReadOnlyList<string>) ?? supportedProtocols.ToList();
if (!await connectionContext.HandshakeAsync(handshakeTimeout, resolvedSupportedProtocols, _protocolResolver, _userIdProvider, _enableDetailedErrors))
{
return;
}
// -- the connectionContext has been set up --
try
{
await _lifetimeManager.OnConnectedAsync(connectionContext);
await RunHubAsync(connectionContext);
}
finally
{
connectionContext.Cleanup();
Log.ConnectedEnding(_logger);
await _lifetimeManager.OnDisconnectedAsync(connectionContext);
}
}
private async Task RunHubAsync(HubConnectionContext connection)
{
try
{
await _dispatcher.OnConnectedAsync(connection);
}
catch (Exception ex)
{
Log.ErrorDispatchingHubEvent(_logger, "OnConnectedAsync", ex);
// The client shouldn't try to reconnect given an error in OnConnected.
await SendCloseAsync(connection, ex, allowReconnect: false);
// return instead of throw to let close message send successfully
return;
}
try
{
await DispatchMessagesAsync(connection);
}
catch (OperationCanceledException)
{
// Don't treat OperationCanceledException as an error, it's basically a "control flow"
// exception to stop things from running
}
catch (Exception ex)
{
Log.ErrorProcessingRequest(_logger, ex);
await HubOnDisconnectedAsync(connection, ex);
// return instead of throw to let close message send successfully
return;
}
await HubOnDisconnectedAsync(connection, connection.CloseException);
}
private async Task HubOnDisconnectedAsync(HubConnectionContext connection, Exception? exception)
{
var disconnectException = exception;
if (connection.CloseMessage is not null)
{
// If client sent a CloseMessage we don't care about any internal exceptions that may have occurred.
// The CloseMessage indicates a graceful closure on the part of the client.
disconnectException = null;
exception = null;
if (connection.CloseMessage.Error is not null)
{
// A bit odd for the client to send an error along with a graceful close, but just in case we should surface it in OnDisconnectedAsync
disconnectException = new HubException(connection.CloseMessage.Error);
}
}
// send close message before aborting the connection
await SendCloseAsync(connection, exception, connection.AllowReconnect);
// We wait on abort to complete, this is so that we can guarantee that all callbacks have fired
// before OnDisconnectedAsync
// Ensure the connection is aborted before firing disconnect
await connection.AbortAsync();
// If a client result is requested in OnDisconnectedAsync we want to avoid the SemaphoreFullException and get the better connection disconnected IOException
_ = connection.ActiveInvocationLimit.TryAcquire();
try
{
await _dispatcher.OnDisconnectedAsync(connection, disconnectException);
}
catch (Exception ex)
{
Log.ErrorDispatchingHubEvent(_logger, "OnDisconnectedAsync", ex);
throw;
}
}
private async Task SendCloseAsync(HubConnectionContext connection, Exception? exception, bool allowReconnect)
{
var closeMessage = CloseMessage.Empty;
if (exception != null)
{
var errorMessage = ErrorMessageHelper.BuildErrorMessage("Connection closed with an error.", exception, _enableDetailedErrors);
closeMessage = new CloseMessage(errorMessage, allowReconnect);
}
else if (allowReconnect)
{
closeMessage = new CloseMessage(error: null, allowReconnect);
}
try
{
await connection.WriteAsync(closeMessage, ignoreAbort: true);
}
catch (Exception ex)
{
Log.ErrorSendingClose(_logger, ex);
}
}
private async Task DispatchMessagesAsync(HubConnectionContext connection)
{
var input = connection.Input;
var protocol = connection.Protocol;
connection.BeginClientTimeout();
var binder = new HubConnectionBinder<THub>(_dispatcher, _lifetimeManager, connection);
while (true)
{
var result = await input.ReadAsync();
var buffer = result.Buffer;
try
{
if (result.IsCanceled)
{
break;
}
if (!buffer.IsEmpty)
{
bool messageReceived = false;
// No message limit, just parse and dispatch
if (_maximumMessageSize == null)
{
while (protocol.TryParseMessage(ref buffer, binder, out var message))
{
connection.StopClientTimeout();
// This lets us know the timeout has stopped and we need to re-enable it after dispatching the message
messageReceived = true;
await _dispatcher.DispatchMessageAsync(connection, message);
}
if (messageReceived)
{
connection.BeginClientTimeout();
}
}
else
{
// We give the parser a sliding window of the default message size
var maxMessageSize = _maximumMessageSize.Value;
while (!buffer.IsEmpty)
{
var segment = buffer;
var overLength = false;
if (segment.Length > maxMessageSize)
{
segment = segment.Slice(segment.Start, maxMessageSize);
overLength = true;
}
if (protocol.TryParseMessage(ref segment, binder, out var message))
{
connection.StopClientTimeout();
// This lets us know the timeout has stopped and we need to re-enable it after dispatching the message
messageReceived = true;
await _dispatcher.DispatchMessageAsync(connection, message);
}
else if (overLength)
{
throw new InvalidDataException($"The maximum message size of {maxMessageSize}B was exceeded. The message size can be configured in AddHubOptions.");
}
else
{
// No need to update the buffer since we didn't parse anything
break;
}
// Update the buffer to the remaining segment
buffer = buffer.Slice(segment.Start);
}
if (messageReceived)
{
connection.BeginClientTimeout();
}
}
}
if (result.IsCompleted)
{
if (!buffer.IsEmpty)
{
throw new InvalidDataException("Connection terminated while reading a message.");
}
break;
}
}
finally
{
// The buffer was sliced up to where it was consumed, so we can just advance to the start.
// We mark examined as buffer.End so that if we didn't receive a full frame, we'll wait for more data
// before yielding the read again.
input.AdvanceTo(buffer.Start, buffer.End);
}
}
}
}
| is |
csharp | dotnet__efcore | src/EFCore/Diagnostics/KeyEventData.cs | {
"start": 261,
"end": 477
} | class ____ events that have a key.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-diagnostics">Logging, events, and diagnostics</see> for more information and examples.
/// </remarks>
| for |
csharp | unoplatform__uno | src/Uno.UI.Toolkit/DevTools/Input/IInjectedPointer.cs | {
"start": 271,
"end": 501
} | internal interface ____
{
void Press(Point position);
void MoveTo(Point position, uint? steps = null, uint? stepOffsetInMilliseconds = null);
void MoveBy(double deltaX = 0, double deltaY = 0);
void Release();
}
| IInjectedPointer |
csharp | nuke-build__nuke | source/Nuke.Tooling/Options.When.cs | {
"start": 202,
"end": 695
} | partial class ____
{
public static T When<T>(this T options, Func<T, bool> condition, Configure<T> configurator)
where T : Options, new()
{
return condition.Invoke(options) ? options.Apply(configurator) : options;
}
public static T[] When<T>(this T[] options, Func<T, bool> condition, Configure<T> configurator)
where T : Options, new()
{
return options.Select(x => condition(x) ? x.Apply(configurator) : x).ToArray();
}
}
| OptionsExtensions |
csharp | dotnetcore__CAP | test/DotNetCore.CAP.Test/ConsumerServiceSelectorTest.cs | {
"start": 7533,
"end": 8121
} | public class ____ : IBarTest
{
[CandidatesTopic("Candidates.Bar")]
public Task GetBar()
{
Console.WriteLine("GetBar() method has bee excuted.");
return Task.CompletedTask;
}
[CandidatesTopic("Candidates.Bar2")]
public void GetBar2()
{
Console.WriteLine("GetBar2() method has bee excuted.");
}
public void GetBar3()
{
Console.WriteLine("GetBar3() method has bee excuted.");
}
}
/// <summary>
/// Test to verify if an inherited | CandidatesBarTest |
csharp | protobuf-net__protobuf-net | src/Examples/Issues/SO11657482.cs | {
"start": 275,
"end": 435
} | public class ____ : Base
{
[ProtoMember(1)]
public int SomeProperty { get; set; }
}
[ProtoContract]
| Derived |
csharp | RicoSuter__NJsonSchema | src/NJsonSchema.Annotations/JsonSchemaProcessorAttribute.cs | {
"start": 627,
"end": 1366
} | public class ____ : Attribute
{
/// <summary>Initializes a new instance of the <see cref="JsonSchemaProcessorAttribute"/> class.</summary>
/// <param name="type">The schema processor type (must implement ISchemaProcessor).</param>
/// <param name="parameters">The parameters.</param>
public JsonSchemaProcessorAttribute(Type type, params object[] parameters)
{
Type = type;
Parameters = parameters;
}
/// <summary>Gets or sets the type of the operation processor (must implement ISchemaProcessor).</summary>
public Type Type { get; set; }
/// <summary>Gets or sets the type of the constructor parameters.</summary>
public object[] Parameters { get; set; }
} | JsonSchemaProcessorAttribute |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Razor.RuntimeCompilation/src/MvcRazorRuntimeCompilationOptions.cs | {
"start": 796,
"end": 1730
} | public class ____
{
/// <summary>
/// Gets the <see cref="IFileProvider" /> instances used to locate Razor files.
/// </summary>
/// <remarks>
/// At startup, this collection is initialized to include an instance of
/// <see cref="IHostingEnvironment.ContentRootFileProvider"/> that is rooted at the application root.
/// </remarks>
public IList<IFileProvider> FileProviders { get; } = new List<IFileProvider>();
/// <summary>
/// Gets paths to additional references used during runtime compilation of Razor files.
/// </summary>
/// <remarks>
/// By default, the runtime compiler <see cref="ICompilationReferencesProvider"/> to gather references
/// uses to compile a Razor file. This API allows providing additional references to the compiler.
/// </remarks>
public IList<string> AdditionalReferencePaths { get; } = new List<string>();
}
| MvcRazorRuntimeCompilationOptions |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs | {
"start": 1344,
"end": 2253
} | public class ____ : Expression
{
public AstType Type {
get { return GetChildByRole(Roles.Type); }
set { SetChildByRole(Roles.Type, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitTypeReferenceExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitTypeReferenceExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitTypeReferenceExpression(this, data);
}
public TypeReferenceExpression()
{
}
public TypeReferenceExpression(AstType type)
{
AddChild(type, Roles.Type);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
TypeReferenceExpression o = other as TypeReferenceExpression;
return o != null && this.Type.DoMatch(o.Type, match);
}
}
}
| TypeReferenceExpression |
csharp | cake-build__cake | src/Cake.Frosting/IFrostingLifetime.cs | {
"start": 815,
"end": 1390
} | public interface ____
{
/// <summary>
/// This method is executed after all tasks have been run.
/// If a setup action or a task fails with or without recovery, the specified teardown action will still be executed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="info">The teardown information.</param>
void Teardown(ICakeContext context, ITeardownContext info);
}
/// <summary>
/// Represents the Setup/Teardown logic for a Cake run.
/// </summary>
| IFrostingTeardown |
csharp | dotnet__maui | src/Compatibility/Core/src/Android/CollectionView/DataChangeObserver.cs | {
"start": 208,
"end": 1973
} | internal class ____ : RecyclerView.AdapterDataObserver
{
IntPtr _adapter;
readonly Action _onDataChange;
public bool Observing { get; private set; }
public DataChangeObserver(Action onDataChange) : base()
{
_onDataChange = onDataChange;
}
public void Start(Adapter adapter)
{
if (Observing)
{
return;
}
adapter.RegisterAdapterDataObserver(this);
_adapter = adapter.Handle;
Observing = true;
}
public void Stop(Adapter adapter)
{
if (Observing && IsValidAdapter(adapter))
{
adapter.UnregisterAdapterDataObserver(this);
}
_adapter = IntPtr.Zero;
Observing = false;
}
public override void OnChanged()
{
base.OnChanged();
_onDataChange?.Invoke();
}
public override void OnItemRangeInserted(int positionStart, int itemCount)
{
base.OnItemRangeInserted(positionStart, itemCount);
_onDataChange?.Invoke();
}
public override void OnItemRangeChanged(int positionStart, int itemCount)
{
base.OnItemRangeChanged(positionStart, itemCount);
_onDataChange?.Invoke();
}
public override void OnItemRangeChanged(int positionStart, int itemCount, Object payload)
{
base.OnItemRangeChanged(positionStart, itemCount, payload);
_onDataChange?.Invoke();
}
public override void OnItemRangeRemoved(int positionStart, int itemCount)
{
base.OnItemRangeRemoved(positionStart, itemCount);
_onDataChange?.Invoke();
}
public override void OnItemRangeMoved(int fromPosition, int toPosition, int itemCount)
{
base.OnItemRangeMoved(fromPosition, toPosition, itemCount);
_onDataChange?.Invoke();
}
bool IsValidAdapter(Adapter adapter)
{
return adapter != null && adapter.Handle == _adapter && adapter.HasObservers;
}
}
} | DataChangeObserver |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/DataContractTests.cs | {
"start": 4872,
"end": 5034
} | public class ____
{
[DataMember(Name = "NewName")]
public string Name { get; set; }
}
[DataContract]
| ClassTwo |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/ContainerTests/Batch_Specs.cs | {
"start": 386,
"end": 1440
} | public class ____
{
[Test]
public async Task Should_deliver_the_batch_to_the_consumer()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddConsumer<TestBatchConsumer>();
})
.BuildServiceProvider(true);
var harness = provider.GetTestHarness();
await harness.Start();
await harness.Bus.PublishBatch([new BatchItem(), new BatchItem()]);
await Assert.MultipleAsync(async () =>
{
Assert.That(await harness.Consumed.SelectAsync<BatchItem>().Take(2).Count(), Is.EqualTo(2));
Assert.That(await harness.GetConsumerHarness<TestBatchConsumer>().Consumed.Any<Batch<BatchItem>>());
Assert.That(await harness.Published.Any<BatchResult>(x => x.Context.Message is { Count: 2, Mode: BatchCompletionMode.Time }));
});
}
}
[TestFixture]
| When_batch_limit_is_reached |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWeb/ServiceModels.cs | {
"start": 17737,
"end": 19228
} | public partial class ____
{
public AllTypes()
{
StringList = new List<string>{};
StringArray = new string[]{};
StringMap = new Dictionary<string, string>{};
IntStringMap = new Dictionary<int, string>{};
}
public virtual int Id { get; set; }
public virtual int? NullableId { get; set; }
public virtual byte Byte { get; set; }
public virtual short Short { get; set; }
public virtual int Int { get; set; }
public virtual long Long { get; set; }
public virtual ushort UShort { get; set; }
public virtual uint UInt { get; set; }
public virtual ulong ULong { get; set; }
public virtual float Float { get; set; }
public virtual double Double { get; set; }
public virtual decimal Decimal { get; set; }
public virtual string String { get; set; }
public virtual DateTime DateTime { get; set; }
public virtual TimeSpan TimeSpan { get; set; }
public virtual DateTime? NullableDateTime { get; set; }
public virtual TimeSpan? NullableTimeSpan { get; set; }
public virtual List<string> StringList { get; set; }
public virtual string[] StringArray { get; set; }
public virtual Dictionary<string, string> StringMap { get; set; }
public virtual Dictionary<int, string> IntStringMap { get; set; }
public virtual SubType SubType { get; set; }
}
| AllTypes |
csharp | dotnet__BenchmarkDotNet | src/BenchmarkDotNet/Diagnosers/ThreadingDiagnoser.cs | {
"start": 412,
"end": 2330
} | public class ____ : IDiagnoser
{
public static readonly ThreadingDiagnoser Default = new ThreadingDiagnoser(new ThreadingDiagnoserConfig(displayCompletedWorkItemCountWhenZero: true, displayLockContentionWhenZero: true));
public ThreadingDiagnoser(ThreadingDiagnoserConfig config) => Config = config;
public ThreadingDiagnoserConfig Config { get; }
public IEnumerable<string> Ids => new[] { nameof(ThreadingDiagnoser) };
public IEnumerable<IExporter> Exporters => Array.Empty<IExporter>();
public IEnumerable<IAnalyser> Analysers => Array.Empty<IAnalyser>();
public void DisplayResults(ILogger logger) { }
public RunMode GetRunMode(BenchmarkCase benchmarkCase) => RunMode.NoOverhead;
public void Handle(HostSignal signal, DiagnoserActionParameters parameters) { }
public IEnumerable<Metric> ProcessResults(DiagnoserResults results)
{
yield return new Metric(new CompletedWorkItemCountMetricDescriptor(Config), results.ThreadingStats.CompletedWorkItemCount / (double)results.ThreadingStats.TotalOperations);
yield return new Metric(new LockContentionCountMetricDescriptor(Config), results.ThreadingStats.LockContentionCount / (double)results.ThreadingStats.TotalOperations);
}
public IEnumerable<ValidationError> Validate(ValidationParameters validationParameters)
{
foreach (var benchmark in validationParameters.Benchmarks)
{
var runtime = benchmark.Job.ResolveValue(EnvironmentMode.RuntimeCharacteristic, EnvironmentResolver.Instance);
if (runtime.RuntimeMoniker < RuntimeMoniker.NetCoreApp30)
{
yield return new ValidationError(true, $"{nameof(ThreadingDiagnoser)} supports only .NET Core 3.0+", benchmark);
}
}
}
| ThreadingDiagnoser |
csharp | microsoft__semantic-kernel | dotnet/src/Experimental/Process.IntegrationTestRunner.Dapr/ProcessTestFixture.cs | {
"start": 340,
"end": 5218
} | public sealed class ____ : IDisposable, IAsyncLifetime
{
private System.Diagnostics.Process? _process;
private HttpClient? _httpClient;
/// <summary>
/// Called by xUnit before the test is run.
/// </summary>
/// <returns></returns>
public async Task InitializeAsync()
{
this._httpClient = new HttpClient();
await this.StartTestHostAsync();
}
/// <summary>
/// Starts the test host by creating a new process with the Dapr cli. The startup process can take 30 seconds or more and so we wait for this to complete before returning.
/// </summary>
/// <returns></returns>
private async Task StartTestHostAsync()
{
try
{
string workingDirectory = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\..\Process.IntegrationTestHost.Dapr"));
var processStartInfo = new ProcessStartInfo
{
FileName = "dapr",
Arguments = "run --app-id daprprocesstests --app-port 5200 --dapr-http-port 3500 -- dotnet run --urls http://localhost:5200",
WorkingDirectory = workingDirectory,
RedirectStandardOutput = false,
RedirectStandardError = false,
UseShellExecute = true,
CreateNoWindow = false
};
this._process = new System.Diagnostics.Process
{
StartInfo = processStartInfo
};
this._process.Start();
await this.WaitForHostStartupAsync();
}
catch (Exception)
{
throw;
}
}
private async Task ShutdownTestHostAsync()
{
var processStartInfo = new ProcessStartInfo
{
FileName = "dapr",
Arguments = "stop --app-id daprprocesstests",
RedirectStandardOutput = false,
RedirectStandardError = false,
UseShellExecute = true,
CreateNoWindow = false
};
using var shutdownProcess = new System.Diagnostics.Process
{
StartInfo = processStartInfo
};
shutdownProcess.Start();
await shutdownProcess.WaitForExitAsync();
}
/// <summary>
/// Waits for the test host to be ready to accept requests. This is determined by making a request to the health endpoint.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidProgramException"></exception>
private async Task WaitForHostStartupAsync()
{
// Wait for the process to start
var now = DateTime.Now;
while (DateTime.Now - now < TimeSpan.FromSeconds(120))
{
if (this._process!.HasExited)
{
break;
}
try
{
var healthResponse = await this._httpClient!.GetAsync(new Uri("http://localhost:5200/daprHealth"));
if (healthResponse.StatusCode == HttpStatusCode.OK)
{
await Task.Delay(TimeSpan.FromSeconds(10));
return;
}
}
catch (HttpRequestException)
{
// Do nothing, just wait
}
}
throw new InvalidProgramException("Dapr Test Host did not start");
}
/// <summary>
/// Starts a process.
/// </summary>
/// <param name="process">The process to start.</param>
/// <param name="kernel">An instance of <see cref="Kernel"/></param>
/// <param name="initialEvent">An optional initial event.</param>
/// <param name="externalMessageChannel">channel used for external messages</param>
/// <returns>A <see cref="Task{KernelProcessContext}"/></returns>
public async Task<KernelProcessContext> StartProcessAsync(KernelProcess process, Kernel kernel, KernelProcessEvent initialEvent, IExternalKernelProcessMessageChannel? externalMessageChannel = null)
{
// Actual Kernel injection of Kernel and ExternalKernelProcessMessageChannel is in dotnet\src\Experimental\Process.IntegrationTestHost.Dapr\Program.cs
var context = new DaprTestProcessContext(process, this._httpClient!);
await context.StartWithEventAsync(initialEvent);
return context;
}
/// <summary>
/// Disposes of the test fixture.
/// </summary>
public void Dispose()
{
if (this._process is not null && this._process.HasExited)
{
this._process?.Kill();
this._process?.WaitForExit();
}
this._process?.Dispose();
this._httpClient?.Dispose();
}
/// <summary>
/// Called by xUnit after the test is run.
/// </summary>
/// <returns></returns>
public Task DisposeAsync()
{
return this.ShutdownTestHostAsync();
}
}
| ProcessTestFixture |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs | {
"start": 18000,
"end": 18216
} | public class ____
{
public string YourFieldName { get; set; } = null!;
[GraphQLDeprecated("This is deprecated")]
public string YourFieldname { get; set; } = null!;
}
| QueryFieldCasing |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/test/Data.Tests/TypeValidationTests.cs | {
"start": 2262,
"end": 2471
} | public class ____
{
[UsePaging]
[UseFiltering]
[UseProjection]
public IEnumerable<string> GetBars() => throw new NotImplementedException();
}
| InvalidMiddlewarePipeline2 |
csharp | bitwarden__server | util/SqliteMigrations/Migrations/20240425111436_EnableOrgsCollectionEnhancements.cs | {
"start": 139,
"end": 693
} | public partial class ____ : Migration
{
private const string _enableOrgsCollectionEnhancementsScript = "SqliteMigrations.HelperScripts.2024-04-25_00_EnableOrgsCollectionEnhancements.sql";
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(CoreHelpers.GetEmbeddedResourceContentsAsync(_enableOrgsCollectionEnhancementsScript));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
throw new Exception("Irreversible migration");
}
}
| EnableOrgsCollectionEnhancements |
csharp | duplicati__duplicati | Duplicati/Library/Main/Database/DatabaseSchemaMarker.cs | {
"start": 78,
"end": 152
} | class ____ locating the assembly with the database schema.
/// </summary>
| for |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ApiExplorer/test/DefaultApiDescriptionProviderTest.cs | {
"start": 97191,
"end": 97393
} | private class ____
{
[FromQuery(Name = "managerid")]
public string ManagerId { get; set; }
[FromQuery(Name = "name")]
public string Name { get; set; }
}
| Manager |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Common/View/IAreaViewFactory.cs | {
"start": 35,
"end": 178
} | public interface ____
{
string AreaName { get; }
IEnumerable<string> GetViewLocations(IEnumerable<string> viewLocations);
} | IAreaViewFactory |
csharp | dotnet__maui | src/Controls/src/Core/Handlers/Items2/iOS/CarouselViewController2.cs | {
"start": 317,
"end": 17471
} | public class ____ : ItemsViewController2<CarouselView>
{
bool _isUpdating = false;
int _section = 0;
CarouselViewLoopManager _carouselViewLoopManager;
// We need to keep track of the old views to update the visual states
// if this is null we are not attached to the window
List<View> _oldViews;
Items.ILoopItemsViewSource LoopItemsSource => ItemsSource as Items.ILoopItemsViewSource;
public CarouselViewController2(CarouselView itemsView, UICollectionViewLayout layout) : base(itemsView, layout)
{
CollectionView.AllowsSelection = false;
CollectionView.AllowsMultipleSelection = false;
}
private protected override NSIndexPath GetAdjustedIndexPathForItemSource(NSIndexPath indexPath)
{
return NSIndexPath.FromItemSection(GetIndexFromIndexPath(indexPath), _section);
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
UICollectionViewCell cell;
cell = base.GetCell(collectionView, indexPath);
var element = (cell as TemplatedCell2)?.PlatformHandler?.VirtualView as VisualElement;
if (element is not null)
{
VisualStateManager.GoToState(element, CarouselView.DefaultItemVisualState);
}
return cell;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section) => LoopItemsSource.Loop ? LoopItemsSource.LoopCount : LoopItemsSource.ItemCount;
void InitializeCarouselViewLoopManager()
{
if (_carouselViewLoopManager is null)
{
_carouselViewLoopManager = new CarouselViewLoopManager();
_carouselViewLoopManager.SetItemsSource(LoopItemsSource);
}
}
public override void ViewDidLoad()
{
InitializeCarouselViewLoopManager();
base.ViewDidLoad();
}
public override void ViewWillLayoutSubviews()
{
base.ViewWillLayoutSubviews();
UpdateVisualStates();
}
public override async void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
await UpdateInitialPosition();
}
public override void DraggingStarted(UIScrollView scrollView)
{
// _isDragging = true;
ItemsView?.SetIsDragging(true);
}
public override void DraggingEnded(UIScrollView scrollView, bool willDecelerate)
{
ItemsView?.SetIsDragging(false);
//_isDragging = false;
}
public override void UpdateItemsSource()
{
UnsubscribeCollectionItemsSourceChanged(ItemsSource);
_isUpdating = true;
base.UpdateItemsSource();
//we don't need to Subscribe because base calls CreateItemsViewSource
_carouselViewLoopManager?.SetItemsSource(LoopItemsSource);
if (InitialPositionSet && ItemsView is CarouselView carousel)
{
carousel.SetValueFromRenderer(CarouselView.CurrentItemProperty, null);
carousel.SetValueFromRenderer(CarouselView.PositionProperty, 0);
}
_isUpdating = false;
}
protected override bool IsHorizontal => ItemsView?.ItemsLayout?.Orientation == ItemsLayoutOrientation.Horizontal;
protected override UICollectionViewDelegateFlowLayout CreateDelegator() => new CarouselViewDelegator2(ItemsViewLayout, this);
protected override string DetermineCellReuseId(NSIndexPath indexPath)
{
var itemIndex = GetAdjustedIndexPathForItemSource(indexPath);
return base.DetermineCellReuseId(itemIndex);
}
private protected override (Type CellType, string CellTypeReuseId) DetermineTemplatedCellType()
=> (typeof(CarouselTemplatedCell2), CarouselTemplatedCell2.ReuseId);
protected override Items.IItemsViewSource CreateItemsViewSource()
{
var itemsSource = ItemsSourceFactory2.CreateForCarouselView(ItemsView.ItemsSource, this, ItemsView.Loop);
_carouselViewLoopManager?.SetItemsSource(itemsSource);
SubscribeCollectionItemsSourceChanged(itemsSource);
return itemsSource;
}
private protected override async void AttachingToWindow()
{
base.AttachingToWindow();
Setup(ItemsView);
// if we navigate back on NavigationController LayoutSubviews might not fire.
await UpdateInitialPosition();
}
private protected override void DetachingFromWindow()
{
base.DetachingFromWindow();
TearDown(ItemsView);
}
internal bool InitialPositionSet { get; private set; }
void TearDown(CarouselView carouselView)
{
_oldViews = null;
InitialPositionSet = false;
UnsubscribeCollectionItemsSourceChanged(ItemsSource);
_carouselViewLoopManager?.Dispose();
_carouselViewLoopManager = null;
_isUpdating = false;
}
internal void UpdateScrollingConstraints()
{
CollectionView.AlwaysBounceVertical = !IsHorizontal;
CollectionView.AlwaysBounceHorizontal = IsHorizontal;
}
void Setup(CarouselView carouselView)
{
InitializeCarouselViewLoopManager();
_oldViews = new List<View>();
SubscribeCollectionItemsSourceChanged(ItemsSource);
}
internal void UpdateIsScrolling(bool isScrolling)
{
if (ItemsView is CarouselView carousel)
{
carousel.IsScrolling = isScrolling;
}
}
internal NSIndexPath GetScrollToIndexPath(int position)
{
if (ItemsView?.Loop == true && _carouselViewLoopManager != null)
{
return _carouselViewLoopManager.GetCorrectedIndexPathFromIndex(position);
}
return NSIndexPath.FromItemSection(position, _section);
}
internal int GetIndexFromIndexPath(NSIndexPath indexPath)
{
if (ItemsView?.Loop == true && _carouselViewLoopManager != null)
{
return _carouselViewLoopManager.GetCorrectedIndexFromIndexPath(indexPath);
}
return indexPath.Row;
}
// [UnconditionalSuppressMessage("Memory", "MEM0003", Justification = "Proven safe in test: MemoryTests.HandlerDoesNotLeak")]
// void CarouselViewScrolled(object sender, ItemsViewScrolledEventArgs e)
// {
// System.Diagnostics.Debug.WriteLine($"CarouselViewScrolled: {e.CenterItemIndex}");
// // If we are trying to center the item when Loop is enabled we don't want to update the position
// // if (_isCenteringItem)
// // {
// // return;
// // }
// // // If we are dragging the carousel we don't want to update the position
// // // We will do it when the dragging ends
// // if (_isDragging)
// // {
// // return;
// // }
// // SetPosition(e.CenterItemIndex);
// UpdateVisualStates();
// }
int _positionAfterUpdate = -1;
[UnconditionalSuppressMessage("Memory", "MEM0003", Justification = "Proven safe in test: MemoryTests.HandlerDoesNotLeak")]
void CollectionViewUpdating(object sender, NotifyCollectionChangedEventArgs e)
{
_isUpdating = true;
if (ItemsView is not CarouselView carousel)
{
return;
}
var count = ItemsSource.ItemCount;
if (count == 0)
{
_positionAfterUpdate = -1;
return;
}
int carouselPosition = carousel.Position;
_positionAfterUpdate = carouselPosition;
var currentItemPosition = ItemsSource.GetIndexForItem(carousel.CurrentItem).Row;
if (e.Action == NotifyCollectionChangedAction.Remove)
{
_positionAfterUpdate = GetPositionWhenRemovingItems(e.OldStartingIndex, carouselPosition, currentItemPosition, count);
}
if (e.Action == NotifyCollectionChangedAction.Reset)
{
_positionAfterUpdate = GetPositionWhenResetItems();
}
if (e.Action == NotifyCollectionChangedAction.Add)
{
_positionAfterUpdate = GetPositionWhenAddingItems(carouselPosition, currentItemPosition);
}
}
[UnconditionalSuppressMessage("Memory", "MEM0003", Justification = "Proven safe in test: MemoryTests.HandlerDoesNotLeak")]
void CollectionViewUpdated(object sender, NotifyCollectionChangedEventArgs e)
{
int targetPosition;
if (_positionAfterUpdate == -1)
{
return;
}
//_gotoPosition = -1;
// We need to update the position while modifying the collection.
targetPosition = GetTargetPosition();
_positionAfterUpdate = -1;
SetPosition(targetPosition);
SetCurrentItem(targetPosition);
if (e.Action == NotifyCollectionChangedAction.Reset)
{
}
else
{
//Since we can be removing the item that is already created next to the current item we need to update the visible cells
if (ItemsView.Loop)
{
CollectionView.ReloadItems(new NSIndexPath[] { GetScrollToIndexPath(targetPosition) });
}
}
_isUpdating = false;
ScrollToPosition(targetPosition, targetPosition, false, true);
}
int GetPositionWhenAddingItems(int carouselPosition, int currentItemPosition)
{
//If we are adding a new item make sure to maintain the CurrentItemPosition
return currentItemPosition != -1 ? currentItemPosition : carouselPosition;
}
private int GetTargetPosition()
{
if (ItemsSource.ItemCount == 0)
{
return 0;
}
return ItemsView.ItemsUpdatingScrollMode switch
{
ItemsUpdatingScrollMode.KeepItemsInView => 0,
ItemsUpdatingScrollMode.KeepLastItemInView => ItemsSource.ItemCount - 1,
_ => _positionAfterUpdate
};
}
int GetPositionWhenResetItems()
{
//If we are reseting the collection Position should go to 0
ItemsView?.SetValueFromRenderer(CarouselView.CurrentItemProperty, null);
return 0;
}
int GetPositionWhenRemovingItems(int oldStartingIndex, int carouselPosition, int currentItemPosition, int count)
{
bool removingCurrentElement = currentItemPosition == -1;
bool removingFirstElement = oldStartingIndex == 0;
bool removingLastElement = oldStartingIndex == count;
int currentPosition = ItemsView?.Position ?? 0;
bool removingCurrentElementAndLast = removingCurrentElement && removingLastElement && currentPosition > 0;
if (removingCurrentElementAndLast)
{
//If we are removing the last element update the position
carouselPosition = currentPosition - 1;
}
else if (removingFirstElement && !removingCurrentElement)
{
//If we are not removing the current element set position to the CurrentItem
carouselPosition = currentItemPosition;
}
return carouselPosition;
}
void SubscribeCollectionItemsSourceChanged(Items.IItemsViewSource itemsSource)
{
UnsubscribeCollectionItemsSourceChanged(ItemsSource);
if (itemsSource is Items.ObservableItemsSource newItemsSource)
{
newItemsSource.CollectionViewUpdating += CollectionViewUpdating;
newItemsSource.CollectionViewUpdated += CollectionViewUpdated;
}
}
void UnsubscribeCollectionItemsSourceChanged(Items.IItemsViewSource oldItemsSource)
{
if (oldItemsSource is Items.ObservableItemsSource oldObservableItemsSource)
{
oldObservableItemsSource.CollectionViewUpdating -= CollectionViewUpdating;
oldObservableItemsSource.CollectionViewUpdated -= CollectionViewUpdated;
}
}
internal bool IsUpdating()
{
return _isUpdating;
}
internal void UpdateLoop()
{
if (ItemsView is not CarouselView carousel)
{
return;
}
var carouselPosition = carousel.Position;
if (LoopItemsSource is not null)
{
LoopItemsSource.Loop = carousel.Loop;
}
// CollectionView.ReloadData();
// ScrollToPosition(carouselPosition, carouselPosition, false, true);
}
void ScrollToPosition(int goToPosition, int carouselPosition, bool animate, bool forceScroll = false)
{
if (ItemsView is not CarouselView carousel)
{
return;
}
if (ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
if (goToPosition != carouselPosition || forceScroll)
{
UICollectionViewScrollPosition uICollectionViewScrollPosition = IsHorizontal ? UICollectionViewScrollPosition.CenteredHorizontally : UICollectionViewScrollPosition.CenteredVertically;
var goToIndexPath = GetScrollToIndexPath(goToPosition);
if (!LayoutFactory2.IsIndexPathValid(goToIndexPath, CollectionView))
{
return;
}
CollectionView.ScrollToItem(goToIndexPath, uICollectionViewScrollPosition, animate);
}
}
internal void SetPosition(int position)
{
if (ItemsView is not CarouselView carousel)
{
return;
}
if (ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
if (!InitialPositionSet || position == -1)
{
return;
}
ItemsView.SetValueFromRenderer(CarouselView.PositionProperty, position);
SetCurrentItem(position);
UpdateVisualStates();
}
void SetCurrentItem(int carouselPosition)
{
if (ItemsView is not CarouselView carousel)
{
return;
}
if (ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
var item = GetItemAtIndex(NSIndexPath.FromItemSection(carouselPosition, _section));
ItemsView?.SetValueFromRenderer(CarouselView.CurrentItemProperty, item);
UpdateVisualStates();
}
internal void UpdateFromCurrentItem()
{
if (!InitialPositionSet)
return;
if (ItemsView is not CarouselView carousel)
{
return;
}
if (carousel.CurrentItem is null || ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
var currentItemPosition = GetIndexForItem(carousel.CurrentItem).Row;
ScrollToPosition(currentItemPosition, carousel.Position, carousel.AnimateCurrentItemChanges);
UpdateVisualStates();
}
internal void UpdateFromPosition()
{
if (!InitialPositionSet)
{
return;
}
if (ItemsView is not CarouselView carousel)
{
return;
}
if (ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
var currentItemPosition = GetIndexForItem(carousel.CurrentItem).Row;
var carouselPosition = carousel.Position;
ScrollToPosition(carouselPosition, currentItemPosition, carousel.AnimatePositionChanges);
// SetCurrentItem(carouselPosition);
}
async Task UpdateInitialPosition()
{
if (ItemsView is not CarouselView carousel)
{
return;
}
if (!ItemsView.IsVisible)
{
// If the CarouselView is not visible we don't want to set the initial position
// since it will be set when the CarouselView becomes visible
return;
}
if (ItemsSource is null)
{
return;
}
if (InitialPositionSet)
{
return;
}
await Task.Delay(100).ContinueWith(_ =>
{
MainThread.BeginInvokeOnMainThread(() =>
{
if (!IsViewLoaded)
{
return;
}
if (ItemsSource is null || ItemsSource.ItemCount == 0)
{
return;
}
InitialPositionSet = true;
int position = carousel.Position;
var currentItem = carousel.CurrentItem;
if (currentItem != null)
{
// Sometimes the item could be just being removed while we navigate back to the CarouselView
var positionCurrentItem = ItemsSource.GetIndexForItem(currentItem).Row;
if (positionCurrentItem != -1)
{
position = positionCurrentItem;
}
}
var projectedPosition = LoopItemsSource.Loop
? GetScrollToIndexPath(position) // We need to set the position to the correct position since we added 1 item at the beginning
: NSIndexPath.FromItemSection(position, _section);
var uICollectionViewScrollPosition = IsHorizontal ? UICollectionViewScrollPosition.CenteredHorizontally : UICollectionViewScrollPosition.CenteredVertically;
if (!LayoutFactory2.IsIndexPathValid(projectedPosition, CollectionView))
{
return;
}
CollectionView.ScrollToItem(projectedPosition, uICollectionViewScrollPosition, false);
//Set the position on VirtualView to update the CurrentItem also
SetPosition(position);
UpdateVisualStates();
});
});
}
void UpdateVisualStates()
{
if (ItemsView is not CarouselView carousel)
{
return;
}
// We aren't ready to update the visual states yet
if (_oldViews is null)
{
return;
}
var cells = CollectionView.VisibleCells;
var newViews = new List<View>();
var carouselPosition = carousel.Position;
var previousPosition = carouselPosition - 1;
var nextPosition = carouselPosition + 1;
foreach (var cell in cells)
{
if (!((cell as TemplatedCell2)?.PlatformHandler?.VirtualView is View itemView))
{
return;
}
var item = itemView.BindingContext;
var pos = GetIndexForItem(item).Row;
if (pos == carouselPosition)
{
VisualStateManager.GoToState(itemView, CarouselView.CurrentItemVisualState);
}
else if (pos == previousPosition)
{
VisualStateManager.GoToState(itemView, CarouselView.PreviousItemVisualState);
}
else if (pos == nextPosition)
{
VisualStateManager.GoToState(itemView, CarouselView.NextItemVisualState);
}
else
{
VisualStateManager.GoToState(itemView, CarouselView.DefaultItemVisualState);
}
newViews.Add(itemView);
if (!carousel.VisibleViews.Contains(itemView))
{
carousel.VisibleViews.Add(itemView);
}
}
foreach (var itemView in _oldViews)
{
if (!newViews.Contains(itemView))
{
VisualStateManager.GoToState(itemView, CarouselView.DefaultItemVisualState);
if (carousel.VisibleViews.Contains(itemView))
{
carousel.VisibleViews.Remove(itemView);
}
}
}
_oldViews = newViews;
}
internal protected override void UpdateVisibility()
{
if (ItemsView.IsVisible)
{
CollectionView.Hidden = false;
}
else
{
CollectionView.Hidden = true;
}
}
}
| CarouselViewController2 |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Shell/TaskbarManager.cs | {
"start": 291,
"end": 7164
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal TaskbarManager()
{
}
#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 IsPinningAllowed
{
get
{
throw new global::System.NotImplementedException("The member bool TaskbarManager.IsPinningAllowed is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20TaskbarManager.IsPinningAllowed");
}
}
#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 IsSupported
{
get
{
throw new global::System.NotImplementedException("The member bool TaskbarManager.IsSupported is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20TaskbarManager.IsSupported");
}
}
#endif
// Forced skipping of method Windows.UI.Shell.TaskbarManager.IsSupported.get
// Forced skipping of method Windows.UI.Shell.TaskbarManager.IsPinningAllowed.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncOperation<bool> IsCurrentAppPinnedAsync()
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.IsCurrentAppPinnedAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.IsCurrentAppPinnedAsync%28%29");
}
#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.IAsyncOperation<bool> IsAppListEntryPinnedAsync(global::Windows.ApplicationModel.Core.AppListEntry appListEntry)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.IsAppListEntryPinnedAsync(AppListEntry appListEntry) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.IsAppListEntryPinnedAsync%28AppListEntry%20appListEntry%29");
}
#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.IAsyncOperation<bool> RequestPinCurrentAppAsync()
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.RequestPinCurrentAppAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.RequestPinCurrentAppAsync%28%29");
}
#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.IAsyncOperation<bool> RequestPinAppListEntryAsync(global::Windows.ApplicationModel.Core.AppListEntry appListEntry)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.RequestPinAppListEntryAsync(AppListEntry appListEntry) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.RequestPinAppListEntryAsync%28AppListEntry%20appListEntry%29");
}
#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.IAsyncOperation<bool> IsSecondaryTilePinnedAsync(string tileId)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.IsSecondaryTilePinnedAsync(string tileId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.IsSecondaryTilePinnedAsync%28string%20tileId%29");
}
#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.IAsyncOperation<bool> RequestPinSecondaryTileAsync(global::Windows.UI.StartScreen.SecondaryTile secondaryTile)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.RequestPinSecondaryTileAsync(SecondaryTile secondaryTile) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.RequestPinSecondaryTileAsync%28SecondaryTile%20secondaryTile%29");
}
#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.IAsyncOperation<bool> TryUnpinSecondaryTileAsync(string tileId)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<bool> TaskbarManager.TryUnpinSecondaryTileAsync(string tileId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3Cbool%3E%20TaskbarManager.TryUnpinSecondaryTileAsync%28string%20tileId%29");
}
#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 static global::Windows.UI.Shell.TaskbarManager GetDefault()
{
throw new global::System.NotImplementedException("The member TaskbarManager TaskbarManager.GetDefault() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=TaskbarManager%20TaskbarManager.GetDefault%28%29");
}
#endif
}
}
| TaskbarManager |
csharp | bitwarden__server | src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyRequirements/OrganizationDataOwnershipPolicyRequirement.cs | {
"start": 2926,
"end": 3185
} | public record ____(Guid OrganizationUserId, bool ShouldCreateDefaultCollection)
{
public readonly bool ShouldCreateDefaultCollection = ShouldCreateDefaultCollection;
public readonly Guid OrganizationUserId = OrganizationUserId;
}
| DefaultCollectionRequest |
csharp | dotnet__aspire | src/Aspire.Hosting.Qdrant/QdrantContainerImageTags.cs | {
"start": 172,
"end": 477
} | internal static class ____
{
/// <remarks>docker.io</remarks>
public const string Registry = "docker.io";
/// <remarks>qdrant/qdrant</remarks>
public const string Image = "qdrant/qdrant";
/// <remarks>v1.15.5</remarks>
public const string Tag = "v1.15.5";
}
| QdrantContainerImageTags |
csharp | microsoft__garnet | libs/server/Custom/CustomCommandRegistration.cs | {
"start": 5246,
"end": 5651
} | internal abstract class ____<T> : RegisterCustomCommandProviderBase<T, RegisterCmdArgs>
{
protected RegisterCustomCmdProvider(T instance, RegisterCmdArgs args) : base(instance, args)
{
}
}
/// <summary>
/// Base custom transaction registration provider
/// </summary>
/// <typeparam name="T">Type of custom transaction</typeparam>
| RegisterCustomCmdProvider |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonPrimitiveCollectionSqlServerTest.cs | {
"start": 211,
"end": 3264
} | public class ____(ComplexJsonSqlServerFixture fixture, ITestOutputHelper testOutputHelper)
: ComplexJsonPrimitiveCollectionRelationalTestBase<ComplexJsonSqlServerFixture>(fixture, testOutputHelper)
{
public override async Task Count()
{
await base.Count();
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE (
SELECT COUNT(*)
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) AS [i]) = 3
""");
}
public override async Task Index()
{
await base.Index();
if (Fixture.UsingJsonType)
{
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE JSON_VALUE([r].[RequiredAssociate], '$.Ints[0]' RETURNING int) = 1
""");
}
else
{
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE CAST(JSON_VALUE([r].[RequiredAssociate], '$.Ints[0]') AS int) = 1
""");
}
}
public override async Task Contains()
{
await base.Contains();
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE 3 IN (
SELECT [i].[value]
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) WITH ([value] int '$') AS [i]
)
""");
}
public override async Task Any_predicate()
{
await base.Any_predicate();
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE 2 IN (
SELECT [i].[value]
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) WITH ([value] int '$') AS [i]
)
""");
}
public override async Task Nested_Count()
{
await base.Nested_Count();
AssertSql(
"""
SELECT [r].[Id], [r].[Name], [r].[AssociateCollection], [r].[OptionalAssociate], [r].[RequiredAssociate]
FROM [RootEntity] AS [r]
WHERE (
SELECT COUNT(*)
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.RequiredNestedAssociate.Ints')) AS [i]) = 3
""");
}
public override async Task Select_Sum()
{
await base.Select_Sum();
AssertSql(
"""
SELECT (
SELECT COALESCE(SUM([i0].[value]), 0)
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) WITH ([value] int '$') AS [i0])
FROM [RootEntity] AS [r]
WHERE (
SELECT COALESCE(SUM([i].[value]), 0)
FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) WITH ([value] int '$') AS [i]) >= 6
""");
}
[ConditionalFact]
public virtual void Check_all_tests_overridden()
=> TestHelpers.AssertAllMethodsOverridden(GetType());
}
| ComplexJsonPrimitiveCollectionSqlServerTest |
csharp | dotnet__aspire | tests/Aspire.StackExchange.Redis.Tests/ConformanceTests.cs | {
"start": 420,
"end": 4633
} | public class ____ : ConformanceTests<IConnectionMultiplexer, StackExchangeRedisSettings>, IClassFixture<RedisContainerFixture>
{
private readonly RedisContainerFixture _containerFixture;
protected string ConnectionString => _containerFixture.GetConnectionString();
protected override ServiceLifetime ServiceLifetime => ServiceLifetime.Singleton;
protected override bool CanConnectToServer => RequiresDockerAttribute.IsSupported;
protected override bool SupportsKeyedRegistrations => true;
protected override string[] RequiredLogCategories => ["StackExchange.Redis.ConnectionMultiplexer"];
protected override string? ConfigurationSectionName => "Aspire:StackExchange:Redis";
// https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/e4cb523a4a3592e1a1adf30f3596025bfd8978e3/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisConnectionInstrumentation.cs#L34
protected override string ActivitySourceName => "OpenTelemetry.Instrumentation.StackExchangeRedis";
protected override string ValidJsonConfig => """
{
"Aspire": {
"StackExchange": {
"Redis": {
"ConnectionString": "YOUR_ENDPOINT",
"DisableHealthChecks": false,
"DisableTracing": true,
"ConfigurationOptions": {
"CheckCertificateRevocation": true,
"ConnectTimeout": 5,
"HeartbeatInterval": "00:00:02",
"Ssl" : true,
"SslProtocols" : "Tls11"
}
}
}
}
}
""";
protected override (string json, string error)[] InvalidJsonToErrorMessage => new[]
{
("""{"Aspire": { "StackExchange": { "Redis":{ "ConfigurationOptions": "YOUR_OPTION"}}}}""", "Value is \"string\" but should be \"object\""),
("""{"Aspire": { "StackExchange": { "Redis":{ "ConfigurationOptions": { "Proxy": "Fast"}}}}}""", "Value should match one of the values specified by the enum"),
("""{"Aspire": { "StackExchange": { "Redis":{ "ConfigurationOptions": { "SslProtocols": "Fast"}}}}}""", "Value should match one of the values specified by the enum"),
("""{"Aspire": { "StackExchange": { "Redis":{ "ConfigurationOptions": { "HeartbeatInterval": "3S"}}}}}""", "The string value is not a match for the indicated regular expression")
};
public ConformanceTests(RedisContainerFixture containerFixture, ITestOutputHelper? output = null) : base(output)
{
_containerFixture = containerFixture;
}
protected override void PopulateConfiguration(ConfigurationManager configuration, string? key = null)
{
string connectionString = RequiresDockerAttribute.IsSupported
? _containerFixture.GetConnectionString()
: "localhost";
configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>(ConformanceTests.CreateConfigKey("Aspire:StackExchange:Redis", key, "ConnectionString"), connectionString)
]);
}
protected override void RegisterComponent(HostApplicationBuilder builder, Action<StackExchangeRedisSettings>? configure = null, string? key = null)
{
if (key is null)
{
builder.AddRedisClient("redis", configure);
}
else
{
builder.AddKeyedRedisClient(key, configure);
}
}
protected override void SetHealthCheck(StackExchangeRedisSettings options, bool enabled)
=> options.DisableHealthChecks = !enabled;
protected override void SetTracing(StackExchangeRedisSettings options, bool enabled)
=> options.DisableTracing = !enabled;
protected override void SetMetrics(StackExchangeRedisSettings options, bool enabled)
=> throw new NotImplementedException();
protected override void TriggerActivity(IConnectionMultiplexer service)
{
var database = service.GetDatabase();
string id = Guid.NewGuid().ToString();
database.StringSet(id, "hello");
database.KeyDelete(id);
}
}
| ConformanceTests |
csharp | grpc__grpc-dotnet | test/FunctionalTests/Server/ServerStreamingMethodTests.cs | {
"start": 9007,
"end": 9832
} | public class ____
{
public SyncPoint SyncPoint { get; set; } = default!;
public ILogger Logger { get; set; } = default!;
public async Task SayHellosAsync(HelloRequest request, IServerStreamWriter<HelloReply> responseStream)
{
for (var i = 0; i < 3; i++)
{
await SyncPoint.WaitToContinue();
var message = $"How are you {request.Name}? {i}";
Logger.LogInformation("Sending message");
await responseStream.WriteAsync(new HelloReply { Message = message });
}
await SyncPoint.WaitToContinue();
Logger.LogInformation("Sending message");
await responseStream.WriteAsync(new HelloReply { Message = $"Goodbye {request.Name}!" });
}
}
}
| MethodWrapper |
csharp | fluentassertions__fluentassertions | Src/FluentAssertions/Primitives/NullableEnumAssertions.cs | {
"start": 690,
"end": 4686
} | public class ____<TEnum, TAssertions> : EnumAssertions<TEnum, TAssertions>
where TEnum : struct, Enum
where TAssertions : NullableEnumAssertions<TEnum, TAssertions>
{
private readonly AssertionChain assertionChain;
public NullableEnumAssertions(TEnum? subject, AssertionChain assertionChain)
: base(subject, assertionChain)
{
this.assertionChain = assertionChain;
}
/// <summary>
/// Asserts that a nullable <typeparamref name="TEnum"/> value is not <see langword="null"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndWhichConstraint<TAssertions, TEnum> HaveValue([StringSyntax("CompositeFormat")] string because = "", params object[] becauseArgs)
{
assertionChain
.ForCondition(Subject.HasValue)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:nullable enum} to have a value{reason}, but found {0}.", Subject);
return new AndWhichConstraint<TAssertions, TEnum>((TAssertions)this, Subject.GetValueOrDefault(), assertionChain, ".Value");
}
/// <summary>
/// Asserts that a nullable <typeparamref name="TEnum"/> is not <see langword="null"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndWhichConstraint<TAssertions, TEnum> NotBeNull([StringSyntax("CompositeFormat")] string because = "", params object[] becauseArgs)
{
return HaveValue(because, becauseArgs);
}
/// <summary>
/// Asserts that a nullable <typeparamref name="TEnum"/> value is <see langword="null"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotHaveValue([StringSyntax("CompositeFormat")] string because = "", params object[] becauseArgs)
{
assertionChain
.ForCondition(!Subject.HasValue)
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {context:nullable enum} to have a value{reason}, but found {0}.", Subject);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a nullable <typeparamref name="TEnum"/> value is <see langword="null"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeNull([StringSyntax("CompositeFormat")] string because = "", params object[] becauseArgs)
{
return NotHaveValue(because, becauseArgs);
}
}
| NullableEnumAssertions |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs | {
"start": 22442,
"end": 23403
} | internal class ____ : IXmlNode
{
private readonly XObject? _xmlObject;
public XObjectWrapper(XObject? xmlObject)
{
_xmlObject = xmlObject;
}
public object? WrappedNode => _xmlObject;
public virtual XmlNodeType NodeType => _xmlObject?.NodeType ?? XmlNodeType.None;
public virtual string? LocalName => null;
public virtual List<IXmlNode> ChildNodes => XmlNodeConverter.EmptyChildNodes;
public virtual List<IXmlNode> Attributes => XmlNodeConverter.EmptyChildNodes;
public virtual IXmlNode? ParentNode => null;
public virtual string? Value
{
get => null;
set => throw new InvalidOperationException();
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string? NamespaceUri => null;
}
| XObjectWrapper |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/BasicStringSerializerTests.cs | {
"start": 338,
"end": 1227
} | public class ____
{
readonly char[] allCharsUsed = new[] {
JsWriter.QuoteChar, JsWriter.ItemSeperator,
JsWriter.MapStartChar, JsWriter.MapKeySeperator, JsWriter.MapEndChar,
JsWriter.ListEndChar, JsWriter.ListEndChar,
};
readonly string fieldWithInvalidChars = string.Format("all {0} {1} {2} {3} {4} {5} {6} invalid chars",
JsWriter.QuoteChar, JsWriter.ItemSeperator,
JsWriter.MapStartChar, JsWriter.MapKeySeperator, JsWriter.MapEndChar,
JsWriter.ListEndChar, JsWriter.ListEndChar);
readonly int[] intValues = new[] { 1, 2, 3, 4, 5 };
readonly double[] doubleValues = new[] { 1.0d, 2.0d, 3.0d, 4.0d, 5.0d };
readonly string[] stringValues = new[] { "One", "Two", "Three", "Four", "Five" };
readonly string[] stringValuesWithIllegalChar = new[] { "One", ",", "Three", "Four", "Five" };
| BasicStringSerializerTests |
csharp | dotnet__efcore | src/EFCore.Relational/Migrations/Operations/AlterSequenceOperation.cs | {
"start": 501,
"end": 1247
} | public class ____ : SequenceOperation, IAlterMigrationOperation
{
/// <summary>
/// The schema that contains the sequence, or <see langword="null" /> if the default schema should be used.
/// </summary>
public virtual string? Schema { get; set; }
/// <summary>
/// The name of the sequence.
/// </summary>
public virtual string Name { get; set; } = null!;
/// <summary>
/// An operation representing the sequence as it was before being altered.
/// </summary>
public virtual SequenceOperation OldSequence { get; set; } = new CreateSequenceOperation();
/// <inheritdoc />
IMutableAnnotatable IAlterMigrationOperation.OldAnnotations
=> OldSequence;
}
| AlterSequenceOperation |
csharp | MassTransit__MassTransit | src/MassTransit/Serialization/SystemTextJsonRawMessageBody.cs | {
"start": 191,
"end": 1996
} | public class ____<TMessage> :
MessageBody
where TMessage : class
{
readonly object? _message;
readonly JsonSerializerOptions _options;
byte[]? _bytes;
string? _string;
public SystemTextJsonRawMessageBody(SendContext<TMessage> context, JsonSerializerOptions options, object? message = null)
{
_options = options;
_message = message ?? context.Message;
}
public long? Length => _bytes?.Length ?? _string?.Length;
public Stream GetStream()
{
return new MemoryStream(GetBytes(), false);
}
public byte[] GetBytes()
{
if (_bytes != null)
return _bytes;
if (_string != null)
{
_bytes = Encoding.UTF8.GetBytes(_string);
return _bytes;
}
try
{
_bytes = JsonSerializer.SerializeToUtf8Bytes(_message, _options);
return _bytes;
}
catch (Exception ex)
{
throw new SerializationException("Failed to serialize message", ex);
}
}
public string GetString()
{
if (_string != null)
return _string;
if (_bytes != null)
{
_string = Encoding.UTF8.GetString(_bytes);
return _string;
}
try
{
_string = JsonSerializer.Serialize(_message, _options);
return _string;
}
catch (Exception ex)
{
throw new SerializationException("Failed to serialize message", ex);
}
}
}
}
| SystemTextJsonRawMessageBody |
csharp | AutoFixture__AutoFixture | Src/AutoFixture/DataAnnotations/StringLengthAttributeRelay.cs | {
"start": 263,
"end": 2353
} | public class ____ : ISpecimenBuilder
{
private IRequestMemberTypeResolver requestMemberTypeResolver = new RequestMemberTypeResolver();
/// <summary>
/// Gets or sets the current IRequestMemberTypeResolver.
/// </summary>
public IRequestMemberTypeResolver RequestMemberTypeResolver
{
get => this.requestMemberTypeResolver;
set => this.requestMemberTypeResolver = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Creates a new specimen based on a specified length of characters that are allowed.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">A container that can be used to create other specimens.</param>
/// <returns>
/// A specimen created from a <see cref="RangedNumberRequest"/> encapsulating the operand
/// type, the minimum and the maximum of the requested number, if possible; otherwise,
/// a <see cref="NoSpecimen"/> instance.
/// </returns>
public object Create(object request, ISpecimenContext context)
{
if (context is null) throw new ArgumentNullException(nameof(context));
if (request is null)
{
return new NoSpecimen();
}
var attribute = TypeEnvy.GetAttribute<StringLengthAttribute>(request);
if (attribute is null)
{
return new NoSpecimen();
}
if (!this.RequestMemberTypeResolver.TryGetMemberType(request, out var memberType))
{
return new NoSpecimen();
}
if (memberType != typeof(string))
{
return new NoSpecimen();
}
var stringRequest = new ConstrainedStringRequest(
attribute.MinimumLength,
attribute.MaximumLength);
return context.Resolve(stringRequest);
}
}
} | StringLengthAttributeRelay |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ApplicationModels/DefaultApplicationModelProviderTest.cs | {
"start": 56470,
"end": 56686
} | private class ____ : ViewFeaturesController
{
public new void Dispose()
{
throw new NotImplementedException();
}
}
| DerivedFromControllerAndHidesBaseDisposeMethodController |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.ViewManagement/AccessibilitySettings.cs | {
"start": 260,
"end": 1148
} | public partial class ____
{
// Skipping already declared property HighContrast
// Skipping already declared property HighContrastScheme
// Skipping already declared method Windows.UI.ViewManagement.AccessibilitySettings.AccessibilitySettings()
// Forced skipping of method Windows.UI.ViewManagement.AccessibilitySettings.AccessibilitySettings()
// Forced skipping of method Windows.UI.ViewManagement.AccessibilitySettings.HighContrast.get
// Forced skipping of method Windows.UI.ViewManagement.AccessibilitySettings.HighContrastScheme.get
// Forced skipping of method Windows.UI.ViewManagement.AccessibilitySettings.HighContrastChanged.add
// Forced skipping of method Windows.UI.ViewManagement.AccessibilitySettings.HighContrastChanged.remove
// Skipping already declared event Windows.UI.ViewManagement.AccessibilitySettings.HighContrastChanged
}
}
| AccessibilitySettings |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Language/test/Language.Tests/ValueNodeExtensionsTests.cs | {
"start": 34,
"end": 808
} | public static class ____
{
[Fact]
public static void IsNull_Null_True()
{
// arrange
var value = default(IValueNode);
// act
var result = value.IsNull();
// assert
Assert.True(result);
}
[Fact]
public static void IsNull_NullValueNode_True()
{
// arrange
IValueNode value = NullValueNode.Default;
// act
var result = value.IsNull();
// assert
Assert.True(result);
}
[Fact]
public static void IsNull_StringValueNode_False()
{
// arrange
IValueNode value = new StringValueNode("foo");
// act
var result = value.IsNull();
// assert
Assert.False(result);
}
}
| ValueNodeExtensionsTests |
csharp | jellyfin__jellyfin | MediaBrowser.Controller/Channels/IChannelManager.cs | {
"start": 343,
"end": 3730
} | public interface ____
{
/// <summary>
/// Gets the channel features.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>ChannelFeatures.</returns>
ChannelFeatures GetChannelFeatures(Guid? id);
/// <summary>
/// Gets all channel features.
/// </summary>
/// <returns>IEnumerable{ChannelFeatures}.</returns>
ChannelFeatures[] GetAllChannelFeatures();
bool EnableMediaSourceDisplay(BaseItem item);
bool CanDelete(BaseItem item);
Task DeleteItem(BaseItem item);
/// <summary>
/// Gets the channel.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Channel.</returns>
Channel GetChannel(string id);
/// <summary>
/// Gets the channels internal.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The channels.</returns>
Task<QueryResult<Channel>> GetChannelsInternalAsync(ChannelQuery query);
/// <summary>
/// Gets the channels.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The channels.</returns>
Task<QueryResult<BaseItemDto>> GetChannelsAsync(ChannelQuery query);
/// <summary>
/// Gets the latest channel items.
/// </summary>
/// <param name="query">The item query.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The latest channels.</returns>
Task<QueryResult<BaseItemDto>> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
/// Gets the latest channel items.
/// </summary>
/// <param name="query">The item query.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The latest channels.</returns>
Task<QueryResult<BaseItem>> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel items.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The channel items.</returns>
Task<QueryResult<BaseItemDto>> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel items.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="progress">The progress to report to.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The channel items.</returns>
Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQuery query, IProgress<double> progress, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel item media sources.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The item media sources.</returns>
IEnumerable<MediaSourceInfo> GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken);
}
}
| IChannelManager |
csharp | dotnet__orleans | test/Extensions/AWSUtils.Tests/Streaming/SQSClientStreamTests.cs | {
"start": 2249,
"end": 3511
} | private class ____ : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder
.AddSqsStreams(SQSStreamProviderName, (Action<SqsOptions>)(options =>
{
options.ConnectionString = AWSTestConstants.SqsConnectionString;
}));
}
}
public override async Task DisposeAsync()
{
var clusterId = HostedCluster.Options.ClusterId;
await base.DisposeAsync();
if (!string.IsNullOrWhiteSpace(StorageConnectionString))
{
await SQSStreamProviderUtils.DeleteAllUsedQueues(SQSStreamProviderName, clusterId, StorageConnectionString, NullLoggerFactory.Instance);
}
}
[SkippableFact, TestCategory("AWS")]
public async Task SQSStreamProducerOnDroppedClientTest()
{
logger.LogInformation("************************ AQStreamProducerOnDroppedClientTest *********************************");
await runner.StreamProducerOnDroppedClientTest(SQSStreamProviderName, StreamNamespace);
}
}
}
| MyClientBuilderConfigurator |
csharp | FluentValidation__FluentValidation | src/FluentValidation/Validators/GreaterThanValidator.cs | {
"start": 820,
"end": 1831
} | public class ____<T, TProperty> : AbstractComparisonValidator<T, TProperty> where TProperty : IComparable<TProperty>, IComparable {
public override string Name => "GreaterThanValidator";
public GreaterThanValidator(TProperty value) : base(value) {
}
public GreaterThanValidator(Func<T, TProperty> valueToCompareFunc, MemberInfo member, string memberDisplayName)
: base(valueToCompareFunc, member, memberDisplayName) {
}
public GreaterThanValidator(Func<T, (bool HasValue, TProperty Value)> valueToCompareFunc, MemberInfo member, string memberDisplayName)
: base(valueToCompareFunc, member, memberDisplayName) {
}
public override bool IsValid(TProperty value, TProperty valueToCompare) {
if (valueToCompare == null)
return false;
return value.CompareTo(valueToCompare) > 0;
}
public override Comparison Comparison => Validators.Comparison.GreaterThan;
protected override string GetDefaultMessageTemplate(string errorCode) {
return Localized(errorCode, Name);
}
}
| GreaterThanValidator |
csharp | dotnet__aspnetcore | src/Http/Headers/src/HeaderUtilities.cs | {
"start": 438,
"end": 27387
} | public static class ____
{
private const int _qualityValueMaxCharCount = 10; // Little bit more permissive than RFC7231 5.3.1
private const string QualityName = "q";
internal const string BytesUnit = "bytes";
internal static void SetQuality(IList<NameValueHeaderValue> parameters, double? value)
{
var qualityParameter = NameValueHeaderValue.Find(parameters, QualityName);
if (value.HasValue)
{
// Note that even if we check the value here, we can't prevent a user from adding an invalid quality
// value using Parameters.Add(). Even if we would prevent the user from adding an invalid value
// using Parameters.Add() they could always add invalid values using HttpHeaders.AddWithoutValidation().
// So this check is really for convenience to show users that they're trying to add an invalid
// value.
if ((value < 0) || (value > 1))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
var qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo);
if (qualityParameter != null)
{
qualityParameter.Value = qualityString;
}
else
{
parameters.Add(new NameValueHeaderValue(QualityName, qualityString));
}
}
else
{
// Remove quality parameter
if (qualityParameter != null)
{
parameters.Remove(qualityParameter);
}
}
}
internal static double? GetQuality(IList<NameValueHeaderValue>? parameters)
{
var qualityParameter = NameValueHeaderValue.Find(parameters, QualityName);
if (qualityParameter != null)
{
// Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal
// separator is considered invalid (even if the current culture would allow it).
if (TryParseQualityDouble(qualityParameter.Value, 0, out var qualityValue, out _))
{
return qualityValue;
}
}
return null;
}
internal static void CheckValidToken(StringSegment value, string parameterName)
{
if (StringSegment.IsNullOrEmpty(value))
{
throw new ArgumentException("An empty string is not allowed.", parameterName);
}
if (HttpRuleParser.GetTokenLength(value, 0) != value.Length)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Invalid token '{0}'.", value));
}
}
internal static bool AreEqualCollections<T>(ICollection<T>? x, ICollection<T>? y)
{
return AreEqualCollections(x, y, null);
}
internal static bool AreEqualCollections<T>(ICollection<T>? x, ICollection<T>? y, IEqualityComparer<T>? comparer)
{
if (x == null)
{
return (y == null) || (y.Count == 0);
}
if (y == null)
{
return (x.Count == 0);
}
if (x.Count != y.Count)
{
return false;
}
if (x.Count == 0)
{
return true;
}
// We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually
// headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive.
var alreadyFound = new bool[x.Count];
var i = 0;
foreach (var xItem in x)
{
Contract.Assert(xItem != null);
i = 0;
var found = false;
foreach (var yItem in y)
{
if (!alreadyFound[i])
{
if (((comparer == null) && xItem.Equals(yItem)) ||
((comparer != null) && comparer.Equals(xItem, yItem)))
{
alreadyFound[i] = true;
found = true;
break;
}
}
i++;
}
if (!found)
{
return false;
}
}
// Since we never re-use a "found" value in 'y', we expected 'alreadyFound' to have all fields set to 'true'.
// Otherwise the two collections can't be equal and we should not get here.
Contract.Assert(Contract.ForAll(alreadyFound, value => { return value; }),
"Expected all values in 'alreadyFound' to be true since collections are considered equal.");
return true;
}
internal static int GetNextNonEmptyOrWhitespaceIndex(
StringSegment input,
int startIndex,
bool skipEmptyValues,
out bool separatorFound)
{
Contract.Requires(startIndex <= input.Length); // it's OK if index == value.Length.
separatorFound = false;
var current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
if ((current == input.Length) || (input[current] != ','))
{
return current;
}
// If we have a separator, skip the separator and all following whitespaces. If we support
// empty values, continue until the current character is neither a separator nor a whitespace.
separatorFound = true;
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if (skipEmptyValues)
{
while ((current < input.Length) && (input[current] == ','))
{
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
return current;
}
private static int AdvanceCacheDirectiveIndex(int current, string headerValue)
{
// Skip until the next potential name
current += HttpRuleParser.GetWhitespaceLength(headerValue, current);
// Skip the value if present
if (current < headerValue.Length && headerValue[current] == '=')
{
current++; // skip '='
current += NameValueHeaderValue.GetValueLength(headerValue, current);
}
// Find the next delimiter
current = headerValue.IndexOf(',', current);
if (current == -1)
{
// If no delimiter found, skip to the end
return headerValue.Length;
}
current++; // skip ','
current += HttpRuleParser.GetWhitespaceLength(headerValue, current);
return current;
}
/// <summary>
/// Try to find a target header value among the set of given header values and parse it as a
/// <see cref="TimeSpan"/>.
/// </summary>
/// <param name="headerValues">
/// The <see cref="StringValues"/> containing the set of header values to search.
/// </param>
/// <param name="targetValue">
/// The target header value to look for.
/// </param>
/// <param name="value">
/// When this method returns, contains the parsed <see cref="TimeSpan"/>, if the parsing succeeded, or
/// null if the parsing failed. The conversion fails if the <paramref name="targetValue"/> was not
/// found or could not be parsed as a <see cref="TimeSpan"/>. This parameter is passed uninitialized;
/// any value originally supplied in result will be overwritten.
/// </param>
/// <returns>
/// <see langword="true" /> if <paramref name="targetValue"/> is found and successfully parsed; otherwise,
/// <see langword="false" />.
/// </returns>
// e.g. { "headerValue=10, targetHeaderValue=30" }
public static bool TryParseSeconds(StringValues headerValues, string targetValue, [NotNullWhen(true)] out TimeSpan? value)
{
if (StringValues.IsNullOrEmpty(headerValues) || string.IsNullOrEmpty(targetValue))
{
value = null;
return false;
}
for (var i = 0; i < headerValues.Count; i++)
{
var segment = headerValues[i] ?? string.Empty;
// Trim leading white space
var current = HttpRuleParser.GetWhitespaceLength(segment, 0);
while (current < segment.Length)
{
long seconds;
var initial = current;
var tokenLength = HttpRuleParser.GetTokenLength(headerValues[i], current);
if (tokenLength == targetValue.Length
&& string.Compare(headerValues[i], current, targetValue, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0
&& TryParseNonNegativeInt64FromHeaderValue(current + tokenLength, segment, out seconds))
{
// Token matches target value and seconds were parsed
value = TimeSpan.FromSeconds(seconds);
return true;
}
current = AdvanceCacheDirectiveIndex(current + tokenLength, segment);
// Ensure index was advanced
if (current <= initial)
{
Debug.Assert(false, $"Index '{nameof(current)}' not advanced, this is a bug.");
value = null;
return false;
}
}
}
value = null;
return false;
}
/// <summary>
/// Check if a target directive exists among the set of given cache control directives.
/// </summary>
/// <param name="cacheControlDirectives">
/// The <see cref="StringValues"/> containing the set of cache control directives.
/// </param>
/// <param name="targetDirectives">
/// The target cache control directives to look for.
/// </param>
/// <returns>
/// <see langword="true" /> if <paramref name="targetDirectives"/> is contained in <paramref name="cacheControlDirectives"/>;
/// otherwise, <see langword="false" />.
/// </returns>
public static bool ContainsCacheDirective(StringValues cacheControlDirectives, string targetDirectives)
{
if (StringValues.IsNullOrEmpty(cacheControlDirectives) || string.IsNullOrEmpty(targetDirectives))
{
return false;
}
for (var i = 0; i < cacheControlDirectives.Count; i++)
{
var segment = cacheControlDirectives[i] ?? string.Empty;
// Trim leading white space
var current = HttpRuleParser.GetWhitespaceLength(segment, 0);
while (current < segment.Length)
{
var initial = current;
var tokenLength = HttpRuleParser.GetTokenLength(segment, current);
if (tokenLength == targetDirectives.Length
&& string.Compare(segment, current, targetDirectives, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0)
{
// Token matches target value
return true;
}
current = AdvanceCacheDirectiveIndex(current + tokenLength, segment);
// Ensure index was advanced
if (current <= initial)
{
Debug.Assert(false, $"Index '{nameof(current)}' not advanced, this is a bug.");
return false;
}
}
}
return false;
}
private static bool TryParseNonNegativeInt64FromHeaderValue(int startIndex, string headerValue, out long result)
{
// Trim leading whitespace
startIndex += HttpRuleParser.GetWhitespaceLength(headerValue, startIndex);
// Match and skip '=', it also can't be the last character in the headerValue
if (startIndex >= headerValue.Length - 1 || headerValue[startIndex] != '=')
{
result = 0;
return false;
}
startIndex++;
// Trim trailing whitespace
startIndex += HttpRuleParser.GetWhitespaceLength(headerValue, startIndex);
// Try parse the number
if (TryParseNonNegativeInt64(new StringSegment(headerValue, startIndex, HttpRuleParser.GetNumberLength(headerValue, startIndex, false)), out result))
{
return true;
}
result = 0;
return false;
}
/// <summary>
/// Try to convert a string representation of a positive number to its 64-bit signed integer equivalent.
/// A return value indicates whether the conversion succeeded or failed.
/// </summary>
/// <param name="value">
/// A string containing a number to convert.
/// </param>
/// <param name="result">
/// When this method returns, contains the 64-bit signed integer value equivalent of the number contained
/// in the string, if the conversion succeeded, or zero if the conversion failed. The conversion fails if
/// the string is null or String.Empty, is not of the correct format, is negative, or represents a number
/// greater than Int64.MaxValue. This parameter is passed uninitialized; any value originally supplied in
/// result will be overwritten.
/// </param>
/// <returns><see langword="true" /> if parsing succeeded; otherwise, <see langword="false" />.</returns>
public static bool TryParseNonNegativeInt32(StringSegment value, out int result)
{
if (string.IsNullOrEmpty(value.Buffer) || value.Length == 0)
{
result = 0;
return false;
}
return int.TryParse(value.AsSpan(), NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
}
/// <summary>
/// Try to convert a <see cref="StringSegment"/> representation of a positive number to its 64-bit signed
/// integer equivalent. A return value indicates whether the conversion succeeded or failed.
/// </summary>
/// <param name="value">
/// A <see cref="StringSegment"/> containing a number to convert.
/// </param>
/// <param name="result">
/// When this method returns, contains the 64-bit signed integer value equivalent of the number contained
/// in the string, if the conversion succeeded, or zero if the conversion failed. The conversion fails if
/// the <see cref="StringSegment"/> is null or String.Empty, is not of the correct format, is negative, or
/// represents a number greater than Int64.MaxValue. This parameter is passed uninitialized; any value
/// originally supplied in result will be overwritten.
/// </param>
/// <returns><see langword="true" /> if parsing succeeded; otherwise, <see langword="false" />.</returns>
public static bool TryParseNonNegativeInt64(StringSegment value, out long result)
{
if (string.IsNullOrEmpty(value.Buffer) || value.Length == 0)
{
result = 0;
return false;
}
return long.TryParse(value.AsSpan(), NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
}
// Strict and fast RFC9110 12.4.2 Quality value parser (and without memory allocation)
// See https://tools.ietf.org/html/rfc9110#section-12.4.2
// Check is made to verify if the value is between 0 and 1 (and it returns False if the check fails).
internal static bool TryParseQualityDouble(StringSegment input, int startIndex, out double quality, out int length)
{
quality = 0;
length = 0;
var inputLength = input.Length;
var current = startIndex;
var limit = startIndex + _qualityValueMaxCharCount;
var decPart = 0;
var decPow = 1;
if (current >= inputLength)
{
return false;
}
var ch = input[current];
int intPart;
if (ch >= '0' && ch <= '1') // Only values between 0 and 1 are accepted, according to RFC
{
intPart = ch - '0';
current++;
}
else
{
// The RFC doesn't allow decimal values starting with dot. I.e. value ".123" is invalid. It must be in the
// form "0.123".
return false;
}
if (current < inputLength)
{
ch = input[current];
if (ch >= '0' && ch <= '9')
{
// The RFC accepts only one digit before the dot
return false;
}
if (ch == '.')
{
current++;
while (current < inputLength)
{
ch = input[current];
if (ch >= '0' && ch <= '9')
{
if (current >= limit)
{
return false;
}
decPart = decPart * 10 + ch - '0';
decPow *= 10;
current++;
}
else
{
break;
}
}
}
}
if (decPart != 0)
{
quality = intPart + decPart / (double)decPow;
}
else
{
quality = intPart;
}
if (quality > 1)
{
// reset quality
quality = 0;
return false;
}
length = current - startIndex;
return true;
}
/// <summary>
/// Converts the non-negative 64-bit numeric value to its equivalent string representation.
/// </summary>
/// <param name="value">
/// The number to convert.
/// </param>
/// <returns>
/// The string representation of the value of this instance, consisting of a sequence of digits ranging from 0 to 9 with no leading zeroes.
/// </returns>
public static string FormatNonNegativeInt64(long value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "The value to be formatted must be non-negative.");
}
if (value == 0)
{
return "0";
}
return ((ulong)value).ToString(NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// Converts the 64-bit numeric value to its equivalent string representation.
/// </summary>
/// <param name="value">
/// The number to convert.
/// </param>
/// <returns>
/// The string representation of the value of this instance, consisting of a sequence of digits ranging from 0 to 9 with no leading zeroes.
/// In case of negative numeric value it will have a leading minus sign.
/// </returns>
internal static string FormatInt64(long value)
{
return value switch
{
0 => "0",
1 => "1",
-1 => "-1",
_ => value.ToString(NumberFormatInfo.InvariantInfo)
};
}
/// <summary>
///Attempts to parse the specified <paramref name="input"/> as a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="input">The input value.</param>
/// <param name="result">The parsed value.</param>
/// <returns>
/// <see langword="true" /> if <paramref name="input"/> can be parsed as a date, otherwise <see langword="false" />.
/// </returns>
public static bool TryParseDate(StringSegment input, out DateTimeOffset result)
{
return HttpRuleParser.TryStringToDate(input, out result);
}
/// <summary>
/// Formats the <paramref name="dateTime"/> using the RFC1123 format specifier.
/// </summary>
/// <param name="dateTime">The date to format.</param>
/// <returns>The formatted date.</returns>
public static string FormatDate(DateTimeOffset dateTime)
{
return FormatDate(dateTime, quoted: false);
}
/// <summary>
/// Formats the <paramref name="dateTime"/> using the RFC1123 format specifier and optionally quotes it.
/// </summary>
/// <param name="dateTime">The date to format.</param>
/// <param name="quoted">Determines if the formatted date should be quoted.</param>
/// <returns>The formatted date.</returns>
public static string FormatDate(DateTimeOffset dateTime, bool quoted)
{
if (quoted)
{
return string.Create(31, dateTime, (span, dt) =>
{
span[0] = span[30] = '"';
dt.TryFormat(span.Slice(1), out _, "r", CultureInfo.InvariantCulture);
});
}
return dateTime.ToString("r", CultureInfo.InvariantCulture);
}
/// <summary>
/// Removes quotes from the specified <paramref name="input"/> if quoted.
/// </summary>
/// <param name="input">The input to remove quotes from.</param>
/// <returns>The value without quotes.</returns>
public static StringSegment RemoveQuotes(StringSegment input)
{
if (IsQuoted(input))
{
input = input.Subsegment(1, input.Length - 2);
}
return input;
}
/// <summary>
/// Determines if the specified <paramref name="input"/> is quoted.
/// </summary>
/// <param name="input">The value to inspect.</param>
/// <returns><see langword="true"/> if the value is quoted, otherwise <see langword="false"/>.</returns>
public static bool IsQuoted(StringSegment input)
{
return !StringSegment.IsNullOrEmpty(input) && input.Length >= 2 && input[0] == '"' && input[input.Length - 1] == '"';
}
/// <summary>
/// Given a quoted-string as defined by <see href="https://tools.ietf.org/html/rfc7230#section-3.2.6">the RFC specification</see>,
/// removes quotes and unescapes backslashes and quotes. This assumes that the input is a valid quoted-string.
/// </summary>
/// <param name="input">The quoted-string to be unescaped.</param>
/// <returns>An unescaped version of the quoted-string.</returns>
public static StringSegment UnescapeAsQuotedString(StringSegment input)
{
input = RemoveQuotes(input);
// First pass to calculate the size of the string
var backSlashCount = CountBackslashesForDecodingQuotedString(input);
if (backSlashCount == 0)
{
return input;
}
return string.Create(input.Length - backSlashCount, input, (span, segment) =>
{
var spanIndex = 0;
var spanLength = span.Length;
for (var i = 0; i < segment.Length && (uint)spanIndex < (uint)spanLength; i++)
{
int nextIndex = i + 1;
if ((uint)nextIndex < (uint)segment.Length && segment[i] == '\\')
{
// If there is an backslash character as the last character in the string,
// we will assume that it should be included literally in the unescaped string
// Ex: "hello\\" => "hello\\"
// Also, if a sender adds a quoted pair like '\\''n',
// we will assume it is over escaping and just add a n to the string.
// Ex: "he\\llo" => "hello"
span[spanIndex] = segment[nextIndex];
i++;
}
else
{
span[spanIndex] = segment[i];
}
spanIndex++;
}
});
}
private static int CountBackslashesForDecodingQuotedString(StringSegment input)
{
var numberBackSlashes = 0;
for (var i = 0; i < input.Length; i++)
{
if (i < input.Length - 1 && input[i] == '\\')
{
// If there is an backslash character as the last character in the string,
// we will assume that it should be included literally in the unescaped string
// Ex: "hello\\" => "hello\\"
// Also, if a sender adds a quoted pair like '\\''n',
// we will assume it is over escaping and just add a n to the string.
// Ex: "he\\llo" => "hello"
if (input[i + 1] == '\\')
{
// Only count escaped backslashes once
i++;
}
numberBackSlashes++;
}
}
return numberBackSlashes;
}
/// <summary>
/// Escapes a <see cref="StringSegment"/> as a quoted-string, which is defined by
/// <see href="https://tools.ietf.org/html/rfc7230#section-3.2.6">the RFC specification</see>.
/// </summary>
/// <remarks>
/// This will add a backslash before each backslash and quote and add quotes
/// around the input. Assumes that the input does not have quotes around it,
/// as this method will add them. Throws if the input contains any invalid escape characters,
/// as defined by rfc7230.
/// </remarks>
/// <param name="input">The input to be escaped.</param>
/// <returns>An escaped version of the quoted-string.</returns>
public static StringSegment EscapeAsQuotedString(StringSegment input)
{
// By calling this, we know that the string requires quotes around it to be a valid token.
var backSlashCount = CountAndCheckCharactersNeedingBackslashesWhenEncoding(input);
// 2 for quotes
return string.Create(input.Length + backSlashCount + 2, input, (span, segment) =>
{
// Helps to elide the bounds check for span[0]
span[span.Length - 1] = span[0] = '\"';
var spanIndex = 1;
for (var i = 0; i < segment.Length; i++)
{
if (segment[i] == '\\' || segment[i] == '\"')
{
span[spanIndex++] = '\\';
}
else if ((segment[i] <= 0x1F || segment[i] == 0x7F) && segment[i] != 0x09)
{
// Control characters are not allowed in a quoted-string, which include all characters
// below 0x1F (except for 0x09 (TAB)) and 0x7F.
throw new FormatException($"Invalid control character '{segment[i]}' in input.");
}
span[spanIndex++] = segment[i];
}
});
}
private static int CountAndCheckCharactersNeedingBackslashesWhenEncoding(StringSegment input)
{
var numberOfCharactersNeedingEscaping = 0;
for (var i = 0; i < input.Length; i++)
{
if (input[i] == '\\' || input[i] == '\"')
{
numberOfCharactersNeedingEscaping++;
}
}
return numberOfCharactersNeedingEscaping;
}
internal static void ThrowIfReadOnly(bool isReadOnly)
{
if (isReadOnly)
{
throw new InvalidOperationException("The object cannot be modified because it is read-only.");
}
}
}
| HeaderUtilities |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/Evaluators/BinaryClassifierEvaluator.cs | {
"start": 3393,
"end": 21644
} | public enum ____
{
[EnumValueDisplay(BinaryClassifierEvaluator.Accuracy)]
Accuracy,
[EnumValueDisplay(BinaryClassifierEvaluator.PosPrecName)]
PosPrecName,
[EnumValueDisplay(BinaryClassifierEvaluator.PosRecallName)]
PosRecallName,
[EnumValueDisplay(BinaryClassifierEvaluator.NegPrecName)]
NegPrecName,
[EnumValueDisplay(BinaryClassifierEvaluator.NegRecallName)]
NegRecallName,
[EnumValueDisplay(BinaryClassifierEvaluator.Auc)]
Auc,
[EnumValueDisplay(BinaryClassifierEvaluator.LogLoss)]
LogLoss,
[EnumValueDisplay(BinaryClassifierEvaluator.LogLossReduction)]
LogLossReduction,
[EnumValueDisplay(BinaryClassifierEvaluator.F1)]
F1,
[EnumValueDisplay(BinaryClassifierEvaluator.AuPrc)]
AuPrc,
}
/// <summary>
/// Binary classification evaluator outputs a data view with this name, which contains the p/r data.
/// It contains the columns listed below, and in case data also contains a weight column, it contains
/// also columns for the weighted values.
/// and false positive rate.
/// </summary>
public const string PrCurve = "PrCurve";
// Column names for the p/r data view.
public const string Precision = "Precision";
public const string Recall = "Recall";
public const string FalsePositiveRate = "FPR";
public const string Threshold = "Threshold";
private readonly Single _threshold;
private readonly bool _useRaw;
private readonly int _prCount;
private readonly int _aucCount;
private readonly int _auPrcCount;
public BinaryClassifierEvaluator(IHostEnvironment env, Arguments args)
: base(env, LoadName)
{
var host = Host.NotSensitive();
host.CheckValue(args, nameof(args));
host.CheckUserArg(args.MaxAucExamples >= -1, nameof(args.MaxAucExamples), "Must be at least -1");
host.CheckUserArg(args.NumRocExamples >= 0, nameof(args.NumRocExamples), "Must be non-negative");
host.CheckUserArg(args.NumAuPrcExamples >= 0, nameof(args.NumAuPrcExamples), "Must be non-negative");
_useRaw = args.UseRawScoreThreshold;
_threshold = args.Threshold;
_prCount = args.NumRocExamples;
_aucCount = args.MaxAucExamples;
_auPrcCount = args.NumAuPrcExamples;
}
private protected override void CheckScoreAndLabelTypes(RoleMappedSchema schema)
{
var score = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
var host = Host.SchemaSensitive();
var t = score.Type;
if (t != NumberDataViewType.Single)
throw host.ExceptSchemaMismatch(nameof(schema), "score", score.Name, "Single", t.ToString());
host.Check(schema.Label.HasValue, "Could not find the label column");
t = schema.Label.Value.Type;
if (t != NumberDataViewType.Single && t != NumberDataViewType.Double && t != BooleanDataViewType.Instance && t.GetKeyCount() != 2)
throw host.ExceptSchemaMismatch(nameof(schema), "label", schema.Label.Value.Name, "Single, Double, Boolean, or a Key with cardinality 2", t.ToString());
}
private protected override void CheckCustomColumnTypesCore(RoleMappedSchema schema)
{
var prob = schema.GetColumns(AnnotationUtils.Const.ScoreValueKind.Probability);
var host = Host.SchemaSensitive();
if (prob != null)
{
host.CheckParam(prob.Count == 1, nameof(schema), "Cannot have multiple probability columns");
var probType = prob[0].Type;
if (probType != NumberDataViewType.Single)
throw host.ExceptSchemaMismatch(nameof(schema), "probability", prob[0].Name, "Single", probType.ToString());
}
else if (!_useRaw)
{
throw host.ExceptParam(nameof(schema),
"Cannot compute the predicted label from the probability column because it does not exist");
}
}
// Add also the probability column.
private protected override Func<int, bool> GetActiveColsCore(RoleMappedSchema schema)
{
var pred = base.GetActiveColsCore(schema);
var prob = schema.GetColumns(AnnotationUtils.Const.ScoreValueKind.Probability);
Host.Assert(prob == null || prob.Count == 1);
return i => Utils.Size(prob) > 0 && i == prob[0].Index || pred(i);
}
private protected override Aggregator GetAggregatorCore(RoleMappedSchema schema, string stratName)
{
var classNames = GetClassNames(schema);
return new Aggregator(Host, classNames, schema.Weight != null, _aucCount, _auPrcCount, _threshold, _useRaw, _prCount, stratName);
}
private ReadOnlyMemory<char>[] GetClassNames(RoleMappedSchema schema)
{
// Get the label names if they exist, or use the default names.
var labelNames = default(VBuffer<ReadOnlyMemory<char>>);
var labelCol = schema.Label.Value;
if (labelCol.Type is KeyDataViewType &&
labelCol.Annotations.Schema.GetColumnOrNull(AnnotationUtils.Kinds.KeyValues)?.Type is VectorDataViewType vecType &&
vecType.Size > 0 && vecType.ItemType == TextDataViewType.Instance)
{
labelCol.GetKeyValues(ref labelNames);
}
else
labelNames = new VBuffer<ReadOnlyMemory<char>>(2, new[] { "positive".AsMemory(), "negative".AsMemory() });
ReadOnlyMemory<char>[] names = new ReadOnlyMemory<char>[2];
labelNames.CopyTo(names);
return names;
}
private protected override IRowMapper CreatePerInstanceRowMapper(RoleMappedSchema schema)
{
Contracts.CheckValue(schema, nameof(schema));
Contracts.CheckParam(schema.Label != null, nameof(schema), "Could not find the label column");
var scoreInfo = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
var probInfos = schema.GetColumns(AnnotationUtils.Const.ScoreValueKind.Probability);
var probCol = Utils.Size(probInfos) > 0 ? probInfos[0].Name : null;
return new BinaryPerInstanceEvaluator(Host, schema.Schema, scoreInfo.Name, probCol, schema.Label.Value.Name, _threshold, _useRaw);
}
public override IEnumerable<MetricColumn> GetOverallMetricColumns()
{
yield return new MetricColumn("Accuracy", Accuracy);
yield return new MetricColumn("PosPrec", PosPrecName);
yield return new MetricColumn("PosRecall", PosRecallName);
yield return new MetricColumn("NegPrec", NegPrecName);
yield return new MetricColumn("NegRecall", NegRecallName);
yield return new MetricColumn("AUC", Auc);
yield return new MetricColumn("LogLoss", LogLoss, MetricColumn.Objective.Minimize);
yield return new MetricColumn("LogLossReduction", LogLossReduction);
yield return new MetricColumn("Entropy", Entropy);
yield return new MetricColumn("F1", F1);
yield return new MetricColumn("AUPRC", AuPrc);
}
private protected override void GetAggregatorConsolidationFuncs(Aggregator aggregator, AggregatorDictionaryBase[] dictionaries,
out Action<uint, ReadOnlyMemory<char>, Aggregator> addAgg, out Func<Dictionary<string, IDataView>> consolidate)
{
var stratCol = new List<uint>();
var stratVal = new List<ReadOnlyMemory<char>>();
var isWeighted = new List<bool>();
var auc = new List<Double>();
var accuracy = new List<Double>();
var posPrec = new List<Double>();
var posRecall = new List<Double>();
var negPrec = new List<Double>();
var negRecall = new List<Double>();
var logLoss = new List<Double>();
var logLossRed = new List<Double>();
var entropy = new List<Double>();
var f1 = new List<Double>();
var auprc = new List<Double>();
var counts = new List<Double[]>();
var weights = new List<Double[]>();
var confStratCol = new List<uint>();
var confStratVal = new List<ReadOnlyMemory<char>>();
var scores = new List<Single>();
var precision = new List<Double>();
var recall = new List<Double>();
var fpr = new List<Double>();
var weightedPrecision = new List<Double>();
var weightedRecall = new List<Double>();
var weightedFpr = new List<Double>();
var prStratCol = new List<uint>();
var prStratVal = new List<ReadOnlyMemory<char>>();
bool hasStrats = Utils.Size(dictionaries) > 0;
bool hasWeight = aggregator.Weighted;
addAgg =
(stratColKey, stratColVal, agg) =>
{
Host.Check(agg.Weighted == hasWeight, "All aggregators must either be weighted or unweighted");
Host.Check((agg.AuPrcAggregator == null) == (aggregator.AuPrcAggregator == null),
"All aggregators must either compute AUPRC or not compute AUPRC");
agg.Finish();
stratCol.Add(stratColKey);
stratVal.Add(stratColVal);
isWeighted.Add(false);
auc.Add(agg.UnweightedAuc);
accuracy.Add(agg.UnweightedCounters.Acc);
posPrec.Add(agg.UnweightedCounters.PrecisionPos);
posRecall.Add(agg.UnweightedCounters.RecallPos);
negPrec.Add(agg.UnweightedCounters.PrecisionNeg);
negRecall.Add(agg.UnweightedCounters.RecallNeg);
logLoss.Add(agg.UnweightedCounters.LogLoss);
logLossRed.Add(agg.UnweightedCounters.LogLossReduction);
entropy.Add(agg.UnweightedCounters.Entropy);
f1.Add(agg.UnweightedCounters.F1);
if (agg.AuPrcAggregator != null)
auprc.Add(agg.UnweightedAuPrc);
confStratCol.AddRange(new[] { stratColKey, stratColKey });
confStratVal.AddRange(new[] { stratColVal, stratColVal });
counts.Add(new[] { agg.UnweightedCounters.NumTruePos, agg.UnweightedCounters.NumFalseNeg });
counts.Add(new[] { agg.UnweightedCounters.NumFalsePos, agg.UnweightedCounters.NumTrueNeg });
if (agg.Scores != null)
{
Host.AssertValue(agg.Precision);
Host.AssertValue(agg.Recall);
Host.AssertValue(agg.FalsePositiveRate);
scores.AddRange(agg.Scores);
precision.AddRange(agg.Precision);
recall.AddRange(agg.Recall);
fpr.AddRange(agg.FalsePositiveRate);
if (hasStrats)
{
prStratCol.AddRange(agg.Scores.Select(x => stratColKey));
prStratVal.AddRange(agg.Scores.Select(x => stratColVal));
}
}
if (agg.Weighted)
{
stratCol.Add(stratColKey);
stratVal.Add(stratColVal);
isWeighted.Add(true);
auc.Add(agg.WeightedAuc);
accuracy.Add(agg.WeightedCounters.Acc);
posPrec.Add(agg.WeightedCounters.PrecisionPos);
posRecall.Add(agg.WeightedCounters.RecallPos);
negPrec.Add(agg.WeightedCounters.PrecisionNeg);
negRecall.Add(agg.WeightedCounters.RecallNeg);
logLoss.Add(agg.WeightedCounters.LogLoss);
logLossRed.Add(agg.WeightedCounters.LogLossReduction);
entropy.Add(agg.WeightedCounters.Entropy);
f1.Add(agg.WeightedCounters.F1);
if (agg.AuPrcAggregator != null)
auprc.Add(agg.WeightedAuPrc);
weights.Add(new[] { agg.WeightedCounters.NumTruePos, agg.WeightedCounters.NumFalseNeg });
weights.Add(new[] { agg.WeightedCounters.NumFalsePos, agg.WeightedCounters.NumTrueNeg });
if (agg.Scores != null)
{
Host.AssertValue(agg.WeightedPrecision);
Host.AssertValue(agg.WeightedRecall);
Host.AssertValue(agg.WeightedFalsePositiveRate);
weightedPrecision.AddRange(agg.WeightedPrecision);
weightedRecall.AddRange(agg.WeightedRecall);
weightedFpr.AddRange(agg.WeightedFalsePositiveRate);
}
}
};
consolidate =
() =>
{
var overallDvBldr = new ArrayDataViewBuilder(Host);
if (hasStrats)
{
overallDvBldr.AddColumn(MetricKinds.ColumnNames.StratCol, GetKeyValueGetter(dictionaries), (ulong)dictionaries.Length, stratCol.ToArray());
overallDvBldr.AddColumn(MetricKinds.ColumnNames.StratVal, TextDataViewType.Instance, stratVal.ToArray());
}
if (hasWeight)
overallDvBldr.AddColumn(MetricKinds.ColumnNames.IsWeighted, BooleanDataViewType.Instance, isWeighted.ToArray());
overallDvBldr.AddColumn(Auc, NumberDataViewType.Double, auc.ToArray());
overallDvBldr.AddColumn(Accuracy, NumberDataViewType.Double, accuracy.ToArray());
overallDvBldr.AddColumn(PosPrecName, NumberDataViewType.Double, posPrec.ToArray());
overallDvBldr.AddColumn(PosRecallName, NumberDataViewType.Double, posRecall.ToArray());
overallDvBldr.AddColumn(NegPrecName, NumberDataViewType.Double, negPrec.ToArray());
overallDvBldr.AddColumn(NegRecallName, NumberDataViewType.Double, negRecall.ToArray());
overallDvBldr.AddColumn(LogLoss, NumberDataViewType.Double, logLoss.ToArray());
overallDvBldr.AddColumn(LogLossReduction, NumberDataViewType.Double, logLossRed.ToArray());
overallDvBldr.AddColumn(Entropy, NumberDataViewType.Double, entropy.ToArray());
overallDvBldr.AddColumn(F1, NumberDataViewType.Double, f1.ToArray());
if (aggregator.AuPrcAggregator != null)
overallDvBldr.AddColumn(AuPrc, NumberDataViewType.Double, auprc.ToArray());
var confDvBldr = new ArrayDataViewBuilder(Host);
if (hasStrats)
{
confDvBldr.AddColumn(MetricKinds.ColumnNames.StratCol, GetKeyValueGetter(dictionaries), (ulong)dictionaries.Length, confStratCol.ToArray());
confDvBldr.AddColumn(MetricKinds.ColumnNames.StratVal, TextDataViewType.Instance, confStratVal.ToArray());
}
ValueGetter<VBuffer<ReadOnlyMemory<char>>> getSlotNames =
(ref VBuffer<ReadOnlyMemory<char>> dst) =>
dst = new VBuffer<ReadOnlyMemory<char>>(aggregator.ClassNames.Length, aggregator.ClassNames);
confDvBldr.AddColumn(MetricKinds.ColumnNames.Count, getSlotNames, NumberDataViewType.Double, counts.ToArray());
if (hasWeight)
confDvBldr.AddColumn(MetricKinds.ColumnNames.Weight, getSlotNames, NumberDataViewType.Double, weights.ToArray());
var result = new Dictionary<string, IDataView>();
result.Add(MetricKinds.OverallMetrics, overallDvBldr.GetDataView());
result.Add(MetricKinds.ConfusionMatrix, confDvBldr.GetDataView());
if (scores.Count > 0)
{
var dvBldr = new ArrayDataViewBuilder(Host);
if (hasStrats)
{
dvBldr.AddColumn(MetricKinds.ColumnNames.StratCol, GetKeyValueGetter(dictionaries), (ulong)dictionaries.Length, prStratCol.ToArray());
dvBldr.AddColumn(MetricKinds.ColumnNames.StratVal, TextDataViewType.Instance, prStratVal.ToArray());
}
dvBldr.AddColumn(Threshold, NumberDataViewType.Single, scores.ToArray());
dvBldr.AddColumn(Precision, NumberDataViewType.Double, precision.ToArray());
dvBldr.AddColumn(Recall, NumberDataViewType.Double, recall.ToArray());
dvBldr.AddColumn(FalsePositiveRate, NumberDataViewType.Double, fpr.ToArray());
if (weightedPrecision.Count > 0)
{
dvBldr.AddColumn("Weighted " + Precision, NumberDataViewType.Double, weightedPrecision.ToArray());
dvBldr.AddColumn("Weighted " + Recall, NumberDataViewType.Double, weightedRecall.ToArray());
dvBldr.AddColumn("Weighted " + FalsePositiveRate, NumberDataViewType.Double, weightedFpr.ToArray());
}
result.Add(PrCurve, dvBldr.GetDataView());
}
return result;
};
}
| Metrics |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | {
"start": 70358,
"end": 70443
} | public sealed class ____ : IEnumerable<int>
{
| EnumerableWithConverter |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/FilterFault_Specs.cs | {
"start": 4462,
"end": 4710
} | public class ____ :
CorrelatedBy<Guid>
{
public Initialize()
{
CorrelationId = NewId.NextGuid();
}
public Guid CorrelationId { get; set; }
}
}
}
| Initialize |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/PdbGenerationTestRunner.cs | {
"start": 524,
"end": 4022
} | public class ____
{
static readonly string TestCasePath = Tester.TestCasePath + "/PdbGen";
[Test]
public void HelloWorld()
{
TestGeneratePdb();
}
[Test]
[Ignore("Missing nested local scopes for loops, differences in IL ranges")]
public void ForLoopTests()
{
TestGeneratePdb();
}
[Test]
[Ignore("Differences in IL ranges")]
public void LambdaCapturing()
{
TestGeneratePdb();
}
[Test]
[Ignore("Duplicate sequence points for local function")]
public void Members()
{
TestGeneratePdb();
}
[Test]
public void CustomPdbId()
{
// Generate a PDB for an assembly using a randomly-generated ID, then validate that the PDB uses the specified ID
(string peFileName, string pdbFileName) = CompileTestCase(nameof(CustomPdbId));
var moduleDefinition = new PEFile(peFileName);
var resolver = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Metadata.DetectTargetFrameworkId(), null, PEStreamOptions.PrefetchEntireImage);
var decompiler = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings());
var expectedPdbId = new BlobContentId(Guid.NewGuid(), (uint)Random.Shared.Next());
using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, nameof(CustomPdbId) + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
pdbStream.SetLength(0);
PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true, pdbId: expectedPdbId);
pdbStream.Position = 0;
var metadataReader = MetadataReaderProvider.FromPortablePdbStream(pdbStream).GetMetadataReader();
var generatedPdbId = new BlobContentId(metadataReader.DebugMetadataHeader.Id);
Assert.That(generatedPdbId.Guid, Is.EqualTo(expectedPdbId.Guid));
Assert.That(generatedPdbId.Stamp, Is.EqualTo(expectedPdbId.Stamp));
}
}
[Test]
public void ProgressReporting()
{
// Generate a PDB for an assembly and validate that the progress reporter is called with reasonable values
(string peFileName, string pdbFileName) = CompileTestCase(nameof(ProgressReporting));
var moduleDefinition = new PEFile(peFileName);
var resolver = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Metadata.DetectTargetFrameworkId(), null, PEStreamOptions.PrefetchEntireImage);
var decompiler = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings());
var lastFilesWritten = 0;
var totalFiles = -1;
Action<DecompilationProgress> reportFunc = progress => {
if (totalFiles == -1)
{
// Initialize value on first call
totalFiles = progress.TotalUnits;
}
Assert.That(totalFiles, Is.EqualTo(progress.TotalUnits));
Assert.That(lastFilesWritten + 1, Is.EqualTo(progress.UnitsCompleted));
lastFilesWritten = progress.UnitsCompleted;
};
using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, nameof(ProgressReporting) + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
pdbStream.SetLength(0);
PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true, progress: new TestProgressReporter(reportFunc));
pdbStream.Position = 0;
var metadataReader = MetadataReaderProvider.FromPortablePdbStream(pdbStream).GetMetadataReader();
var generatedPdbId = new BlobContentId(metadataReader.DebugMetadataHeader.Id);
}
Assert.That(lastFilesWritten, Is.EqualTo(totalFiles));
}
| PdbGenerationTestRunner |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/NewTupleExpressionToAggregationExpressionTranslator.cs | {
"start": 974,
"end": 2661
} | internal static class ____
{
public static bool CanTranslate(NewExpression expression)
{
var type = expression.Type;
return type.IsTuple() || type.IsValueTuple();
}
public static TranslatedExpression Translate(TranslationContext context, NewExpression expression)
{
if (CanTranslate(expression))
{
var arguments = expression.Arguments;
var tupleType = expression.Type;
var items = new AstExpression[arguments.Count];
var itemSerializers = new IBsonSerializer[arguments.Count];
for (var i = 0; i < arguments.Count; i++)
{
var valueExpression = arguments[i];
var valueTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, valueExpression);
items[i] = valueTranslation.Ast;
itemSerializers[i] = valueTranslation.Serializer;
}
var ast = AstExpression.ComputedArray(items);
var tupleSerializer = CreateTupleSerializer(tupleType, itemSerializers);
return new TranslatedExpression(expression, ast, tupleSerializer);
}
throw new ExpressionNotSupportedException(expression);
}
private static IBsonSerializer CreateTupleSerializer(Type tupleType, IEnumerable<IBsonSerializer> itemSerializers)
{
return tupleType.IsTuple() ? TupleSerializer.Create(itemSerializers) : ValueTupleSerializer.Create(itemSerializers);
}
}
}
| NewTupleExpressionToAggregationExpressionTranslator |
csharp | xunit__xunit | src/xunit.v1.tests/xunit/SingleTests.cs | {
"start": 2506,
"end": 3704
} | public class ____
{
[Fact]
public void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single<object>(null));
}
[Fact]
public void EmptyCollectionThrows()
{
object[] collection = new object[0];
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 0 elements instead of 1.", ex.Message);
}
[Fact]
public void MultiItemCollectionThrows()
{
string[] collection = new[] { "Hello", "World!" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 2 elements instead of 1.", ex.Message);
}
[Fact]
public void SingleItemCollectionDoesNotThrow()
{
string[] collection = new[] { "Hello" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.Null(ex);
}
[Fact]
public void SingleItemCollectionReturnsTheItem()
{
string[] collection = new[] { "Hello" };
string result = Assert.Single(collection);
Assert.Equal("Hello", result);
}
}
| GenericEnumerable |
csharp | moq__moq4 | src/Moq.Tests/Regressions/IssueReportsFixture.cs | {
"start": 165855,
"end": 166908
} | public class ____
{
[Fact]
public void SubscribingWorks()
{
var target = new Mock<Foo> { CallBase = true };
target.As<IBar>();
var bar = (IBar)target.Object;
var raised = false;
bar.SomeEvent += (sender, e) => raised = true;
target.As<IBar>().Raise(b => b.SomeEvent += null, EventArgs.Empty);
Assert.True(raised);
}
[Fact]
public void UnsubscribingWorks()
{
var target = new Mock<Foo> { CallBase = true };
target.As<IBar>();
var bar = (IBar)target.Object;
var raised = false;
EventHandler handler = (sender, e) => raised = true;
bar.SomeEvent += handler;
bar.SomeEvent -= handler;
target.As<IBar>().Raise(b => b.SomeEvent += null, EventArgs.Empty);
Assert.False(raised);
}
| _325 |
csharp | Cysharp__UniTask | src/UniTask/Assets/Scenes/SandboxMain.cs | {
"start": 870,
"end": 907
} | public enum ____
{
A, B, C
}
| MyEnum |
csharp | Cysharp__UniTask | src/UniTask/Assets/Scenes/SandboxMain.cs | {
"start": 2538,
"end": 3213
} | public class ____ : MonoBehaviour
{
public Camera mycamera;
public Button okButton;
public Button cancelButton;
CancellationTokenSource cts;
public AsyncReactiveProperty<int> RP1;
UniTaskCompletionSource ucs;
async UniTask<int> FooAsync()
{
// use F10, will crash.
var loop = int.Parse("9");
await UniTask.DelayFrame(loop);
Debug.Log("OK");
await UniTask.DelayFrame(loop);
Debug.Log("Again");
// var foo = InstantiateAsync<SandboxMain>(this).ToUniTask();
// var tako = await foo;
//UnityAction action;
return 10;
}
| SandboxMain |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Validation/Models/JwtRequestValidationResult.cs | {
"start": 289,
"end": 576
} | public class ____ : ValidationResult
{
/// <summary>
/// The key/value pairs from the JWT payload of a successfully validated
/// request, or null if a validation error occurred.
/// </summary>
public IEnumerable<Claim>? Payload { get; set; }
}
| JwtRequestValidationResult |
csharp | dotnet__extensions | test/Libraries/Microsoft.Extensions.AI.Tests/Functions/AIFunctionFactoryTest.cs | {
"start": 47097,
"end": 47145
} | private sealed class ____ : B;
public readonly | C |
csharp | getsentry__sentry-dotnet | src/Sentry/Internal/Http/CachingTransport.cs | {
"start": 283,
"end": 578
} | class ____ a <see cref="CachingTransport.DisposeAsync"/>
/// method, it doesn't implement <see cref="IAsyncDisposable"/> as this caused
/// a dependency issue with Log4Net in some situations.
/// </para>
/// <para>See https://github.com/getsentry/sentry-dotnet/issues/3178</para>
/// </remarks>
| has |
csharp | dotnet__aspnetcore | src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Expectation.cs | {
"start": 208,
"end": 282
} | public enum ____
{
Fail,
NonStrict,
OkOrFail,
Ok
}
| Expectation |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Tests/Types/Composite/LookupTests.cs | {
"start": 7074,
"end": 7122
} | public record ____(int Id, string Title);
| Book1 |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/src/core/Index/Common/CheckpointSettings.cs | {
"start": 169,
"end": 786
} | public enum ____
{
/// <summary>
/// Take separate snapshot of in-memory portion of log (default)
/// </summary>
Snapshot,
/// <summary>
/// Flush current log (move read-only to tail)
/// (enables incremental checkpointing, but log grows faster)
/// </summary>
FoldOver,
/// <summary>
/// Yield a stream of key-value records in version (v), that can be used to rebuild the store
/// </summary>
StreamingSnapshot,
}
/// <summary>
/// Checkpoint-related settings
/// </summary>
| CheckpointType |
csharp | duplicati__duplicati | Duplicati/Library/Common/IO/SystemIOLinux.cs | {
"start": 1484,
"end": 1611
} | public struct ____ : ISystemIO
{
/// <summary>
/// PInvoke methods
/// </summary>
| SystemIOLinux |
csharp | dotnet__efcore | src/EFCore.Relational/Metadata/RuntimeEntityTypeMappingFragment.cs | {
"start": 469,
"end": 3122
} | public class ____ : AnnotatableBase, IEntityTypeMappingFragment
{
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeEntityTypeMappingFragment" /> class.
/// </summary>
/// <param name="entityType">The entity type for which the fragment is defined.</param>
/// <param name="storeObject">The store object for which the configuration is applied.</param>
/// <param name="isTableExcludedFromMigrations">
/// A value indicating whether the associated table is ignored by Migrations.
/// </param>
public RuntimeEntityTypeMappingFragment(
RuntimeEntityType entityType,
in StoreObjectIdentifier storeObject,
bool? isTableExcludedFromMigrations)
{
EntityType = entityType;
StoreObject = storeObject;
if (isTableExcludedFromMigrations != null)
{
SetAnnotation(RelationalAnnotationNames.IsTableExcludedFromMigrations, isTableExcludedFromMigrations.Value);
}
}
/// <summary>
/// Gets the entity type for which the fragment is defined.
/// </summary>
public virtual RuntimeEntityType EntityType { get; }
/// <inheritdoc />
public virtual StoreObjectIdentifier StoreObject { get; }
/// <inheritdoc />
public virtual bool? IsTableExcludedFromMigrations
=> (bool?)this[RelationalAnnotationNames.IsTableExcludedFromMigrations];
/// <inheritdoc />
public override string ToString()
=> ((IEntityTypeMappingFragment)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public virtual DebugView DebugView
=> new(
() => ((IEntityTypeMappingFragment)this).ToDebugString(),
() => ((IEntityTypeMappingFragment)this).ToDebugString(MetadataDebugStringOptions.LongDefault));
/// <inheritdoc />
IEntityType IEntityTypeMappingFragment.EntityType
{
[DebuggerStepThrough]
get => EntityType;
}
/// <inheritdoc />
IReadOnlyEntityType IReadOnlyEntityTypeMappingFragment.EntityType
{
[DebuggerStepThrough]
get => EntityType;
}
}
| RuntimeEntityTypeMappingFragment |
csharp | open-telemetry__opentelemetry-dotnet | test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/Implementation/ExportClient/OtlpHttpTraceExportClientTests.cs | {
"start": 553,
"end": 8557
} | public sealed class ____ : IDisposable
{
private static readonly SdkLimitOptions DefaultSdkLimitOptions = new();
private readonly ActivityListener activityListener;
static OtlpHttpTraceExportClientTests()
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
}
public OtlpHttpTraceExportClientTests()
{
this.activityListener = new ActivityListener
{
ShouldListenTo = _ => true,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllDataAndRecorded,
};
ActivitySource.AddActivityListener(this.activityListener);
}
public void Dispose()
{
this.activityListener.Dispose();
}
[Fact]
public void NewOtlpHttpTraceExportClient_OtlpExporterOptions_ExporterHasCorrectProperties()
{
var header1 = new { Name = "hdr1", Value = "val1" };
var header2 = new { Name = "hdr2", Value = "val2" };
var options = new OtlpExporterOptions
{
Headers = $"{header1.Name}={header1.Value}, {header2.Name} = {header2.Value}",
};
var client = new OtlpHttpExportClient(options, options.HttpClientFactory(), "/v1/traces");
Assert.NotNull(client.HttpClient);
Assert.Equal(2 + OtlpExporterOptions.StandardHeaders.Length, client.Headers.Count);
Assert.Contains(client.Headers, kvp => kvp.Key == header1.Name && kvp.Value == header1.Value);
Assert.Contains(client.Headers, kvp => kvp.Key == header2.Name && kvp.Value == header2.Value);
for (int i = 0; i < OtlpExporterOptions.StandardHeaders.Length; i++)
{
Assert.Contains(client.Headers, entry => entry.Key == OtlpExporterOptions.StandardHeaders[i].Key && entry.Value == OtlpExporterOptions.StandardHeaders[i].Value);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SendExportRequest_ExportTraceServiceRequest_SendsCorrectHttpRequest(bool includeServiceNameInResource)
{
// Arrange
var evenTags = new[] { new KeyValuePair<string, object?>("k0", "v0") };
var oddTags = new[] { new KeyValuePair<string, object?>("k1", "v1") };
var sources = new[]
{
new ActivitySource("even", "2.4.6"),
new ActivitySource("odd", "1.3.5"),
};
var header1 = new { Name = "hdr1", Value = "val1" };
var header2 = new { Name = "hdr2", Value = "val2" };
var options = new OtlpExporterOptions
{
Endpoint = new Uri("http://localhost:4317"),
Headers = $"{header1.Name}={header1.Value}, {header2.Name} = {header2.Value}",
};
#pragma warning disable CA2000 // Dispose objects before losing scope
var testHttpHandler = new TestHttpMessageHandler();
#pragma warning restore CA2000 // Dispose objects before losing scope
using var httpClient = new HttpClient(testHttpHandler);
var exportClient = new OtlpHttpExportClient(options, httpClient, string.Empty);
var resourceBuilder = ResourceBuilder.CreateEmpty();
if (includeServiceNameInResource)
{
resourceBuilder.AddAttributes(
new List<KeyValuePair<string, object>>
{
new(ResourceSemanticConventions.AttributeServiceName, "service_name"),
new(ResourceSemanticConventions.AttributeServiceNamespace, "ns_1"),
});
}
var builder = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(resourceBuilder)
.AddSource(sources[0].Name)
.AddSource(sources[1].Name);
using var openTelemetrySdk = builder.Build();
var exportedItems = new List<Activity>();
#pragma warning disable CA2000 // Dispose objects before losing scope
var processor = new BatchActivityExportProcessor(new InMemoryExporter<Activity>(exportedItems));
#pragma warning restore CA2000 // Dispose objects before losing scope
const int numOfSpans = 10;
bool isEven;
for (var i = 0; i < numOfSpans; i++)
{
isEven = i % 2 == 0;
var source = sources[i % 2];
var activityKind = isEven ? ActivityKind.Client : ActivityKind.Server;
var activityTags = isEven ? evenTags : oddTags;
using Activity? activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags);
Assert.NotNull(activity);
processor.OnEnd(activity);
}
processor.Shutdown();
var batch = new Batch<Activity>([.. exportedItems], exportedItems.Count);
RunTest(batch);
void RunTest(Batch<Activity> batch)
{
var deadlineUtc = DateTime.UtcNow.AddMilliseconds(httpClient.Timeout.TotalMilliseconds);
var request = new OtlpCollector.ExportTraceServiceRequest();
var (buffer, contentLength) = CreateTraceExportRequest(DefaultSdkLimitOptions, batch, resourceBuilder.Build());
// Act
var result = exportClient.SendExportRequest(buffer, contentLength, deadlineUtc);
var httpRequest = testHttpHandler.HttpRequestMessage;
// Assert
Assert.True(result.Success);
Assert.NotNull(httpRequest);
Assert.Equal(HttpMethod.Post, httpRequest.Method);
Assert.NotNull(httpRequest.RequestUri);
Assert.Equal("http://localhost:4317/", httpRequest.RequestUri.AbsoluteUri);
Assert.Equal(OtlpExporterOptions.StandardHeaders.Length + 2, httpRequest.Headers.Count());
Assert.Contains(httpRequest.Headers, h => h.Key == header1.Name && h.Value.First() == header1.Value);
Assert.Contains(httpRequest.Headers, h => h.Key == header2.Name && h.Value.First() == header2.Value);
for (int i = 0; i < OtlpExporterOptions.StandardHeaders.Length; i++)
{
Assert.Contains(httpRequest.Headers, entry => entry.Key == OtlpExporterOptions.StandardHeaders[i].Key && entry.Value.First() == OtlpExporterOptions.StandardHeaders[i].Value);
}
Assert.NotNull(testHttpHandler.HttpRequestContent);
// TODO: Revisit once the HttpClient part is overridden.
// Assert.IsType<ProtobufOtlpHttpExportClient.ExportRequestContent>(httpRequest.Content);
Assert.NotNull(httpRequest.Content);
Assert.Contains(httpRequest.Content.Headers, h => h.Key == "Content-Type" && h.Value.First() == OtlpHttpExportClient.MediaHeaderValue.ToString());
var exportTraceRequest = OtlpCollector.ExportTraceServiceRequest.Parser.ParseFrom(testHttpHandler.HttpRequestContent);
Assert.NotNull(exportTraceRequest);
Assert.Single(exportTraceRequest.ResourceSpans);
var resourceSpan = exportTraceRequest.ResourceSpans.First();
if (includeServiceNameInResource)
{
Assert.Contains(resourceSpan.Resource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceName && kvp.Value.StringValue == "service_name");
Assert.Contains(resourceSpan.Resource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceNamespace && kvp.Value.StringValue == "ns_1");
}
else
{
Assert.DoesNotContain(resourceSpan.Resource.Attributes, kvp => kvp.Key == ResourceSemanticConventions.AttributeServiceName);
}
}
}
private static (byte[] Buffer, int ContentLength) CreateTraceExportRequest(SdkLimitOptions sdkOptions, in Batch<Activity> batch, Resource resource)
{
var buffer = new byte[4096];
var writePosition = ProtobufOtlpTraceSerializer.WriteTraceData(ref buffer, 0, sdkOptions, resource, batch);
return (buffer, writePosition);
}
}
| OtlpHttpTraceExportClientTests |
csharp | moq__moq4 | src/Moq/ExpressionReconstructor.cs | {
"start": 508,
"end": 1418
} | abstract class ____
{
static ExpressionReconstructor instance = new ActionObserver();
public static ExpressionReconstructor Instance
{
get => instance;
set => instance = value ?? throw new ArgumentNullException(nameof(value));
}
protected ExpressionReconstructor()
{
}
/// <summary>
/// Reconstructs a <see cref="LambdaExpression"/> from the given <see cref="Action{T}"/> delegate.
/// </summary>
/// <param name="action">The <see cref="Action"/> delegate for which to reconstruct a LINQ expression tree.</param>
/// <param name="ctorArgs">Arguments to pass to a parameterized constructor of <typeparamref name="T"/>. (Optional.)</param>
public abstract Expression<Action<T>> ReconstructExpression<T>(Action<T> action, object[] ctorArgs = null);
}
}
| ExpressionReconstructor |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Media/BezierSegment .cs | {
"start": 46,
"end": 2064
} | public sealed class ____ : PathSegment
{
/// <summary>
/// Defines the <see cref="Point1"/> property.
/// </summary>
public static readonly StyledProperty<Point> Point1Property
= AvaloniaProperty.Register<BezierSegment, Point>(nameof(Point1));
/// <summary>
/// Defines the <see cref="Point2"/> property.
/// </summary>
public static readonly StyledProperty<Point> Point2Property
= AvaloniaProperty.Register<BezierSegment, Point>(nameof(Point2));
/// <summary>
/// Defines the <see cref="Point3"/> property.
/// </summary>
public static readonly StyledProperty<Point> Point3Property
= AvaloniaProperty.Register<BezierSegment, Point>(nameof(Point3));
/// <summary>
/// Gets or sets the point1.
/// </summary>
/// <value>
/// The point1.
/// </value>
public Point Point1
{
get { return GetValue(Point1Property); }
set { SetValue(Point1Property, value); }
}
/// <summary>
/// Gets or sets the point2.
/// </summary>
/// <value>
/// The point2.
/// </value>
public Point Point2
{
get { return GetValue(Point2Property); }
set { SetValue(Point2Property, value); }
}
/// <summary>
/// Gets or sets the point3.
/// </summary>
/// <value>
/// The point3.
/// </value>
public Point Point3
{
get { return GetValue(Point3Property); }
set { SetValue(Point3Property, value); }
}
internal override void ApplyTo(StreamGeometryContext ctx)
{
ctx.CubicBezierTo(Point1, Point2, Point3, IsStroked);
}
public override string ToString()
=> FormattableString.Invariant($"C {Point1} {Point2} {Point3}");
}
}
| BezierSegment |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.TagProvider.cs | {
"start": 7971,
"end": 8044
} | class ____ : BaseClass, IFoo
{
}
| MyClass |
csharp | cake-build__cake | src/Cake.Frosting.Tests/Fixtures/CakeHostFixture.cs | {
"start": 395,
"end": 2103
} | public sealed class ____
{
public CakeHost Host { get; set; }
public FakeEnvironment Environment { get; set; }
public FakeFileSystem FileSystem { get; set; }
public FakeConsole Console { get; set; }
public ICakeLog Log { get; set; }
public IExecutionStrategy Strategy { get; set; }
public IToolInstaller Installer { get; set; }
public CakeHostFixture()
{
Host = new CakeHost();
Environment = FakeEnvironment.CreateUnixEnvironment();
Console = new FakeConsole();
Log = Substitute.For<ICakeLog>();
Installer = Substitute.For<IToolInstaller>();
FileSystem = new FakeFileSystem(Environment);
FileSystem.CreateDirectory("/Working");
}
public void RegisterTask<T>()
where T : class, IFrostingTask
{
Host.ConfigureServices(services => services.AddSingleton<IFrostingTask, T>());
}
public int Run(params string[] args)
{
Host.ConfigureServices(services => services.AddSingleton<IFileSystem>(FileSystem));
Host.ConfigureServices(services => services.AddSingleton<ICakeEnvironment>(Environment));
Host.ConfigureServices(services => services.AddSingleton<IConsole>(Console));
Host.ConfigureServices(services => services.AddSingleton(Log));
Host.ConfigureServices(services => services.AddSingleton(Installer));
if (Strategy != null)
{
Host.ConfigureServices(services => services.AddSingleton(Strategy));
}
return Host.Run(args);
}
}
}
| CakeHostFixture |
csharp | scriban__scriban | src/Scriban/Syntax/Statements/ScriptStatement.cs | {
"start": 255,
"end": 407
} | class ____ all statements.
/// </summary>
/// <seealso cref="ScriptNode" />
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
abstract | for |
csharp | dotnet__extensions | src/Generators/Microsoft.Gen.Logging/Parsing/AttributeProcessors.cs | {
"start": 212,
"end": 6075
} | internal static class ____
{
private const string MessageProperty = "Message";
private const string EventNameProperty = "EventName";
private const string EventIdProperty = "EventId";
private const string LevelProperty = "Level";
private const string SkipEnabledCheckProperty = "SkipEnabledCheck";
private const string SkipNullProperties = "SkipNullProperties";
private const string OmitReferenceName = "OmitReferenceName";
private const string Transitive = "Transitive";
private const int LogLevelError = 4;
private const int LogLevelCritical = 5;
public static (int? eventId, int? level, string message, string? eventName, bool skipEnabledCheck)
ExtractLoggerMessageAttributeValues(AttributeData attr, SymbolHolder symbols)
{
// Five constructor arg shapes:
//
// ()
// (int eventId, LogLevel level, string message)
// (LogLevel level, string message)
// (LogLevel level)
// (string message)
int? eventId = null;
int? level = null;
string? eventName = null;
string message = string.Empty;
bool skipEnabledCheck = false;
bool useDefaultForSkipEnabledCheck = true;
foreach (var a in attr.ConstructorArguments)
{
if (SymbolEqualityComparer.Default.Equals(a.Type, symbols.LogLevelSymbol))
{
var v = a.Value;
if (v is int l)
{
level = l;
}
}
else if (a.Type?.SpecialType == SpecialType.System_Int32)
{
var v = a.Value;
if (v is int l)
{
eventId = l;
}
}
else
{
message = a.Value as string ?? string.Empty;
}
}
foreach (var a in attr.NamedArguments)
{
var v = a.Value.Value;
if (v != null)
{
switch (a.Key)
{
case MessageProperty:
if (v is string m)
{
message = m;
}
break;
case EventNameProperty:
if (v is string e)
{
eventName = e;
}
break;
case LevelProperty:
if (v is int l)
{
level = l;
}
break;
case EventIdProperty:
if (v is int id)
{
eventId = id;
}
break;
case SkipEnabledCheckProperty:
if (v is bool b)
{
skipEnabledCheck = b;
useDefaultForSkipEnabledCheck = false;
}
break;
}
}
}
if (level != null)
{
if (useDefaultForSkipEnabledCheck && (level == LogLevelError || level == LogLevelCritical))
{
// unless explicitly set by the user, by default we disable the Enabled check when the log level is Error or Critical
skipEnabledCheck = true;
}
}
return (eventId, level, message, eventName, skipEnabledCheck);
}
public static (bool skipNullProperties, bool omitReferenceName, bool transitive) ExtractLogPropertiesAttributeValues(AttributeData attr)
{
bool skipNullProperties = false;
bool omitReferenceName = false;
bool transitive = false;
foreach (var a in attr.NamedArguments)
{
var v = a.Value.Value;
if (v != null)
{
if (a.Key == SkipNullProperties)
{
if (v is bool b)
{
skipNullProperties = b;
}
}
else if (a.Key == OmitReferenceName)
{
if (v is bool b)
{
omitReferenceName = b;
}
}
else if (a.Key == Transitive)
{
if (v is bool b)
{
transitive = b;
}
}
}
}
return (skipNullProperties, omitReferenceName, transitive);
}
public static (bool omitReferenceName, ITypeSymbol providerType, string providerMethodName) ExtractTagProviderAttributeValues(AttributeData attr)
{
bool omitReferenceName = false;
ITypeSymbol? providerType = null;
string? providerMethodName = null;
foreach (var a in attr.NamedArguments)
{
var v = a.Value.Value;
if (v != null)
{
if (a.Key == OmitReferenceName)
{
if (v is bool b)
{
omitReferenceName = b;
}
}
}
}
providerType = attr.ConstructorArguments[0].Value as ITypeSymbol;
providerMethodName = attr.ConstructorArguments[1].Value as string;
return (omitReferenceName, providerType!, providerMethodName!);
}
public static string ExtractTagNameAttributeValues(AttributeData attr)
=> attr.ConstructorArguments[0].Value as string ?? string.Empty;
}
| AttributeProcessors |
csharp | protobuf-net__protobuf-net | src/protobuf-net.Core/Serializers/RepeatedSerializer.cs | {
"start": 503,
"end": 5517
} | partial class ____
{
/// <summary>Create a serializer that indicates that a scenario is not supported</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
[Obsolete("Since this isn't supported, you probably shouldn't be doing it...", false)]
public static RepeatedSerializer<TCollection, T> CreateNestedDataNotSupported<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
{
ThrowHelper.ThrowNestedDataNotSupported(typeof(TCollection));
return default;
}
/// <summary>Create a serializer that indicates that a scenario is not supported</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
[Obsolete("Since this isn't supported, you probably shouldn't be doing it...", false)]
public static RepeatedSerializer<TCollection, T> CreateNotSupported<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
{
ThrowHelper.ThrowNotSupportedException($"Repeated data of type {typeof(TCollection)} is not supported");
return default;
}
/// <summary>Create a serializer that operates on lists</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<List<T>, T> CreateList<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
=> SerializerCache<ListSerializer<T>>.InstanceField;
/// <summary>Create a serializer that operates on lists</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TList, T> CreateList<TList, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TList : List<T>
=> SerializerCache<ListSerializer<TList, T>>.InstanceField;
/// <summary>Create a serializer that operates on most common collections</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TCollection, T> CreateEnumerable<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TCollection : class, IEnumerable<T>
=> SerializerCache<EnumerableSerializer<TCollection, TCollection, T>>.InstanceField;
/// <summary>Create a serializer that operates on most common collections</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TCollection, T> CreateEnumerable<TCollection, TCreate, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TCollection : class, IEnumerable<T>
where TCreate : TCollection
=> SerializerCache<EnumerableSerializer<TCollection, TCreate, T>>.InstanceField;
/// <summary>Create a serializer that operates on lists</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<T[], T> CreateVector<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
=> SerializerCache<VectorSerializer<T>>.InstanceField;
/// <summary>Create a serializer that operates on lists</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TCollection, T> CreateQueue<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TCollection : Queue<T>
=> SerializerCache<QueueSerializer<TCollection, T>>.InstanceField;
/// <summary>Create a serializer that operates on lists</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TCollection, T> CreateStack<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TCollection : Stack<T>
=> SerializerCache<StackSerializer<TCollection, T>>.InstanceField;
/// <summary>Create a serializer that operates on sets</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<TCollection, T> CreateSet<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
where TCollection : ISet<T>
=> SerializerCache<SetSerializer<TCollection, T>>.InstanceField;
#if NET6_0_OR_GREATER
/// <summary>Create a serializer that operates on sets</summary>
[MethodImpl(ProtoReader.HotPath)]
public static RepeatedSerializer<IReadOnlySet<T>, T> CreateReadOnySet<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] T>()
=> SerializerCache<ReadOnlySetSerializer<T>>.InstanceField;
#endif
/// <summary>Reverses a range of values</summary>
[MethodImpl(ProtoReader.HotPath)] // note: not "in" because ArraySegment<T> isn't "readonly" on all TFMs
internal static void ReverseInPlace<T>(this ref ArraySegment<T> values) => Array.Reverse(values.Array, values.Offset, values.Count);
[MethodImpl(ProtoReader.HotPath)]
internal static ref T Singleton<T>(this ref ArraySegment<T> values) => ref values.Array[values.Offset];
}
/// <summary>
/// Base | RepeatedSerializer |
csharp | dotnet__maui | src/Essentials/src/Clipboard/Clipboard.shared.cs | {
"start": 214,
"end": 1296
} | public interface ____
{
/// <summary>
/// Gets a value indicating whether there is any text on the clipboard.
/// </summary>
bool HasText { get; }
/// <summary>
/// Sets the contents of the clipboard to be the specified text.
/// </summary>
/// <param name="text">The text to put on the clipboard.</param>
/// <returns>A <see cref="Task"/> object with the current status of the asynchronous operation.</returns>
/// <remarks>This method returns immediately and does not guarentee that the text is on the clipboard by the time this method returns.</remarks>
Task SetTextAsync(string? text);
/// <summary>
/// Returns any text that is on the clipboard.
/// </summary>
/// <returns>Text content that is on the clipboard, or <see langword="null"/> if there is none.</returns>
Task<string?> GetTextAsync();
/// <summary>
/// Occurs when the clipboard content changes.
/// </summary>
event EventHandler<EventArgs> ClipboardContentChanged;
}
/// <summary>
/// Provides a way to work with text on the device clipboard.
/// </summary>
| IClipboard |
csharp | dotnet__efcore | src/EFCore/Metadata/IReadOnlyProperty.cs | {
"start": 572,
"end": 18661
} | public interface ____ : IReadOnlyPropertyBase
{
/// <summary>
/// Gets the entity type that this property belongs to.
/// </summary>
[Obsolete("Use DeclaringType and cast to IReadOnlyEntityType or IReadOnlyComplexType")]
IReadOnlyEntityType DeclaringEntityType
=> (IReadOnlyEntityType)DeclaringType;
/// <summary>
/// Gets a value indicating whether this property can contain <see langword="null" />.
/// </summary>
bool IsNullable { get; }
/// <summary>
/// Gets a value indicating when a value for this property will be generated by the database. Even when the
/// property is set to be generated by the database, EF may still attempt to save a specific value (rather than
/// having one generated by the database) when the entity is added and a value is assigned, or the property is
/// marked as modified for an existing entity. See <see cref="GetBeforeSaveBehavior" />
/// and <see cref="GetAfterSaveBehavior" /> for more information and examples.
/// </summary>
ValueGenerated ValueGenerated { get; }
/// <summary>
/// Gets a value indicating whether this property is used as a concurrency token. When a property is configured
/// as a concurrency token the value in the database will be checked when an instance of this entity type
/// is updated or deleted during <see cref="DbContext.SaveChanges()" /> to ensure it has not changed since
/// the instance was retrieved from the database. If it has changed, an exception will be thrown and the
/// changes will not be applied to the database.
/// </summary>
bool IsConcurrencyToken { get; }
/// <summary>
/// Returns the <see cref="CoreTypeMapping" /> for the given property from a finalized model.
/// </summary>
/// <returns>The type mapping.</returns>
CoreTypeMapping GetTypeMapping()
{
var mapping = FindTypeMapping();
if (mapping == null)
{
throw new InvalidOperationException(CoreStrings.ModelNotFinalized(nameof(GetTypeMapping)));
}
return mapping;
}
/// <summary>
/// Returns the type mapping for this property.
/// </summary>
/// <returns>The type mapping, or <see langword="null" /> if none was found.</returns>
CoreTypeMapping? FindTypeMapping();
/// <summary>
/// Gets the maximum length of data that is allowed in this property. For example, if the property is a <see cref="string" />
/// then this is the maximum number of characters.
/// </summary>
/// <returns>
/// The maximum length, <c>-1</c> if the property has no maximum length, or <see langword="null" /> if the maximum length hasn't been
/// set.
/// </returns>
int? GetMaxLength();
/// <summary>
/// Gets the precision of data that is allowed in this property.
/// For example, if the property is a <see cref="decimal" /> then this is the maximum number of digits.
/// </summary>
/// <returns>The precision, or <see langword="null" /> if none is defined.</returns>
int? GetPrecision();
/// <summary>
/// Gets the scale of data that is allowed in this property.
/// For example, if the property is a <see cref="decimal" /> then this is the maximum number of decimal places.
/// </summary>
/// <returns>The scale, or <see langword="null" /> if none is defined.</returns>
int? GetScale();
/// <summary>
/// Gets a value indicating whether the property can persist Unicode characters.
/// </summary>
/// <returns>The Unicode setting, or <see langword="null" /> if none is defined.</returns>
bool? IsUnicode();
/// <summary>
/// Gets a value indicating whether this property can be modified before the entity is
/// saved to the database.
/// </summary>
/// <remarks>
/// <para>
/// If <see cref="PropertySaveBehavior.Throw" />, then an exception
/// will be thrown if a value is assigned to this property when it is in
/// the <see cref="EntityState.Added" /> state.
/// </para>
/// <para>
/// If <see cref="PropertySaveBehavior.Ignore" />, then any value
/// set will be ignored when it is in the <see cref="EntityState.Added" /> state.
/// </para>
/// </remarks>
/// <returns>The before save behavior for this property.</returns>
PropertySaveBehavior GetBeforeSaveBehavior();
/// <summary>
/// Gets a value indicating whether this property can be modified after the entity is
/// saved to the database.
/// </summary>
/// <remarks>
/// <para>
/// If <see cref="PropertySaveBehavior.Throw" />, then an exception
/// will be thrown if a new value is assigned to this property after the entity exists in the database.
/// </para>
/// <para>
/// If <see cref="PropertySaveBehavior.Ignore" />, then any modification to the
/// property value of an entity that already exists in the database will be ignored.
/// </para>
/// </remarks>
/// <returns>The after save behavior for this property.</returns>
PropertySaveBehavior GetAfterSaveBehavior();
/// <summary>
/// Gets the factory that has been set to generate values for this property, if any.
/// </summary>
/// <returns>The factory, or <see langword="null" /> if no factory has been set.</returns>
Func<IProperty, ITypeBase, ValueGenerator>? GetValueGeneratorFactory();
/// <summary>
/// Gets the custom <see cref="ValueConverter" /> set for this property.
/// </summary>
/// <returns>The converter, or <see langword="null" /> if none has been set.</returns>
ValueConverter? GetValueConverter();
/// <summary>
/// Gets the type that the property value will be converted to before being sent to the database provider.
/// </summary>
/// <returns>The provider type, or <see langword="null" /> if none has been set.</returns>
Type? GetProviderClrType();
/// <summary>
/// Gets the <see cref="ValueComparer" /> for this property, or <see langword="null" /> if none is set.
/// </summary>
/// <returns>The comparer, or <see langword="null" /> if none has been set.</returns>
ValueComparer? GetValueComparer();
/// <summary>
/// Gets the <see cref="ValueComparer" /> to use with keys for this property, or <see langword="null" /> if none is set.
/// </summary>
/// <returns>The comparer, or <see langword="null" /> if none has been set.</returns>
ValueComparer? GetKeyValueComparer();
/// <summary>
/// Gets the <see cref="ValueComparer" /> to use for the provider values for this property.
/// </summary>
/// <returns>The comparer, or <see langword="null" /> if none has been set.</returns>
ValueComparer? GetProviderValueComparer();
/// <summary>
/// Gets the <see cref="JsonValueReaderWriter" /> for this property, or <see langword="null" /> if none is set.
/// </summary>
/// <returns>The reader/writer, or <see langword="null" /> if none has been set.</returns>
JsonValueReaderWriter? GetJsonValueReaderWriter();
/// <summary>
/// Gets the configuration for elements of the primitive collection represented by this property.
/// </summary>
/// <returns>The configuration for the elements.</returns>
IReadOnlyElementType? GetElementType();
/// <summary>
/// A property is a primitive collection if it has an element type that matches the element type of the CLR type.
/// </summary>
/// <returns><see langword="true" /> if the property represents a primitive collection.</returns>
bool IsPrimitiveCollection { get; }
/// <summary>
/// Finds the first principal property that the given property is constrained by
/// if the given property is part of a foreign key.
/// </summary>
/// <returns>The first associated principal property, or <see langword="null" /> if none exists.</returns>
IReadOnlyProperty? FindFirstPrincipal()
{
foreach (var foreignKey in GetContainingForeignKeys())
{
for (var propertyIndex = 0; propertyIndex < foreignKey.Properties.Count; propertyIndex++)
{
if (this == foreignKey.Properties[propertyIndex])
{
return foreignKey.PrincipalKey.Properties[propertyIndex];
}
}
}
return null;
}
/// <summary>
/// Finds the list of principal properties including the given property that the given property is constrained by
/// if the given property is part of a foreign key.
/// </summary>
/// <returns>The list of all associated principal properties including the given property.</returns>
IReadOnlyList<IReadOnlyProperty> GetPrincipals()
=> GetPrincipals<IReadOnlyProperty>();
/// <summary>
/// Finds the list of principal properties including the given property that the given property is constrained by
/// if the given property is part of a foreign key.
/// </summary>
/// <returns>The list of all associated principal properties including the given property.</returns>
IReadOnlyList<T> GetPrincipals<T>()
where T : IReadOnlyProperty
{
var principals = new List<T> { (T)this };
AddPrincipals((T)this, principals);
return principals;
}
private static void AddPrincipals<T>(T property, List<T> visited)
where T : IReadOnlyProperty
{
foreach (var foreignKey in property.GetContainingForeignKeys())
{
for (var propertyIndex = 0; propertyIndex < foreignKey.Properties.Count; propertyIndex++)
{
if (ReferenceEquals(property, foreignKey.Properties[propertyIndex]))
{
var principal = (T)foreignKey.PrincipalKey.Properties[propertyIndex];
if (!visited.Contains(principal))
{
visited.Add(principal);
AddPrincipals(principal, visited);
}
}
}
}
}
/// <summary>
/// Gets a value indicating whether this property is used as a foreign key (or part of a composite foreign key).
/// </summary>
/// <returns><see langword="true" /> if the property is used as a foreign key, otherwise <see langword="false" />.</returns>
bool IsForeignKey();
/// <summary>
/// Gets all foreign keys that use this property (including composite foreign keys in which this property
/// is included).
/// </summary>
/// <returns>The foreign keys that use this property.</returns>
IEnumerable<IReadOnlyForeignKey> GetContainingForeignKeys();
/// <summary>
/// Gets a value indicating whether this property is used as an index (or part of a composite index).
/// </summary>
/// <returns><see langword="true" /> if the property is used as an index, otherwise <see langword="false" />.</returns>
bool IsIndex();
/// <summary>
/// Gets a value indicating whether this property is used as a unique index (or part of a unique composite index).
/// </summary>
/// <returns><see langword="true" /> if the property is used as an unique index, otherwise <see langword="false" />.</returns>
bool IsUniqueIndex()
=> GetContainingIndexes().Any(e => e.IsUnique);
/// <summary>
/// Gets all indexes that use this property (including composite indexes in which this property
/// is included).
/// </summary>
/// <returns>The indexes that use this property.</returns>
IEnumerable<IReadOnlyIndex> GetContainingIndexes();
/// <summary>
/// Gets a value indicating whether this property is used as the primary key (or part of a composite primary key).
/// </summary>
/// <returns><see langword="true" /> if the property is used as the primary key, otherwise <see langword="false" />.</returns>
bool IsPrimaryKey()
=> FindContainingPrimaryKey() != null;
/// <summary>
/// Gets the primary key that uses this property (including a composite primary key in which this property
/// is included).
/// </summary>
/// <returns>The primary that use this property, or <see langword="null" /> if it is not part of the primary key.</returns>
IReadOnlyKey? FindContainingPrimaryKey();
/// <summary>
/// Gets a value indicating whether this property is used as the primary key or alternate key
/// (or part of a composite primary or alternate key).
/// </summary>
/// <returns><see langword="true" /> if the property is used as a key, otherwise <see langword="false" />.</returns>
bool IsKey();
/// <summary>
/// Gets all primary or alternate keys that use this property (including composite keys in which this property
/// is included).
/// </summary>
/// <returns>The primary and alternate keys that use this property.</returns>
IEnumerable<IReadOnlyKey> GetContainingKeys();
/// <summary>
/// <para>
/// Creates a human-readable representation of the given metadata.
/// </para>
/// <para>
/// Warning: Do not rely on the format of the returned string.
/// It is designed for debugging only and may change arbitrarily between releases.
/// </para>
/// </summary>
/// <param name="options">Options for generating the string.</param>
/// <param name="indent">The number of indent spaces to use before each new line.</param>
/// <returns>A human-readable representation.</returns>
string ToDebugString(MetadataDebugStringOptions options = MetadataDebugStringOptions.ShortDefault, int indent = 0)
{
var builder = new StringBuilder();
var indentString = new string(' ', indent);
try
{
builder.Append(indentString);
var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0;
if (singleLine)
{
builder.Append($"Property: {DeclaringType.DisplayName()}.");
}
builder.Append(Name).Append(" (");
var field = GetFieldName();
if (field == null)
{
builder.Append("no field, ");
}
else if (!field.EndsWith(">k__BackingField", StringComparison.Ordinal))
{
builder.Append(field).Append(", ");
}
builder.Append(ClrType.ShortDisplayName()).Append(')');
if (IsShadowProperty())
{
builder.Append(" Shadow");
}
if (IsIndexerProperty())
{
builder.Append(" Indexer");
}
if (!IsNullable)
{
builder.Append(" Required");
}
if (IsPrimaryKey())
{
builder.Append(" PK");
}
if (IsForeignKey())
{
builder.Append(" FK");
}
if (IsKey()
&& !IsPrimaryKey())
{
builder.Append(" AlternateKey");
}
if (IsIndex())
{
builder.Append(" Index");
}
if (IsConcurrencyToken)
{
builder.Append(" Concurrency");
}
if (Sentinel != null && !Equals(Sentinel, ClrType.GetDefaultValue()))
{
builder.Append(" Sentinel:").Append(Sentinel);
}
if (GetBeforeSaveBehavior() != PropertySaveBehavior.Save)
{
builder.Append(" BeforeSave:").Append(GetBeforeSaveBehavior());
}
if (GetAfterSaveBehavior() != PropertySaveBehavior.Save)
{
builder.Append(" AfterSave:").Append(GetAfterSaveBehavior());
}
if (ValueGenerated != ValueGenerated.Never)
{
builder.Append(" ValueGenerated.").Append(ValueGenerated);
}
if (GetMaxLength() != null)
{
builder.Append(" MaxLength(").Append(GetMaxLength()).Append(')');
}
if (IsUnicode() == false)
{
builder.Append(" ANSI");
}
if (GetPropertyAccessMode() != PropertyAccessMode.PreferField)
{
builder.Append(" PropertyAccessMode.").Append(GetPropertyAccessMode());
}
var elementType = GetElementType();
if (elementType != null)
{
builder.Append(" Element type: ").Append(elementType.ToDebugString());
}
if ((options & MetadataDebugStringOptions.IncludePropertyIndexes) != 0
&& (this is RuntimeAnnotatableBase || this is AnnotatableBase { IsReadOnly: true }))
{
var indexes = ((IProperty)this).GetPropertyIndexes();
builder.Append(' ').Append(indexes.Index);
builder.Append(' ').Append(indexes.OriginalValueIndex);
builder.Append(' ').Append(indexes.RelationshipIndex);
builder.Append(' ').Append(indexes.ShadowIndex);
builder.Append(' ').Append(indexes.StoreGenerationIndex);
}
if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0)
{
builder.Append(AnnotationsToDebugString(indent + 2));
}
}
catch (Exception exception)
{
builder.AppendLine().AppendLine(CoreStrings.DebugViewError(exception.Message));
}
return builder.ToString();
}
}
| IReadOnlyProperty |
csharp | dotnet__aspnetcore | src/SignalR/server/Core/src/IHubProtocolResolver.cs | {
"start": 336,
"end": 1041
} | public interface ____
{
/// <summary>
/// Gets a collection of all available hub protocols.
/// </summary>
IReadOnlyList<IHubProtocol> AllProtocols { get; }
/// <summary>
/// Gets the hub protocol with the specified name, if it is allowed by the specified list of supported protocols.
/// </summary>
/// <param name="protocolName">The protocol name.</param>
/// <param name="supportedProtocols">A collection of supported protocols.</param>
/// <returns>A matching <see cref="IHubProtocol"/> or <c>null</c> if no matching protocol was found.</returns>
IHubProtocol? GetProtocol(string protocolName, IReadOnlyList<string>? supportedProtocols);
}
| IHubProtocolResolver |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Services/Default/DistributedBackchannelAuthenticationThrottlingService.cs | {
"start": 1751,
"end": 2648
} | record ____
if (lastSeenAsString == null)
{
await _cache.SetStringAsync(key, _clock.UtcNow.ToString("O"), options);
return false;
}
// check interval
if (DateTime.TryParse(lastSeenAsString, out var lastSeen))
{
lastSeen = lastSeen.ToUniversalTime();
var client = await _clientStore.FindEnabledClientByIdAsync(details.ClientId);
var interval = client?.PollingInterval ?? _options.Ciba.DefaultPollingInterval;
if (_clock.UtcNow.UtcDateTime < lastSeen.AddSeconds(interval))
{
await _cache.SetStringAsync(key, _clock.UtcNow.ToString("O"), options);
return true;
}
}
// store current and continue
await _cache.SetStringAsync(key, _clock.UtcNow.ToString("O"), options);
return false;
}
}
| new |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition.Scenes/SceneObject.cs | {
"start": 304,
"end": 540
} | public partial class ____ : global::Windows.UI.Composition.CompositionObject
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal SceneObject()
{
}
#endif
}
}
| SceneObject |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Globalization.NumberFormatting/DecimalFormatter.cs | {
"start": 273,
"end": 9736
} | public partial class ____ : global::Windows.Globalization.NumberFormatting.INumberFormatterOptions, global::Windows.Globalization.NumberFormatting.INumberFormatter, global::Windows.Globalization.NumberFormatting.INumberFormatter2, global::Windows.Globalization.NumberFormatting.INumberParser, global::Windows.Globalization.NumberFormatting.ISignificantDigitsOption, global::Windows.Globalization.NumberFormatting.INumberRounderOption, global::Windows.Globalization.NumberFormatting.ISignedZeroOption
{
// Skipping already declared property IsDecimalPointAlwaysDisplayed
// Skipping already declared property IntegerDigits
// Skipping already declared property IsGrouped
// Skipping already declared property NumeralSystem
// Skipping already declared property FractionDigits
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string GeographicRegion
{
get
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.GeographicRegion is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.GeographicRegion");
}
}
#endif
// Skipping already declared property Languages
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string ResolvedGeographicRegion
{
get
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.ResolvedGeographicRegion is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.ResolvedGeographicRegion");
}
}
#endif
// Skipping already declared property ResolvedLanguage
// Skipping already declared property NumberRounder
// Skipping already declared property IsZeroSigned
// Skipping already declared property SignificantDigits
#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 DecimalFormatter(global::System.Collections.Generic.IEnumerable<string> languages, string geographicRegion)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Globalization.NumberFormatting.DecimalFormatter", "DecimalFormatter.DecimalFormatter(IEnumerable<string> languages, string geographicRegion)");
}
#endif
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.DecimalFormatter(System.Collections.Generic.IEnumerable<string>, string)
// Skipping already declared method Windows.Globalization.NumberFormatting.DecimalFormatter.DecimalFormatter()
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.DecimalFormatter()
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.Languages.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.GeographicRegion.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IntegerDigits.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IntegerDigits.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.FractionDigits.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.FractionDigits.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsGrouped.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsGrouped.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsDecimalPointAlwaysDisplayed.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsDecimalPointAlwaysDisplayed.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.NumeralSystem.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.NumeralSystem.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.ResolvedLanguage.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.ResolvedGeographicRegion.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string Format(long value)
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.Format(long value) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.Format%28long%20value%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string Format(ulong value)
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.Format(ulong value) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.Format%28ulong%20value%29");
}
#endif
// Skipping already declared method Windows.Globalization.NumberFormatting.DecimalFormatter.Format(double)
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string FormatInt(long value)
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.FormatInt(long value) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.FormatInt%28long%20value%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string FormatUInt(ulong value)
{
throw new global::System.NotImplementedException("The member string DecimalFormatter.FormatUInt(ulong value) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DecimalFormatter.FormatUInt%28ulong%20value%29");
}
#endif
// Skipping already declared method Windows.Globalization.NumberFormatting.DecimalFormatter.FormatDouble(double)
#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 long? ParseInt(string text)
{
throw new global::System.NotImplementedException("The member long? DecimalFormatter.ParseInt(string text) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=long%3F%20DecimalFormatter.ParseInt%28string%20text%29");
}
#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 ulong? ParseUInt(string text)
{
throw new global::System.NotImplementedException("The member ulong? DecimalFormatter.ParseUInt(string text) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ulong%3F%20DecimalFormatter.ParseUInt%28string%20text%29");
}
#endif
// Skipping already declared method Windows.Globalization.NumberFormatting.DecimalFormatter.ParseDouble(string)
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.SignificantDigits.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.SignificantDigits.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.NumberRounder.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.NumberRounder.set
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsZeroSigned.get
// Forced skipping of method Windows.Globalization.NumberFormatting.DecimalFormatter.IsZeroSigned.set
// Processing: Windows.Globalization.NumberFormatting.INumberFormatterOptions
// Processing: Windows.Globalization.NumberFormatting.INumberFormatter
// Processing: Windows.Globalization.NumberFormatting.INumberFormatter2
// Processing: Windows.Globalization.NumberFormatting.INumberParser
// Processing: Windows.Globalization.NumberFormatting.ISignificantDigitsOption
// Processing: Windows.Globalization.NumberFormatting.INumberRounderOption
// Processing: Windows.Globalization.NumberFormatting.ISignedZeroOption
}
}
| DecimalFormatter |
csharp | dotnet__reactive | Ix.NET/Source/FasterLinq/Program.cs | {
"start": 33545,
"end": 37437
} | public static class ____
{
private static readonly Task<bool> True = Task.FromResult(true);
private static readonly Task<bool> False = Task.FromResult(false);
public static async Task<R> Aggregate<T, R>(this IAsyncFastEnumerable<T> source, R seed, Func<R, T, R> aggregate)
{
var res = seed;
var e = source.GetAsyncEnumerator();
try
{
while (await e.WaitForNextAsync().ConfigureAwait(false))
{
while (true)
{
var item = e.TryGetNext(out var success);
if (!success)
{
break;
}
res = aggregate(res, item);
}
}
}
finally
{
await e.DisposeAsync().ConfigureAwait(false);
}
return res;
}
public static async Task<R> Aggregate<T, R>(this IAsyncFastEnumerable<T> source, R seed, Func<R, T, Task<R>> aggregate)
{
var res = seed;
var e = source.GetAsyncEnumerator();
try
{
while (await e.WaitForNextAsync().ConfigureAwait(false))
{
while (true)
{
var item = e.TryGetNext(out var success);
if (!success)
{
break;
}
res = await aggregate(res, item).ConfigureAwait(false);
}
}
}
finally
{
await e.DisposeAsync().ConfigureAwait(false);
}
return res;
}
public static IAsyncFastEnumerable<T> Empty<T>() => EmptyIterator<T>.Instance;
public static async Task ForEachAsync<T>(this IAsyncFastEnumerable<T> source, Func<T, Task> next)
{
var e = source.GetAsyncEnumerator();
try
{
while (await e.WaitForNextAsync().ConfigureAwait(false))
{
while (true)
{
var item = e.TryGetNext(out var success);
if (!success)
{
break;
}
await next(item).ConfigureAwait(false);
}
}
}
finally
{
await e.DisposeAsync().ConfigureAwait(false);
}
}
public static IAsyncFastEnumerable<int> Range(int start, int count) => new RangeIterator(start, count);
public static IAsyncFastEnumerable<R> Select<T, R>(this IAsyncFastEnumerable<T> source, Func<T, R> selector) => new SelectFastIterator<T, R>(source, selector);
public static IAsyncFastEnumerable<R> Select<T, R>(this IAsyncFastEnumerable<T> source, Func<T, Task<R>> selector) => new SelectFastIteratorWithTask<T, R>(source, selector);
public static IAsyncFastEnumerable<T> ToAsyncFastEnumerable<T>(this IAsyncEnumerable<T> source) => new AsyncEnumerableToAsyncFastEnumerable<T>(source);
public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IAsyncFastEnumerable<T> source) => new AsyncFastEnumerableToAsyncEnumerable<T>(source);
public static IAsyncFastEnumerable<T> Where<T>(this IAsyncFastEnumerable<T> source, Func<T, bool> predicate) => new WhereFastIterator<T>(source, predicate);
public static IAsyncFastEnumerable<T> Where<T>(this IAsyncFastEnumerable<T> source, Func<T, Task<bool>> predicate) => new WhereFastIteratorWithTask<T>(source, predicate);
| AsyncFastEnumerable |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/Publish_Specs.cs | {
"start": 12486,
"end": 12837
} | public class ____ :
RabbitMqTestFixture
{
[Test]
public async Task Should_not_throw_an_exception()
{
var message = new UnboundMessage { Id = Guid.NewGuid() };
await Bus.Publish(message);
}
| When_a_message_is_published_without_a_queue_binding |
csharp | dotnet__orleans | src/api/Orleans.Core/Orleans.Core.cs | {
"start": 18668,
"end": 19153
} | public partial class ____
{
public static readonly System.TimeSpan DEFAULT_OPENCONNECTION_TIMEOUT;
public System.TimeSpan ConnectionRetryDelay { get { throw null; } set { } }
public int ConnectionsPerEndpoint { get { throw null; } set { } }
public System.TimeSpan OpenConnectionTimeout { get { throw null; } set { } }
public Runtime.Messaging.NetworkProtocolVersion ProtocolVersion { get { throw null; } set { } }
}
| ConnectionOptions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.