language stringclasses 1 value | repo stringclasses 133 values | path stringlengths 13 229 | class_span dict | source stringlengths 14 2.92M | target stringlengths 1 153 |
|---|---|---|---|---|---|
csharp | dotnet__maui | src/Controls/src/Core/Handlers/Items/CarouselViewHandler.cs | {
"start": 71,
"end": 882
} | public partial class ____
{
public CarouselViewHandler() : base(Mapper)
{
}
public CarouselViewHandler(PropertyMapper mapper = null) : base(mapper ?? Mapper)
{
}
public static PropertyMapper<CarouselView, CarouselViewHandler> Mapper = new(ItemsViewMapper)
{
#if TIZEN || ANDROID
[Controls.CarouselView.ItemsLayoutProperty.PropertyName] = MapItemsLayout,
#endif
[Controls.CarouselView.IsSwipeEnabledProperty.PropertyName] = MapIsSwipeEnabled,
[Controls.CarouselView.PeekAreaInsetsProperty.PropertyName] = MapPeekAreaInsets,
[Controls.CarouselView.IsBounceEnabledProperty.PropertyName] = MapIsBounceEnabled,
[Controls.CarouselView.PositionProperty.PropertyName] = MapPosition,
[Controls.CarouselView.CurrentItemProperty.PropertyName] = MapCurrentItem
};
}
} | CarouselViewHandler |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/HtmlGenerationWebSite/Controllers/Catalog_CacheTagHelperController.cs | {
"start": 283,
"end": 2883
} | public class ____ : Controller
{
[HttpGet("/catalog")]
public IActionResult Splash(int categoryId, int correlationId, [FromHeader] string locale)
{
var category = categoryId == 1 ? "Laptops" : "Phones";
ViewData["Category"] = category;
ViewData["Locale"] = locale;
ViewData["CorrelationId"] = correlationId;
return View();
}
[HttpGet("/catalog/{id:int}")]
public IActionResult Details(int id)
{
ViewData["ProductId"] = id;
return View();
}
[HttpGet("/catalog/cart")]
public IActionResult ShoppingCart(int correlationId)
{
ViewData["CorrelationId"] = correlationId;
return View();
}
[HttpGet("/catalog/{region}/confirm-payment")]
public IActionResult GuestConfirmPayment(string region, int confirmationId = 0)
{
ViewData["Message"] = "Welcome Guest. Your confirmation id is " + confirmationId;
ViewData["Region"] = region;
return View("ConfirmPayment");
}
[HttpGet("/catalog/{region}/{section}/confirm-payment")]
public IActionResult ConfirmPayment(string region, string section, int confirmationId)
{
var message = "Welcome " + section + " member. Your confirmation id is " + confirmationId;
ViewData["Message"] = message;
ViewData["Region"] = region;
return View();
}
[HttpGet("/catalog/past-purchases/{id}")]
public IActionResult PastPurchases(string id, int correlationId)
{
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, id));
HttpContext.User = new ClaimsPrincipal(identity);
ViewData["CorrelationId"] = correlationId;
return View();
}
[HttpGet("/categories/{category}")]
public IActionResult ListCategories(string category, int correlationId)
{
ViewData["Category"] = category;
ViewData["CorrelationId"] = correlationId;
return View();
}
[HttpPost("/categories/{category}")]
public IActionResult UpdateProducts(
[FromServices] ProductsService productService,
string category,
[FromBody] List<Product> products)
{
productService.UpdateProducts(category, products);
return Ok();
}
[HttpGet("/catalog/GetDealPercentage/{dealPercentage}")]
public IActionResult Deals(int dealPercentage, bool isEnabled)
{
ViewBag.ProductDealPercentage = dealPercentage;
ViewBag.IsEnabled = isEnabled;
return View();
}
}
| Catalog_CacheTagHelperController |
csharp | xunit__xunit | src/xunit.v3.runner.common/Reporters/Builtin/VstsReporter.cs | {
"start": 459,
"end": 2340
} | public class ____ : IRunnerReporter
{
/// <inheritdoc/>
public bool CanBeEnvironmentallyEnabled =>
true;
/// <inheritdoc/>
public string Description =>
"Azure DevOps/VSTS CI support";
/// <inheritdoc/>
public bool ForceNoLogo =>
false;
/// <inheritdoc/>
public bool IsEnvironmentallyEnabled =>
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("VSTS_ACCESS_TOKEN")) &&
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI")) &&
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")) &&
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("BUILD_BUILDID"));
/// <inheritdoc/>
public string? RunnerSwitch =>
null;
/// <inheritdoc/>
public ValueTask<IRunnerReporterMessageHandler> CreateMessageHandler(
IRunnerLogger logger,
IMessageSink? diagnosticMessageSink)
{
var collectionUri = Guard.NotNull("Environment variable SYSTEM_TEAMFOUNDATIONCOLLECTIONURI is not set", Environment.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"));
var teamProject = Guard.NotNull("Environment variable SYSTEM_TEAMPROJECT is not set", Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT"));
var accessToken = Guard.NotNull("Environment variable VSTS_ACCESS_TOKEN is not set", Environment.GetEnvironmentVariable("VSTS_ACCESS_TOKEN"));
var buildId = Convert.ToInt32(Guard.NotNull("Environment variable BUILD_BUILDID is not set", Environment.GetEnvironmentVariable("BUILD_BUILDID")), CultureInfo.InvariantCulture);
var baseUri = string.Format(CultureInfo.InvariantCulture, "{0}{1}/_apis/test/runs", collectionUri, teamProject);
#pragma warning disable CA2000 // The disposable object is returned via the ValueTask
return new(new VstsReporterMessageHandler(logger, baseUri, accessToken, buildId));
#pragma warning restore CA2000
}
}
| VstsReporter |
csharp | khellang__Scrutor | src/Scrutor/ServiceProviderExtensions.cs | {
"start": 136,
"end": 2311
} | public static class ____
{
/// <summary>
/// Get all decorated services of type <typeparamref name="TService"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="TService">The type of services which were decorated.</typeparam>
/// <param name="serviceProvider">The <see cref="IServiceProvider"/> to retrieve the service objects from.</param>
/// <param name="decoratedType">A handle to a decorated service, obtainable from a <see cref="Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.Decorate{TService, TDecorator}(IServiceCollection, out DecoratedService{TService})"/>
/// overload which omits one as an <c>out</c> parameter.</param>
/// <returns>A service object of type <typeparamref name="TService"/>.</returns>
public static IEnumerable<TService> GetDecoratedServices<TService>(this IServiceProvider serviceProvider, DecoratedService<TService> decoratedType)
{
return decoratedType.ServiceKeys.Reverse().Select(key => (TService)serviceProvider.GetRequiredKeyedService(decoratedType.ServiceType, key));
}
/// <summary>
/// Get decorated service of type <typeparamref name="TService"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="TService">The type of service which was decorated.</typeparam>
/// <param name="serviceProvider">The <see cref="IServiceProvider"/> to retrieve the service object from.</param>
/// <param name="decoratedType">A handle to a decorated service, obtainable from a <see cref="Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.Decorate{TService, TDecorator}(IServiceCollection, out DecoratedService{TService})"/>
/// overload which omits one as an <c>out</c> parameter.</param>
/// <returns>A service object of type <typeparamref name="TService"/>.</returns>
public static TService GetRequiredDecoratedService<TService>(this IServiceProvider serviceProvider, DecoratedService<TService> decoratedType)
{
return (TService)serviceProvider.GetRequiredKeyedService(decoratedType.ServiceType, decoratedType.ServiceKeys[0]);
}
}
| ServiceProviderExtensions |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Misc.Zettle/Services/ZettleHttpClient.cs | {
"start": 347,
"end": 4543
} | public class ____
{
#region Fields
protected readonly HttpClient _httpClient;
protected readonly ZettleSettings _zettleSettings;
protected string _accessToken;
#endregion
#region Ctor
public ZettleHttpClient(HttpClient httpClient, ZettleSettings zettleSettings)
{
httpClient.Timeout = TimeSpan.FromSeconds(zettleSettings.RequestTimeout ?? ZettleDefaults.RequestTimeout);
httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, ZettleDefaults.UserAgent);
httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, MimeTypes.ApplicationJson);
httpClient.DefaultRequestHeaders.Add(ZettleDefaults.PartnerHeader.Name, ZettleDefaults.PartnerHeader.Value);
_httpClient = httpClient;
_zettleSettings = zettleSettings;
}
#endregion
#region Utilities
/// <summary>
/// Get access token
/// </summary>
/// <returns>The asynchronous task whose result contains access token</returns>
protected async Task<string> GetAccessTokenAsync()
{
if (!string.IsNullOrEmpty(_accessToken))
return _accessToken;
if (string.IsNullOrEmpty(_zettleSettings.ApiKey))
throw new NopException("API key is not set");
_accessToken = (await RequestAsync<GetAuthenticationRequest, Authentication>(new()
{
Assertion = _zettleSettings.ApiKey,
ClientId = ZettleDefaults.PartnerHeader.Value,
GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
}))?.AccessToken;
return _accessToken;
}
#endregion
#region Methods
/// <summary>
/// Request services
/// </summary>
/// <typeparam name="TRequest">Request type</typeparam>
/// <typeparam name="TResponse">Response type</typeparam>
/// <param name="request">Request</param>
/// <returns>The asynchronous task whose result contains response details</returns>
public async Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request) where TRequest : IApiRequest where TResponse : IApiResponse
{
//prepare request parameters
var requestString = JsonConvert.SerializeObject(request);
var requestContent = request is not GetAuthenticationRequest authentication
? (ByteArrayContent)new StringContent(requestString, Encoding.UTF8, MimeTypes.ApplicationJson)
: new FormUrlEncodedContent(new Dictionary<string, string>
{
["assertion"] = authentication.Assertion,
["client_id"] = authentication.ClientId,
["grant_type"] = authentication.GrantType
});
var requestMessage = new HttpRequestMessage(new HttpMethod(request.Method), new Uri(new Uri(request.BaseUrl), request.Path))
{
Content = requestContent
};
//add authorization
if (request is IAuthorizedRequest)
{
var accessToken = await GetAccessTokenAsync();
requestMessage.Headers.Add(HeaderNames.Authorization, $"Bearer {accessToken}");
}
//add ETag
if (request is IConditionalRequest conditionalRequest)
{
var header = request.Method == HttpMethods.Get
? HeaderNames.IfNoneMatch
: HeaderNames.IfMatch;
requestMessage.Headers.Add(header, conditionalRequest.ETag);
}
//execute request and get result
var httpResponse = await _httpClient.SendAsync(requestMessage);
var responseString = await httpResponse.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TResponse>(responseString ?? string.Empty);
if (!string.IsNullOrEmpty(result?.Error))
{
var error = !string.IsNullOrEmpty(result.ErrorDescription) ? result.ErrorDescription : result.Error;
throw new NopException($"Request error: {error}");
}
if (!string.IsNullOrEmpty(result?.DeveloperMessage))
throw new NopException($"Request error: {result.DeveloperMessage}{Environment.NewLine}Details: {responseString}");
return result;
}
#endregion
} | ZettleHttpClient |
csharp | MaterialDesignInXAML__MaterialDesignInXamlToolkit | tests/MaterialDesignThemes.Wpf.Tests/TextBoxTests.cs | {
"start": 108,
"end": 969
} | public class ____
{
[Test]
[Description("Issue 1301")]
public async Task DefaultVerticalAlignment_ShouldBeStretch()
{
var testBox = new TextBox();
testBox.ApplyDefaultStyle();
await Assert.That(testBox.VerticalAlignment).IsEqualTo(VerticalAlignment.Stretch);
}
[Test]
[Description("Issue 2556")]
public async Task DefaultVerticalContentAlignment_ShouldBeStretch()
{
//The default was initially set to Top from issue 1301
//However because TextBox contains a ScrollViewer this pushes
//the horizontal scroll bar up by default, which is different
//than the default WPF behavior.
var textBox = new TextBox();
textBox.ApplyDefaultStyle();
await Assert.That(textBox.VerticalContentAlignment).IsEqualTo(VerticalAlignment.Stretch);
}
}
| TextBoxTests |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/UpdateDefinitionBuilder.cs | {
"start": 72068,
"end": 75706
} | internal sealed class ____<TDocument, TItem> : UpdateDefinition<TDocument>
{
private readonly FieldDefinition<TDocument> _field;
private readonly int? _position;
private readonly int? _slice;
private SortDefinition<TItem> _sort;
private readonly List<TItem> _values;
public PushUpdateDefinition(FieldDefinition<TDocument> field, IEnumerable<TItem> values, int? slice = null, int? position = null, SortDefinition<TItem> sort = null)
{
_field = Ensure.IsNotNull(field, nameof(field));
_values = Ensure.IsNotNull(values, nameof(values)).ToList();
_slice = slice;
_position = position;
_sort = sort;
}
public override BsonValue Render(RenderArgs<TDocument> args)
{
var renderedField = _field.Render(args);
IBsonSerializer itemSerializer;
if (renderedField.FieldSerializer != null)
{
var arraySerializer = renderedField.FieldSerializer as IBsonArraySerializer;
BsonSerializationInfo itemSerializationInfo;
if (arraySerializer == null || !arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo))
{
var message = string.Format("The serializer for field '{0}' must implement IBsonArraySerializer and provide item serialization info.", renderedField.FieldName);
throw new InvalidOperationException(message);
}
itemSerializer = itemSerializationInfo.Serializer;
}
else
{
itemSerializer = args.SerializerRegistry.GetSerializer<TItem>();
}
var document = new BsonDocument();
using (var bsonWriter = new BsonDocumentWriter(document))
{
var context = BsonSerializationContext.CreateRoot(bsonWriter);
bsonWriter.WriteStartDocument();
bsonWriter.WriteName("$push");
bsonWriter.WriteStartDocument();
bsonWriter.WriteName(renderedField.FieldName);
if (!_slice.HasValue && !_position.HasValue && _sort == null && _values.Count == 1)
{
itemSerializer.Serialize(context, _values[0]);
}
else
{
bsonWriter.WriteStartDocument();
bsonWriter.WriteName("$each");
bsonWriter.WriteStartArray();
foreach (var value in _values)
{
itemSerializer.Serialize(context, value);
}
bsonWriter.WriteEndArray();
if (_slice.HasValue)
{
bsonWriter.WriteName("$slice");
bsonWriter.WriteInt32(_slice.Value);
}
if (_position.HasValue)
{
bsonWriter.WriteName("$position");
bsonWriter.WriteInt32(_position.Value);
}
bsonWriter.WriteEndDocument();
}
bsonWriter.WriteEndDocument();
bsonWriter.WriteEndDocument();
}
if (_sort != null)
{
document["$push"][renderedField.FieldName]["$sort"] = _sort.RenderAsBsonValue(args.WithNewDocumentType((IBsonSerializer<TItem>)itemSerializer));
}
return document;
}
}
}
| PushUpdateDefinition |
csharp | neuecc__MessagePack-CSharp | src/MessagePack/MessagePackSecurity.cs | {
"start": 9507,
"end": 14558
} | enum ____ to avoid dynamically generating code.
type.IsEnum && type.GetEnumUnderlyingType() is Type underlying ? (
underlying == typeof(byte) ? CollisionResistantEnumHasher<T, byte>.Instance :
underlying == typeof(sbyte) ? CollisionResistantEnumHasher<T, sbyte>.Instance :
underlying == typeof(ushort) ? CollisionResistantEnumHasher<T, ushort>.Instance :
underlying == typeof(short) ? CollisionResistantEnumHasher<T, short>.Instance :
underlying == typeof(uint) ? CollisionResistantEnumHasher<T, uint>.Instance :
underlying == typeof(int) ? CollisionResistantEnumHasher<T, int>.Instance :
underlying == typeof(ulong) ? CollisionResistantEnumHasher<T, ulong>.Instance :
underlying == typeof(long) ? CollisionResistantEnumHasher<T, long>.Instance :
null) :
// Failsafe. If we don't recognize the type, don't assume we have a good, secure hash function for it.
null;
}
}
/// <summary>
/// Returns a hash collision resistant equality comparer.
/// </summary>
/// <typeparam name="T">The type of key that will be hashed in the collection.</typeparam>
/// <returns>A hash collision resistant equality comparer.</returns>
protected virtual IEqualityComparer<T> GetHashCollisionResistantEqualityComparer<T>()
{
if (HashResistantCache<T>.EqualityComparer is { } result)
{
return result;
}
if (typeof(T) == typeof(object))
{
return (IEqualityComparer<T>)this.objectFallbackEqualityComparer;
}
// Any type we don't explicitly whitelist here shouldn't be allowed to use as the key in a hash-based collection since it isn't known to be hash resistant.
// This method can of course be overridden to add more hash collision resistant type support, or the deserializing party can indicate that the data is Trusted
// so that this method doesn't even get called.
throw new TypeAccessException($"No hash-resistant equality comparer available for type: {typeof(T)}");
}
/// <summary>
/// Checks the depth of the deserializing graph and increments it by 1.
/// </summary>
/// <param name="reader">The reader that is involved in deserialization.</param>
/// <remarks>
/// Callers should decrement <see cref="MessagePackReader.Depth"/> after exiting that edge in the graph.
/// </remarks>
/// <exception cref="InsufficientExecutionStackException">Thrown if <see cref="MessagePackReader.Depth"/> is already at or exceeds <see cref="MaximumObjectGraphDepth"/>.</exception>
/// <remarks>
/// Rather than wrap the body of every <see cref="IMessagePackFormatter{T}.Deserialize"/> method,
/// this should wrap *calls* to these methods. They need not appear in pure "thunk" methods that simply delegate the deserialization to another formatter.
/// In this way, we can avoid repeatedly incrementing and decrementing the counter when deserializing each element of a collection.
/// </remarks>
public void DepthStep(ref MessagePackReader reader)
{
if (reader.Depth >= this.MaximumObjectGraphDepth)
{
throw new InsufficientExecutionStackException($"This msgpack sequence has an object graph that exceeds the maximum depth allowed of {MaximumObjectGraphDepth}.");
}
reader.Depth++;
}
/// <summary>
/// Returns a hash collision resistant equality comparer.
/// </summary>
/// <returns>A hash collision resistant equality comparer.</returns>
protected virtual IEqualityComparer GetHashCollisionResistantEqualityComparer() => (IEqualityComparer)this.GetHashCollisionResistantEqualityComparer<object>();
/// <summary>
/// Creates a new instance that is a copy of this one.
/// </summary>
/// <remarks>
/// Derived types should override this method to instantiate their own derived type.
/// </remarks>
protected virtual MessagePackSecurity Clone() => new MessagePackSecurity(this);
private static int SecureHash<T>(T value)
where T : unmanaged
{
Span<T> span = stackalloc T[1];
span[0] = value;
return unchecked((int)Hash.Compute(MemoryMarshal.Cast<T, byte>(span)));
}
private static int SecureHash(ReadOnlySpan<byte> data) => unchecked((int)Hash.Compute(data));
/// <summary>
/// A hash collision resistant implementation of <see cref="IEqualityComparer{T}"/>.
/// </summary>
/// <typeparam name="T">The type of key that will be hashed.</typeparam>
| explicitly |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs | {
"start": 1378,
"end": 2713
} | public interface ____
{
/// <summary>
/// Gets all annotations stored on this IAnnotatable.
/// </summary>
IEnumerable<object> Annotations {
get;
}
/// <summary>
/// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists.
/// </summary>
/// <typeparam name='T'>
/// The type of the annotation.
/// </typeparam>
T Annotation<T>() where T : class;
/// <summary>
/// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists.
/// </summary>
/// <param name='type'>
/// The type of the annotation.
/// </param>
object Annotation(Type type);
/// <summary>
/// Adds an annotation to this instance.
/// </summary>
/// <param name='annotation'>
/// The annotation to add.
/// </param>
void AddAnnotation(object annotation);
/// <summary>
/// Removes all annotations of the specified type.
/// </summary>
/// <typeparam name='T'>
/// The type of the annotations to remove.
/// </typeparam>
void RemoveAnnotations<T>() where T : class;
/// <summary>
/// Removes all annotations of the specified type.
/// </summary>
/// <param name='type'>
/// The type of the annotations to remove.
/// </param>
void RemoveAnnotations(Type type);
}
/// <summary>
/// Base | IAnnotatable |
csharp | bitwarden__server | util/PostgresMigrations/Migrations/20220301211818_FailedLoginCaptcha.Designer.cs | {
"start": 489,
"end": 56762
} | partial class ____
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:CollationDefinition:postgresIndetermanisticCollation", "en-u-ks-primary,en-u-ks-primary,icu,False")
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.12")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Attachments")
.HasColumnType("text");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Favorites")
.HasColumnType("text");
b.Property<string>("Folders")
.HasColumnType("text");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<byte?>("Reprompt")
.HasColumnType("smallint");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Cipher");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Collection");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("CipherId")
.HasColumnType("uuid");
b.HasKey("CollectionId", "CipherId");
b.HasIndex("CipherId");
b.ToTable("CollectionCipher");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<bool>("HidePasswords")
.HasColumnType("boolean");
b.Property<bool>("ReadOnly")
.HasColumnType("boolean");
b.HasKey("CollectionId", "GroupId");
b.HasIndex("GroupId");
b.ToTable("CollectionGroups");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("uuid");
b.Property<bool>("HidePasswords")
.HasColumnType("boolean");
b.Property<bool>("ReadOnly")
.HasColumnType("boolean");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("CollectionId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.HasIndex("UserId");
b.ToTable("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PushToken")
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Device");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.EmergencyAccess", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid?>("GranteeId")
.HasColumnType("uuid");
b.Property<Guid>("GrantorId")
.HasColumnType("uuid");
b.Property<string>("KeyEncrypted")
.HasColumnType("text");
b.Property<DateTime?>("LastNotificationDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("RecoveryInitiatedDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<int>("WaitTimeDays")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("GranteeId");
b.HasIndex("GrantorId");
b.ToTable("EmergencyAccess");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid?>("ActingUserId")
.HasColumnType("uuid");
b.Property<Guid?>("CipherId")
.HasColumnType("uuid");
b.Property<Guid?>("CollectionId")
.HasColumnType("uuid");
b.Property<DateTime>("Date")
.HasColumnType("timestamp without time zone");
b.Property<byte?>("DeviceType")
.HasColumnType("smallint");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("IpAddress")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("OrganizationUserId")
.HasColumnType("uuid");
b.Property<Guid?>("PolicyId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderOrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderUserId")
.HasColumnType("uuid");
b.Property<int>("Type")
.HasColumnType("integer");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.ToTable("Event");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Folder", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Folder");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Grant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("ClientId")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("ConsumedDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Type")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Key");
b.ToTable("Grant");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("AccessAll")
.HasColumnType("boolean");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Name")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("uuid");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("GroupId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.HasIndex("UserId");
b.ToTable("GroupUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Key")
.HasMaxLength(150)
.HasColumnType("character varying(150)");
b.HasKey("Id");
b.ToTable("Installation");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("ApiKey")
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<string>("BillingEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("BusinessAddress1")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessAddress2")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessAddress3")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessCountry")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<string>("BusinessName")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessTaxNumber")
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp without time zone");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("integer");
b.Property<short?>("MaxCollections")
.HasColumnType("smallint");
b.Property<short?>("MaxStorageGb")
.HasColumnType("smallint");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime?>("OwnersNotifiedOfAutoscaling")
.HasColumnType("timestamp without time zone");
b.Property<string>("Plan")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<byte>("PlanType")
.HasColumnType("smallint");
b.Property<string>("PrivateKey")
.HasColumnType("text");
b.Property<string>("PublicKey")
.HasColumnType("text");
b.Property<string>("ReferenceData")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<int?>("Seats")
.HasColumnType("integer");
b.Property<bool>("SelfHost")
.HasColumnType("boolean");
b.Property<long?>("Storage")
.HasColumnType("bigint");
b.Property<string>("TwoFactorProviders")
.HasColumnType("text");
b.Property<bool>("Use2fa")
.HasColumnType("boolean");
b.Property<bool>("UseApi")
.HasColumnType("boolean");
b.Property<bool>("UseDirectory")
.HasColumnType("boolean");
b.Property<bool>("UseEvents")
.HasColumnType("boolean");
b.Property<bool>("UseGroups")
.HasColumnType("boolean");
b.Property<bool>("UseKeyConnector")
.HasColumnType("boolean");
b.Property<bool>("UsePolicies")
.HasColumnType("boolean");
b.Property<bool>("UseResetPassword")
.HasColumnType("boolean");
b.Property<bool>("UseSso")
.HasColumnType("boolean");
b.Property<bool>("UseTotp")
.HasColumnType("boolean");
b.Property<bool>("UsersGetPremium")
.HasColumnType("boolean");
b.HasKey("Id");
b.ToTable("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("CloudSponsor")
.HasColumnType("boolean");
b.Property<string>("FriendlyName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid?>("InstallationId")
.HasColumnType("uuid");
b.Property<DateTime?>("LastSyncDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("OfferedToEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<byte?>("PlanSponsorshipType")
.HasColumnType("smallint");
b.Property<Guid?>("SponsoredOrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("SponsoringOrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("SponsoringOrganizationUserId")
.HasColumnType("uuid");
b.Property<DateTime?>("SponsorshipLapsedDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("TimesRenewedWithoutValidation")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("InstallationId");
b.HasIndex("SponsoredOrganizationId");
b.HasIndex("SponsoringOrganizationId");
b.ToTable("OrganizationSponsorship");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("AccessAll")
.HasColumnType("boolean");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("Permissions")
.HasColumnType("text");
b.Property<string>("ResetPasswordKey")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Policy");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Provider", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("BillingEmail")
.HasColumnType("text");
b.Property<string>("BusinessAddress1")
.HasColumnType("text");
b.Property<string>("BusinessAddress2")
.HasColumnType("text");
b.Property<string>("BusinessAddress3")
.HasColumnType("text");
b.Property<string>("BusinessCountry")
.HasColumnType("text");
b.Property<string>("BusinessName")
.HasColumnType("text");
b.Property<string>("BusinessTaxNumber")
.HasColumnType("text");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<bool>("UseEvents")
.HasColumnType("boolean");
b.HasKey("Id");
b.ToTable("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Settings")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ProviderId");
b.ToTable("ProviderOrganization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.HasColumnType("text");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("Permissions")
.HasColumnType("text");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.HasIndex("UserId");
b.ToTable("ProviderUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int>("AccessCount")
.HasColumnType("integer");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<DateTime>("DeletionDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool?>("HideEmail")
.HasColumnType("boolean");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<int?>("MaxAccessCount")
.HasColumnType("integer");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("Password")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Send");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoConfig", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("SsoConfig");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("ExternalId")
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("SsoUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b =>
{
b.Property<string>("Id")
.HasMaxLength(40)
.HasColumnType("character varying(40)");
b.Property<bool>("Active")
.HasColumnType("boolean");
b.Property<string>("Country")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PostalCode")
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<decimal>("Rate")
.HasColumnType("numeric");
b.Property<string>("State")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.HasKey("Id");
b.ToTable("TaxRate");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Details")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<byte?>("PaymentMethodType")
.HasColumnType("smallint");
b.Property<bool?>("Refunded")
.HasColumnType("boolean");
b.Property<decimal?>("RefundedAmount")
.HasColumnType("numeric");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Transaction");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("AccountRevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("ApiKey")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Culture")
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<bool>("EmailVerified")
.HasColumnType("boolean");
b.Property<string>("EquivalentDomains")
.HasColumnType("text");
b.Property<string>("ExcludedGlobalEquivalentDomains")
.HasColumnType("text");
b.Property<int>("FailedLoginCount")
.HasColumnType("integer");
b.Property<bool>("ForcePasswordReset")
.HasColumnType("boolean");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<byte>("Kdf")
.HasColumnType("smallint");
b.Property<int>("KdfIterations")
.HasColumnType("integer");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<DateTime?>("LastFailedLoginDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("MasterPassword")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("MasterPasswordHint")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<short?>("MaxStorageGb")
.HasColumnType("smallint");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<bool>("Premium")
.HasColumnType("boolean");
b.Property<DateTime?>("PremiumExpirationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("PrivateKey")
.HasColumnType("text");
b.Property<string>("PublicKey")
.HasColumnType("text");
b.Property<string>("ReferenceData")
.HasColumnType("text");
b.Property<DateTime?>("RenewalReminderDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<long?>("Storage")
.HasColumnType("bigint");
b.Property<string>("TwoFactorProviders")
.HasColumnType("text");
b.Property<string>("TwoFactorRecoveryCode")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<bool>("UsesKeyConnector")
.HasColumnType("boolean");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Ciphers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Ciphers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Cipher", "Cipher")
.WithMany("CollectionCiphers")
.HasForeignKey("CipherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionCiphers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cipher");
b.Navigation("Collection");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionGroups")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionUsers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("CollectionUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", null)
.WithMany("CollectionUsers")
.HasForeignKey("UserId");
b.Navigation("Collection");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.EmergencyAccess", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee")
.WithMany()
.HasForeignKey("GranteeId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor")
.WithMany()
.HasForeignKey("GrantorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Grantee");
b.Navigation("Grantor");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Folder", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Folders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Groups")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany("GroupUsers")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", null)
.WithMany("GroupUsers")
.HasForeignKey("UserId");
b.Navigation("Group");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Installation", "Installation")
.WithMany()
.HasForeignKey("InstallationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoredOrganization")
.WithMany()
.HasForeignKey("SponsoredOrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoringOrganization")
.WithMany()
.HasForeignKey("SponsoringOrganizationId");
b.Navigation("Installation");
b.Navigation("SponsoredOrganization");
b.Navigation("SponsoringOrganization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("OrganizationUsers")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("OrganizationUsers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Policies")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Provider");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoConfig", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoConfigs")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoUsers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("SsoUsers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Transactions")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Transactions")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.Navigation("CollectionCiphers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Navigation("CollectionCiphers");
b.Navigation("CollectionGroups");
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Navigation("Ciphers");
b.Navigation("Groups");
b.Navigation("OrganizationUsers");
b.Navigation("Policies");
b.Navigation("SsoConfigs");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Navigation("Ciphers");
b.Navigation("CollectionUsers");
b.Navigation("Folders");
b.Navigation("GroupUsers");
b.Navigation("OrganizationUsers");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
#pragma warning restore 612, 618
}
}
}
| FailedLoginCaptcha |
csharp | AutoMapper__AutoMapper | src/AutoMapper/Execution/ExpressionBuilder.cs | {
"start": 221,
"end": 22860
} | public static class ____
{
public static readonly MethodInfo ObjectToString = typeof(object).GetMethod(nameof(ToString));
public static readonly Expression True = Constant(true, typeof(bool));
public static readonly Expression Null = Expression.Default(typeof(object));
public static readonly Expression Empty = Empty();
public static readonly Expression Zero = Expression.Default(typeof(int));
public static readonly ParameterExpression ExceptionParameter = Parameter(typeof(Exception), "ex");
public static readonly ParameterExpression ContextParameter = Parameter(typeof(ResolutionContext), "context");
public static readonly MethodInfo IListClear = typeof(IList).GetMethod(nameof(IList.Clear));
static readonly MethodInfo ContextCreate = typeof(ResolutionContext).GetInstanceMethod(nameof(ResolutionContext.CreateInstance));
static readonly MethodInfo OverTypeDepthMethod = typeof(ResolutionContext).GetInstanceMethod(nameof(ResolutionContext.OverTypeDepth));
static readonly MethodCallExpression CheckContextCall = Expression.Call(
typeof(ResolutionContext).GetStaticMethod(nameof(ResolutionContext.CheckContext)), ContextParameter);
static readonly MethodInfo ContextMapMethod = typeof(ResolutionContext).GetInstanceMethod(nameof(ResolutionContext.MapInternal));
static readonly MethodInfo ArrayEmptyMethod = typeof(Array).GetStaticMethod(nameof(Array.Empty));
static readonly ParameterExpression Disposable = Variable(typeof(IDisposable), "disposableEnumerator");
static readonly ReadOnlyCollection<ParameterExpression> DisposableArray = Disposable.ToReadOnly();
static readonly MethodInfo DisposeMethod = typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose));
static readonly Expression DisposeCall = IfThen(ReferenceNotEqual(Disposable, Null), Expression.Call(Disposable, DisposeMethod));
static readonly ParameterExpression Index = Variable(typeof(int), "sourceArrayIndex");
static readonly BinaryExpression ResetIndex = Assign(Index, Zero);
static readonly UnaryExpression IncrementIndex = PostIncrementAssign(Index);
public static Expression ReplaceParameters(this IGlobalConfiguration configuration, LambdaExpression initialLambda, Expression newParameter) =>
configuration.ParameterReplaceVisitor().Replace(initialLambda, newParameter);
public static Expression ReplaceParameters(this IGlobalConfiguration configuration, LambdaExpression initialLambda, Expression[] newParameters) =>
configuration.ParameterReplaceVisitor().Replace(initialLambda, newParameters);
public static Expression ConvertReplaceParameters(this IGlobalConfiguration configuration, LambdaExpression initialLambda, Expression newParameter) =>
configuration.ConvertParameterReplaceVisitor().Replace(initialLambda, newParameter);
public static Expression ConvertReplaceParameters(this IGlobalConfiguration configuration, LambdaExpression initialLambda, Expression[] newParameters) =>
configuration.ConvertParameterReplaceVisitor().Replace(initialLambda, newParameters);
public static DefaultExpression Default(this IGlobalConfiguration configuration, Type type) =>
configuration == null ? Expression.Default(type) : configuration.GetDefault(type);
public static (List<ParameterExpression> Variables, List<Expression> Expressions) Scratchpad(this IGlobalConfiguration configuration)
{
var variables = configuration?.Variables;
if (variables == null)
{
variables = [];
}
else
{
variables.Clear();
}
var expressions = configuration?.Expressions;
if (expressions == null)
{
expressions = [];
}
else
{
expressions.Clear();
}
return (variables, expressions);
}
public static Expression MapExpression(this IGlobalConfiguration configuration, ProfileMap profileMap, TypePair typePair, Expression source,
MemberMap memberMap = null, Expression destination = null)
{
destination ??= configuration.Default(typePair.DestinationType);
var typeMap = configuration.ResolveTypeMap(typePair);
Expression mapExpression = null;
bool nullCheck;
if (typeMap != null)
{
typeMap.CheckProjection();
var allowNull = memberMap?.AllowNull;
nullCheck = !typeMap.HasTypeConverter && (destination.NodeType != ExpressionType.Default ||
(allowNull.HasValue && allowNull != profileMap.AllowNullDestinationValues));
if (!typeMap.HasDerivedTypesToInclude)
{
typeMap.Seal(configuration);
if (typeMap.MapExpression != null)
{
mapExpression = typeMap.Invoke(source, destination);
}
}
}
else
{
var mapper = configuration.FindMapper(typePair);
if (mapper != null)
{
mapExpression = mapper.MapExpression(configuration, profileMap, memberMap, source, destination);
nullCheck = mapExpression != source;
}
else
{
nullCheck = true;
}
}
mapExpression = mapExpression == null ? ContextMap(typePair, source, destination, memberMap) : ToType(mapExpression, typePair.DestinationType);
return nullCheck ? configuration.NullCheckSource(profileMap, source, destination, mapExpression, memberMap) : mapExpression;
}
public static Expression NullCheckSource(this IGlobalConfiguration configuration, ProfileMap profileMap, Expression source, Expression destination,
Expression mapExpression, MemberMap memberMap)
{
var sourceType = source.Type;
if (sourceType.IsValueType && !sourceType.IsNullableType())
{
return mapExpression;
}
var destinationType = destination.Type;
var isCollection = destinationType.IsCollection();
var mustUseDestination = memberMap is { MustUseDestination: true };
var ifSourceNull = memberMap == null ?
destination.IfNullElse(DefaultDestination(), ClearDestinationCollection()) :
mustUseDestination ? ClearDestinationCollection() : DefaultDestination();
return source.IfNullElse(ifSourceNull, mapExpression);
Expression ClearDestinationCollection()
{
if (!isCollection)
{
return destination;
}
MethodInfo clearMethod;
var destinationVariable = Variable(destination.Type, "collectionDestination");
Expression collection = destinationVariable;
if (destinationType.IsListType())
{
clearMethod = IListClear;
}
else
{
var destinationCollectionType = destinationType.GetICollectionType();
if (destinationCollectionType == null)
{
if (!mustUseDestination)
{
return destination;
}
var destinationElementType = GetEnumerableElementType(destinationType);
destinationCollectionType = typeof(ICollection<>).MakeGenericType(destinationElementType);
collection = TypeAs(collection, destinationCollectionType);
}
clearMethod = destinationCollectionType.GetMethod("Clear");
}
var (variables, statements) = configuration.Scratchpad();
variables.Add(destinationVariable);
statements.Add(Assign(destinationVariable, destination));
statements.Add(IfThen(ReferenceNotEqual(collection, Null), Expression.Call(collection, clearMethod)));
statements.Add(destinationVariable);
return Block(variables, statements);
}
Expression DefaultDestination()
{
if ((isCollection && profileMap.AllowsNullCollectionsFor(memberMap)) || (!isCollection && profileMap.AllowsNullDestinationValuesFor(memberMap)))
{
return destination.NodeType == ExpressionType.Default ? destination : configuration.Default(destinationType);
}
if (destinationType.IsArray)
{
var destinationElementType = destinationType.GetElementType();
var rank = destinationType.GetArrayRank();
return rank == 1 ?
Expression.Call(ArrayEmptyMethod.MakeGenericMethod(destinationElementType)) :
NewArrayBounds(destinationElementType, Enumerable.Repeat(Zero, rank));
}
return ObjectFactory.GenerateConstructorExpression(destinationType, configuration);
}
}
public static Expression ServiceLocator(Type type) => Expression.Call(ContextParameter, ContextCreate, Constant(type));
public static Expression ContextMap(TypePair typePair, Expression sourceParameter, Expression destinationParameter, MemberMap memberMap)
{
var mapMethod = ContextMapMethod.MakeGenericMethod(typePair.SourceType, typePair.DestinationType);
return Expression.Call(ContextParameter, mapMethod, sourceParameter, destinationParameter, Constant(memberMap, typeof(MemberMap)));
}
public static Expression CheckContext(TypeMap typeMap) => typeMap.PreserveReferences || typeMap.MaxDepth > 0 ? CheckContextCall : null;
public static Expression OverMaxDepth(TypeMap typeMap) => typeMap?.MaxDepth > 0 ?
Expression.Call(ContextParameter, OverTypeDepthMethod, Constant(typeMap)) : null;
public static Expression NullSubstitute(this MemberMap memberMap, Expression sourceExpression) =>
Coalesce(sourceExpression, ToType(Constant(memberMap.NullSubstitute), sourceExpression.Type));
public static Expression ApplyTransformers(this MemberMap memberMap, Expression source, IGlobalConfiguration configuration)
{
var perMember = memberMap.ValueTransformers;
var perMap = memberMap.TypeMap.ValueTransformers;
var perProfile = memberMap.Profile.ValueTransformers;
return perMember.Count > 0 || perMap.Count > 0 || perProfile.Count > 0 ?
memberMap.ApplyTransformers(source, configuration, perMember.Concat(perMap).Concat(perProfile)) : source;
}
static Expression ApplyTransformers(this MemberMap memberMap, Expression result, IGlobalConfiguration configuration, IEnumerable<ValueTransformerConfiguration> transformers)
{
foreach (var transformer in transformers)
{
if (transformer.IsMatch(memberMap))
{
result = ToType(configuration.ReplaceParameters(transformer.TransformerExpression, ToType(result, transformer.ValueType)), memberMap.DestinationType);
}
}
return result;
}
public static LambdaExpression Lambda(this MemberInfo member) => new[] { member }.Lambda();
public static LambdaExpression Lambda(this MemberInfo[] members)
{
var source = Parameter(members[0].DeclaringType, "source");
return Expression.Lambda(members.Chain(source), source);
}
public static Expression Chain(this MemberInfo[] members, Expression target)
{
foreach (var member in members)
{
target = member switch
{
PropertyInfo property => Expression.Property(target, property),
MethodInfo { IsStatic: true } getter => Expression.Call(getter, target),
FieldInfo field => Field(target, field),
MethodInfo getter => Expression.Call(target, getter),
_ => throw new ArgumentOutOfRangeException(nameof(member), member, "Unexpected member.")
};
}
return target;
}
public static MemberInfo[] GetMembersChain(this LambdaExpression lambda) => lambda.Body.GetChain().ToMemberInfos();
public static MemberInfo GetMember(this LambdaExpression lambda) =>
(lambda?.Body is MemberExpression memberExpression && memberExpression.Expression == lambda.Parameters[0]) ? memberExpression.Member : null;
public static MemberInfo[] ToMemberInfos(this Stack<Member> chain)
{
var members = new MemberInfo[chain.Count];
int index = 0;
foreach (var member in chain)
{
members[index++] = member.MemberInfo;
}
return members;
}
public static Stack<Member> GetChain(this Expression expression)
{
Stack<Member> stack = [];
while (expression != null)
{
var member = expression switch
{
MemberExpression { Expression: Expression target, Member: MemberInfo propertyOrField } =>
new Member(expression, propertyOrField, target),
MethodCallExpression { Method: var instanceMethod, Object: Expression target } =>
new Member(expression, instanceMethod, target),
MethodCallExpression { Method: var extensionMethod, Arguments: { Count: > 0 } arguments } when extensionMethod.Has<ExtensionAttribute>() =>
new Member(expression, extensionMethod, arguments[0]),
_ => default
};
if (member.Expression == null)
{
break;
}
stack.Push(member);
expression = member.Target;
}
return stack;
}
public static IEnumerable<MemberExpression> GetMemberExpressions(this Expression expression) => expression is MemberExpression ?
expression.GetChain().Select(m => m.Expression as MemberExpression).TakeWhile(m => m != null) : [];
public static bool IsMemberPath(this LambdaExpression lambda, out Stack<Member> members)
{
Expression currentExpression = null;
members = lambda.Body.GetChain();
foreach (var member in members)
{
currentExpression = member.Expression;
if (currentExpression is not MemberExpression)
{
return false;
}
}
return currentExpression == lambda.Body;
}
public static LambdaExpression MemberAccessLambda(Type type, string memberPath, TypeMap typeMap) =>
GetMemberPath(type, memberPath, typeMap).Lambda();
public static Expression ForEach(List<ParameterExpression> variables, List<Expression> statements, ParameterExpression loopVar, Expression collection, Expression loopContent)
{
if (collection.Type.IsArray)
{
return ForEachArrayItem(variables, statements, loopVar, collection, loopContent);
}
var getEnumeratorCall = Call(collection, "GetEnumerator");
var enumeratorVar = Variable(getEnumeratorCall.Type, "enumerator");
var breakLabel = Label("LoopBreak");
var usingEnumerator = Using(statements, enumeratorVar,
Loop(
IfThenElse(
Call(enumeratorVar, "MoveNext"),
Block(Assign(loopVar, ToType(Property(enumeratorVar, "Current"), loopVar.Type)), loopContent),
Break(breakLabel)
),
breakLabel));
statements.Clear();
variables.Add(enumeratorVar);
variables.Add(loopVar);
statements.Add(Assign(enumeratorVar, getEnumeratorCall));
statements.Add(usingEnumerator);
return Block(variables, statements);
static Expression ForEachArrayItem(List<ParameterExpression> variables, List<Expression> statements, ParameterExpression loopVar, Expression array, Expression loopContent)
{
var breakLabel = Label("LoopBreak");
variables.Add(Index);
variables.Add(loopVar);
statements.Add(ResetIndex);
statements.Add(Loop(
IfThenElse(
LessThan(Index, ArrayLength(array)),
Block(Assign(loopVar, ArrayIndex(array, Index)), loopContent, IncrementIndex),
Break(breakLabel)
),
breakLabel));
return Block(variables, statements);
}
static Expression Using(List<Expression> statements, Expression target, Expression body)
{
Expression finallyDispose;
if (typeof(IDisposable).IsAssignableFrom(target.Type))
{
finallyDispose = Expression.Call(target, DisposeMethod);
}
else
{
if (target.Type.IsValueType)
{
return body;
}
var assignDisposable = Assign(Disposable, TypeAs(target, typeof(IDisposable)));
statements.Add(assignDisposable);
statements.Add(DisposeCall);
finallyDispose = Block(DisposableArray, statements);
}
return TryFinally(body, finallyDispose);
}
}
// Expression.Property(string) is inefficient because it does a case insensitive match
public static MemberExpression Property(Expression target, string name) =>
Expression.Property(target, target.Type.GetInheritedProperty(name));
// Expression.Call(string) is inefficient because it does a case insensitive match
public static MethodCallExpression Call(Expression target, string name) => Expression.Call(target, target.Type.GetInheritedMethod(name));
public static MethodCallExpression Call(Expression target, string name, Expression[] arguments) =>
Expression.Call(target, target.Type.GetInheritedMethod(name), arguments);
public static Expression ToObject(this Expression expression) => expression.Type.IsValueType ? Convert(expression, typeof(object)) : expression;
public static Expression ToType(Expression expression, Type type) => expression.Type == type ? expression : Convert(expression, type);
public static Expression ReplaceParameters(this LambdaExpression initialLambda, Expression newParameter) =>
new ParameterReplaceVisitor().Replace(initialLambda, newParameter);
private static Expression Replace(this ParameterReplaceVisitor visitor, LambdaExpression initialLambda, Expression newParameter) =>
visitor.Replace(initialLambda.Body, initialLambda.Parameters[0], newParameter);
private static Expression Replace(this ParameterReplaceVisitor visitor, LambdaExpression initialLambda, Expression[] newParameters)
{
var newLambda = initialLambda.Body;
for (var i = 0; i < Math.Min(newParameters.Length, initialLambda.Parameters.Count); i++)
{
newLambda = visitor.Replace(newLambda, initialLambda.Parameters[i], newParameters[i]);
}
return newLambda;
}
public static Expression Replace(this Expression exp, Expression old, Expression replace) => new ReplaceVisitor().Replace(exp, old, replace);
public static Expression NullCheck(this Expression expression, IGlobalConfiguration configuration, MemberMap memberMap = null, Expression defaultValue = null, IncludedMember includedMember = null)
{
var chain = expression.GetChain();
var min = (includedMember ?? memberMap?.IncludedMember) == null ? 2 : 1;
if (chain.Count < min || chain.Peek().Target is not ParameterExpression parameter)
{
return expression;
}
var destinationType = memberMap?.DestinationType;
var returnType = (destinationType != null && destinationType != expression.Type && Nullable.GetUnderlyingType(destinationType) == expression.Type) ?
destinationType : expression.Type;
var defaultReturn = (defaultValue is { NodeType: ExpressionType.Default } && defaultValue.Type == returnType) ? defaultValue : configuration.Default(returnType);
List<ParameterExpression> variables = null;
List<Expression> expressions = null;
var name = parameter.Name;
var nullCheckedExpression = NullCheck(parameter);
if (variables == null)
{
return nullCheckedExpression;
}
expressions.Add(nullCheckedExpression);
return Block(variables, expressions);
Expression NullCheck(Expression variable)
{
var member = chain.Pop();
var skipNullCheck = min == 2 && variable == parameter;
if (chain.Count == 0)
{
var updated = UpdateTarget(expression, variable);
return skipNullCheck ? updated : variable.IfNullElse(defaultReturn, updated);
}
if (variables == null)
{
(variables, expressions) = configuration.Scratchpad();
}
name += member.MemberInfo.Name;
var newVariable = Variable(member.Expression.Type, name);
variables.Add(newVariable);
var assignment = Assign(newVariable, UpdateTarget(member.Expression, variable));
var block = Block(assignment, NullCheck(newVariable));
return skipNullCheck ? block : variable.IfNullElse(defaultReturn, block);
}
static Expression UpdateTarget(Expression sourceExpression, Expression newTarget) => sourceExpression switch
{
MemberExpression memberExpression => memberExpression.Update(newTarget),
MethodCallExpression { Object: null, Arguments: var args } methodCall when args[0] != newTarget =>
ExtensionMethod(methodCall.Method, newTarget, args),
MethodCallExpression { Object: Expression target } methodCall when target != newTarget =>
Expression.Call(newTarget, methodCall.Method, methodCall.Arguments),
_ => sourceExpression,
};
static MethodCallExpression ExtensionMethod(MethodInfo method, Expression newTarget, ReadOnlyCollection<Expression> args)
{
var newArgs = args.ToArray();
newArgs[0] = newTarget;
return Expression.Call(method, newArgs);
}
}
public static Expression IfNullElse(this Expression expression, Expression then, Expression @else) => expression.Type.IsValueType ?
(expression.Type.IsNullableType() ? Condition(Property(expression, "HasValue"), ToType(@else, then.Type), then) : @else) :
Condition(ReferenceEqual(expression, Null), then, ToType(@else, then.Type));
}
public readonly | ExpressionBuilder |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Build/TeamCity/Data/TeamCityBuildInfoTests.cs | {
"start": 1245,
"end": 3429
} | public sealed class ____
{
[Fact]
public void Should_Return_Correct_Value()
{
// Given
var info = new TeamCityInfoFixture().CreateBuildInfo();
// When
var result = info.StartDateTime;
// Then
var expected = new DateTimeOffset?(new DateTime(2020, 08, 22, 12, 34, 56, DateTimeKind.Local));
Assert.Equal(expected, result);
}
[Fact]
public void Should_Use_Build_Server_Local_Time()
{
// Given
var now = DateTime.Now;
var startDate = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
var startTime = now.ToString("HHmmss", CultureInfo.InvariantCulture);
var fixture = new TeamCityInfoFixture();
fixture.SetBuildStartDate(startDate);
fixture.SetBuildStartTime(startTime);
var info = fixture.CreateBuildInfo();
// When
var result = info.StartDateTime;
// Then
var expected = new DateTimeOffset?(new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Local));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, null)]
[InlineData("Cake", null)]
[InlineData(null, "Build")]
[InlineData("Cake", "Build")]
[InlineData("Cake", "123456")]
[InlineData("20200822", "Build")]
public void Should_Return_Null_If_Cannot_Parse_Values(string startDate, string startTime)
{
// Given
var fixture = new TeamCityInfoFixture();
fixture.SetBuildStartDate(startDate);
fixture.SetBuildStartTime(startTime);
var info = fixture.CreateBuildInfo();
// When
var result = info.StartDateTime;
// Then
Assert.Equal(null, result);
}
}
| TheStartDateTimeProperty |
csharp | NLog__NLog | src/NLog/SetupLoadConfigurationExtensions.cs | {
"start": 17343,
"end": 21275
} | interface ____.</param>
/// <param name="finalMinLevel">Only discard output from matching Logger when below minimum LogLevel</param>
public static void WriteToNil(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel? finalMinLevel = null)
{
var loggingRule = configBuilder.LoggingRule;
if (finalMinLevel != null)
{
if (loggingRule.Targets.Count == 0)
{
loggingRule = configBuilder.FilterMinLevel(finalMinLevel).LoggingRule;
}
loggingRule.FinalMinLevel = finalMinLevel;
}
else
{
if (loggingRule.Targets.Count == 0)
{
loggingRule = configBuilder.FilterMaxLevel(LogLevel.MaxLevel).LoggingRule;
}
if (loggingRule.Filters.Count == 0)
{
loggingRule.Final = true;
}
}
if (loggingRule.Filters.Count > 0)
{
if (loggingRule.FilterDefaultAction == FilterResult.Ignore)
{
loggingRule.FilterDefaultAction = FilterResult.IgnoreFinal;
}
for (int i = 0; i < loggingRule.Filters.Count; ++i)
{
if (loggingRule.Filters[i].Action == FilterResult.Ignore)
{
loggingRule.Filters[i].Action = FilterResult.IgnoreFinal;
}
}
if (loggingRule.Targets.Count == 0)
{
loggingRule.Targets.Add(new NullTarget());
}
}
if (!configBuilder.Configuration.LoggingRules.Contains(loggingRule))
{
configBuilder.Configuration.LoggingRules.Add(loggingRule);
}
}
/// <summary>
/// Returns first target registered
/// </summary>
public static Target FirstTarget(this ISetupConfigurationTargetBuilder configBuilder)
{
return System.Linq.Enumerable.First(configBuilder.Targets);
}
/// <summary>
/// Returns first target registered with the specified type
/// </summary>
/// <typeparam name="T">Type of target</typeparam>
public static T FirstTarget<T>(this ISetupConfigurationTargetBuilder configBuilder) where T : Target
{
var target = System.Linq.Enumerable.First(configBuilder.Targets);
for (int i = 0; i < configBuilder.Targets.Count; ++i)
{
foreach (var unwrappedTarget in YieldAllTargets(configBuilder.Targets[i]))
{
if (unwrappedTarget is T typedTarget)
return typedTarget;
}
}
throw new InvalidCastException($"Unable to cast object of type '{target.GetType()}' to type '{typeof(T)}'");
}
internal static IEnumerable<Target> YieldAllTargets(Target? target)
{
if (target is not null)
yield return target;
if (target is WrapperTargetBase wrapperTarget)
{
foreach (var unwrappedTarget in YieldAllTargets(wrapperTarget.WrappedTarget))
yield return unwrappedTarget;
}
else if (target is CompoundTargetBase compoundTarget)
{
foreach (var nestedTarget in compoundTarget.Targets)
{
foreach (var unwrappedTarget in YieldAllTargets(nestedTarget))
yield return unwrappedTarget;
}
}
}
/// <summary>
/// Write to <see cref="NLog.Targets.MethodCallTarget"/>
/// </summary>
/// <param name="configBuilder">Fluent | parameter |
csharp | dotnetcore__FreeSql | Providers/FreeSql.Provider.Odbc/Default/OdbcProvider.cs | {
"start": 304,
"end": 4096
} | public class ____<TMark> : BaseDbProvider, IFreeSql<TMark>
{
public override ISelect<T1> CreateSelectProvider<T1>(object dywhere) => new OdbcSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public override IInsert<T1> CreateInsertProvider<T1>() => new OdbcInsert<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression);
public override IUpdate<T1> CreateUpdateProvider<T1>(object dywhere) => new OdbcUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public override IDelete<T1> CreateDeleteProvider<T1>(object dywhere) => new OdbcDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public override IInsertOrUpdate<T1> CreateInsertOrUpdateProvider<T1>() => throw new NotImplementedException();
public override IDbFirst DbFirst => throw new NotImplementedException($"FreeSql.Odbc.Default {CoreErrorStrings.S_Not_Implemented_Feature}");
/// <summary>
/// 生成一个普通访问功能的 IFreeSql 对象,用来访问 odbc
/// </summary>
/// <param name="masterConnectionString"></param>
/// <param name="slaveConnectionString"></param>
/// <param name="adapter">适配器</param>
public OdbcProvider(string masterConnectionString, string[] slaveConnectionString, Func<DbConnection> connectionFactory = null)
{
this.InternalCommonUtils = new OdbcUtils(this);
this.InternalCommonExpression = new OdbcExpression(this.InternalCommonUtils);
this.Ado = new OdbcAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString, connectionFactory);
this.Aop = new AopProvider();
this.CodeFirst = new OdbcCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression);
var _utils = InternalCommonUtils as OdbcUtils;
//处理 MaxLength
this.Aop.ConfigEntityProperty += new EventHandler<Aop.ConfigEntityPropertyEventArgs>((s, e) =>
{
object[] attrs = null;
try
{
attrs = e.Property.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
}
catch { }
var maxlenAttr = attrs.Where(a => {
return ((a as Attribute)?.TypeId as Type)?.Name == "MaxLengthAttribute";
}).FirstOrDefault();
if (maxlenAttr != null)
{
var lenProp = maxlenAttr.GetType().GetProperties().Where(a => a.PropertyType.IsNumberType()).FirstOrDefault();
if (lenProp != null && int.TryParse(string.Concat(lenProp.GetValue(maxlenAttr, null)), out var tryval))
{
if (tryval != 0)
{
switch (this.Ado.DataType)
{
case DataType.Sqlite:
e.ModifyResult.DbType = tryval > 0 ? $"{_utils.Adapter.MappingOdbcTypeVarChar}({tryval})" : _utils.Adapter.MappingOdbcTypeText;
break;
}
}
}
}
});
}
~OdbcProvider() => this.Dispose();
int _disposeCounter;
public override void Dispose()
{
if (Interlocked.Increment(ref _disposeCounter) != 1) return;
try
{
(this.Ado as AdoProvider)?.Dispose();
}
finally
{
FreeSqlOdbcGlobalExtensions._dicOdbcAdater.TryRemove(Ado.Identifier, out var tryada);
}
}
}
}
| OdbcProvider |
csharp | reactiveui__ReactiveUI | src/ReactiveUI/Platforms/apple-common/ReactiveViewController.cs | {
"start": 847,
"end": 5357
} | public class ____ : NSViewController, IReactiveNotifyPropertyChanged<ReactiveViewController>, IHandleObservableErrors, IReactiveObject, ICanActivate
{
private readonly Subject<Unit> _activated = new();
private readonly Subject<Unit> _deactivated = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveViewController"/> class.
/// </summary>
protected ReactiveViewController()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveViewController"/> class.
/// </summary>
/// <param name="c">The coder.</param>
protected ReactiveViewController(NSCoder c)
: base(c)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveViewController"/> class.
/// </summary>
/// <param name="f">The object flag.</param>
protected ReactiveViewController(NSObjectFlag f)
: base(f)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveViewController"/> class.
/// </summary>
/// <param name="handle">The pointer.</param>
protected ReactiveViewController(in IntPtr handle)
: base(handle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveViewController"/> class.
/// </summary>
/// <param name="nibNameOrNull">The name.</param>
/// <param name="nibBundleOrNull">The bundle.</param>
protected ReactiveViewController(string nibNameOrNull, NSBundle nibBundleOrNull)
: base(nibNameOrNull, nibBundleOrNull)
{
}
/// <inheritdoc/>
public event PropertyChangingEventHandler? PropertyChanging;
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveViewController>> Changing => this.GetChangingObservable();
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveViewController>> Changed => this.GetChangedObservable();
/// <inheritdoc/>
public IObservable<Exception> ThrownExceptions => this.GetThrownExceptionsObservable();
/// <inheritdoc/>
public IObservable<Unit> Activated => _activated.AsObservable();
/// <inheritdoc/>
public IObservable<Unit> Deactivated => _deactivated.AsObservable();
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) => PropertyChanging?.Invoke(this, args);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
/// <summary>
/// When this method is called, an object will not fire change
/// notifications (neither traditional nor Observable notifications)
/// until the return value is disposed.
/// </summary>
/// <returns>An object that, when disposed, reenables change
/// notifications.</returns>
public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this);
#if UIKIT
/// <inheritdoc/>
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
_activated.OnNext(Unit.Default);
this.ActivateSubviews(true);
}
/// <inheritdoc/>
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
_deactivated.OnNext(Unit.Default);
this.ActivateSubviews(false);
}
#else
/// <inheritdoc/>
public override void ViewWillAppear()
{
base.ViewWillAppear();
_activated.OnNext(Unit.Default);
this.ActivateSubviews(true);
}
/// <inheritdoc/>
public override void ViewDidDisappear()
{
base.ViewDidDisappear();
_deactivated.OnNext(Unit.Default);
this.ActivateSubviews(false);
}
#endif
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_activated?.Dispose();
_deactivated?.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>
/// This is a View that is both a NSViewController and has ReactiveObject powers
/// (i.e. you can call RaiseAndSetIfChanged).
/// </summary>
/// <typeparam name="TViewModel">The view model type.</typeparam>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same | ReactiveViewController |
csharp | dotnet__aspire | src/Aspire.Hosting/api/Aspire.Hosting.cs | {
"start": 114501,
"end": 114613
} | public enum ____
{
Enabled = 0,
Disabled = 1,
Hidden = 2
}
| ResourceCommandState |
csharp | dotnet__maui | src/Essentials/src/MediaPicker/MediaPicker.ios.cs | {
"start": 408,
"end": 12878
} | partial class ____ : IMediaPicker
{
static UIViewController PickerRef;
public bool IsCaptureSupported
=> UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera);
public Task<FileResult> PickPhotoAsync(MediaPickerOptions options)
=> PhotoAsync(options, true, true);
public Task<List<FileResult>> PickPhotosAsync(MediaPickerOptions options)
=> PhotosAsync(options, true, true);
public Task<FileResult> CapturePhotoAsync(MediaPickerOptions options)
{
if (!IsCaptureSupported)
{
throw new FeatureNotSupportedException();
}
return PhotoAsync(options, true, false);
}
public Task<FileResult> PickVideoAsync(MediaPickerOptions options)
=> PhotoAsync(options, false, true);
public Task<List<FileResult>> PickVideosAsync(MediaPickerOptions options)
=> PhotosAsync(options, false, true);
public Task<FileResult> CaptureVideoAsync(MediaPickerOptions options)
{
if (!IsCaptureSupported)
{
throw new FeatureNotSupportedException();
}
return PhotoAsync(options, false, false);
}
public async Task<FileResult> PhotoAsync(MediaPickerOptions options, bool photo, bool pickExisting)
{
if (!photo && !pickExisting)
{
await Permissions.EnsureGrantedAsync<Permissions.Microphone>();
}
// Check if picking existing or not and ensure permission accordingly as they can be set independently from each other
if (pickExisting && !OperatingSystem.IsIOSVersionAtLeast(11, 0))
{
await Permissions.EnsureGrantedAsync<Permissions.Photos>();
}
if (!pickExisting)
{
await Permissions.EnsureGrantedAsync<Permissions.Camera>();
}
var vc = WindowStateManager.Default.GetCurrentUIViewController(true);
var tcs = new TaskCompletionSource<FileResult>();
if (pickExisting && OperatingSystem.IsIOSVersionAtLeast(14, 0))
{
var config = new PHPickerConfiguration
{
Filter = photo
? PHPickerFilter.ImagesFilter
: PHPickerFilter.VideosFilter
};
var picker = new PHPickerViewController(config)
{
Delegate = new Media.PhotoPickerDelegate
{
CompletedHandler = res =>
tcs.TrySetResult(PickerResultsToMediaFile(res))
}
};
PickerRef = picker;
}
else
{
if (!pickExisting)
{
await Permissions.EnsureGrantedAsync<Permissions.PhotosAddOnly>();
}
var sourceType = pickExisting
? UIImagePickerControllerSourceType.PhotoLibrary
: UIImagePickerControllerSourceType.Camera;
var mediaType = photo ? UTType.Image : UTType.Movie;
if (!UIImagePickerController.IsSourceTypeAvailable(sourceType))
{
tcs.TrySetCanceled();
throw new FeatureNotSupportedException();
}
if (!UIImagePickerController.AvailableMediaTypes(sourceType).Contains(mediaType))
{
tcs.TrySetCanceled();
throw new FeatureNotSupportedException();
}
var picker = new UIImagePickerController
{
SourceType = sourceType,
MediaTypes = [mediaType],
AllowsEditing = false
};
if (!photo && !pickExisting)
{
picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
}
PickerRef = picker;
picker.Delegate = new PhotoPickerDelegate
{
CompletedHandler = async info =>
{
GetFileResult(info, tcs, options);
await picker.DismissViewControllerAsync(true);
}
};
}
if (!string.IsNullOrWhiteSpace(options?.Title))
{
PickerRef.Title = options.Title;
}
if (DeviceInfo.Idiom == DeviceIdiom.Tablet)
{
PickerRef.ModalPresentationStyle = UIModalPresentationStyle.PageSheet;
}
if (PickerRef.PresentationController is not null)
{
PickerRef.PresentationController.Delegate = new PhotoPickerPresentationControllerDelegate
{
Handler = () => tcs.TrySetResult(null)
};
}
await vc.PresentViewControllerAsync(PickerRef, true);
var result = await tcs.Task;
PickerRef?.Dispose();
PickerRef = null;
return result;
}
async Task<List<FileResult>> PhotosAsync(MediaPickerOptions options, bool photo, bool pickExisting)
{
// iOS 14+ only supports multiple selection
// TODO throw exception?
if (!OperatingSystem.IsIOSVersionAtLeast(14, 0))
{
return null;
}
if (!photo && !pickExisting)
{
await Permissions.EnsureGrantedAsync<Permissions.Microphone>();
}
// Check if picking existing or not and ensure permission accordingly as they can be set independently from each other
if (pickExisting && !OperatingSystem.IsIOSVersionAtLeast(11, 0))
{
await Permissions.EnsureGrantedAsync<Permissions.Photos>();
}
if (!pickExisting)
{
await Permissions.EnsureGrantedAsync<Permissions.Camera>();
}
var vc = WindowStateManager.Default.GetCurrentUIViewController(true);
var tcs = new TaskCompletionSource<List<FileResult>>();
if (pickExisting)
{
var config = new PHPickerConfiguration
{
Filter = photo
? PHPickerFilter.ImagesFilter
: PHPickerFilter.VideosFilter,
SelectionLimit = options?.SelectionLimit ?? 1,
};
var picker = new PHPickerViewController(config)
{
Delegate = new Media.PhotoPickerDelegate
{
CompletedHandler = async res =>
{
var result = await PickerResultsToMediaFiles(res, options);
tcs.TrySetResult(result);
}
}
};
PickerRef = picker;
}
if (!string.IsNullOrWhiteSpace(options?.Title))
{
PickerRef.Title = options.Title;
}
if (DeviceInfo.Idiom == DeviceIdiom.Tablet)
{
PickerRef.ModalPresentationStyle = UIModalPresentationStyle.PageSheet;
}
if (PickerRef.PresentationController is not null)
{
PickerRef.PresentationController.Delegate = new PhotoPickerPresentationControllerDelegate
{
Handler = () => tcs.TrySetResult(null)
};
}
await vc.PresentViewControllerAsync(PickerRef, true);
var result = await tcs.Task;
PickerRef?.Dispose();
PickerRef = null;
return result;
}
static FileResult PickerResultsToMediaFile(PHPickerResult[] results)
{
var file = results?.FirstOrDefault();
return file == null
? null
: new PHPickerFileResult(file.ItemProvider);
}
static async Task<List<FileResult>> PickerResultsToMediaFiles(PHPickerResult[] results, MediaPickerOptions options = null)
{
var fileResults = results?
.Select(file => (FileResult)new PHPickerFileResult(file.ItemProvider))
.ToList() ?? [];
// Apply rotation if needed for images
if (ImageProcessor.IsRotationNeeded(options))
{
var rotatedResults = new List<FileResult>();
foreach (var result in fileResults)
{
try
{
using var originalStream = await result.OpenReadAsync();
using var rotatedStream = await ImageProcessor.RotateImageAsync(originalStream, result.FileName);
// Create a temp file for the rotated image
var tempFileName = $"{Guid.NewGuid()}{Path.GetExtension(result.FileName)}";
var tempFilePath = Path.Combine(Path.GetTempPath(), tempFileName);
using (var fileStream = File.Create(tempFilePath))
{
rotatedStream.Position = 0;
await rotatedStream.CopyToAsync(fileStream);
}
rotatedResults.Add(new FileResult(tempFilePath, result.FileName));
}
catch
{
// If rotation fails, use the original file
rotatedResults.Add(result);
}
}
fileResults = rotatedResults;
}
// Apply resizing and compression if specified and dealing with images
if (ImageProcessor.IsProcessingNeeded(options?.MaximumWidth, options?.MaximumHeight, options?.CompressionQuality ?? 100))
{
var compressedResults = new List<FileResult>();
foreach (var result in fileResults)
{
var compressedResult = await CompressedUIImageFileResult.CreateCompressedFromFileResult(result, options?.MaximumWidth, options?.MaximumHeight, options?.CompressionQuality ?? 100, options?.RotateImage ?? false, options?.PreserveMetaData ?? true);
compressedResults.Add(compressedResult);
}
return compressedResults;
}
return fileResults;
}
static void GetFileResult(NSDictionary info, TaskCompletionSource<FileResult> tcs, MediaPickerOptions options = null)
{
try
{
tcs.TrySetResult(DictionaryToMediaFile(info, options));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
static FileResult DictionaryToMediaFile(NSDictionary info, MediaPickerOptions options = null)
{
// This method should only be called for iOS < 14
if (!OperatingSystem.IsIOSVersionAtLeast(14))
{
return null;
}
if (info is null)
{
return null;
}
PHAsset phAsset = null;
NSUrl assetUrl = null;
if (OperatingSystem.IsIOSVersionAtLeast(11, 0))
{
assetUrl = info[UIImagePickerController.ImageUrl] as NSUrl;
// Try the MediaURL sometimes used for videos
assetUrl ??= info[UIImagePickerController.MediaURL] as NSUrl;
if (assetUrl is not null)
{
if (!assetUrl.Scheme.Equals("assets-library", StringComparison.OrdinalIgnoreCase))
{
var docResult = new UIDocumentFileResult(assetUrl);
// Apply rotation if needed and this is a photo
if (ImageProcessor.IsRotationNeeded(options) && IsImageFile(docResult.FileName))
{
try
{
var rotatedResult = RotateImageFile(docResult).GetAwaiter().GetResult();
if (rotatedResult != null)
return rotatedResult;
}
catch
{
// If rotation fails, continue with the original file
}
}
return docResult;
}
phAsset = info.ValueForKey(UIImagePickerController.PHAsset) as PHAsset;
}
}
#if !MACCATALYST
if (phAsset is null)
{
assetUrl = info[UIImagePickerController.ReferenceUrl] as NSUrl;
if (assetUrl is not null)
{
phAsset = PHAsset.FetchAssets([assetUrl], null)?.LastObject as PHAsset;
}
}
#endif
if (phAsset is null || assetUrl is null)
{
var img = info.ValueForKey(UIImagePickerController.OriginalImage) as UIImage;
if (img is not null)
{
// Apply rotation if needed for the UIImage
if (ImageProcessor.IsRotationNeeded(options) && img.Orientation != UIImageOrientation.Up)
{
img = img.NormalizeOrientation();
}
return new CompressedUIImageFileResult(img, null, options?.MaximumWidth, options?.MaximumHeight, options?.CompressionQuality ?? 100);
}
}
if (phAsset is null || assetUrl is null)
{
return null;
}
string originalFilename = PHAssetResource.GetAssetResources(phAsset).FirstOrDefault()?.OriginalFilename;
var assetResult = new PHAssetFileResult(assetUrl, phAsset, originalFilename);
// Apply rotation if needed and this is a photo
if (ImageProcessor.IsRotationNeeded(options) && IsImageFile(assetResult.FileName))
{
try
{
var rotatedResult = RotateImageFile(assetResult).GetAwaiter().GetResult();
if (rotatedResult != null)
return rotatedResult;
}
catch
{
// If rotation fails, continue with the original file
}
}
return assetResult;
}
// Helper method to check if a file is an image based on extension
static bool IsImageFile(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
var ext = Path.GetExtension(fileName)?.ToLowerInvariant();
return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".heic" || ext == ".heif";
}
// Helper method to rotate an image file
static async Task<FileResult> RotateImageFile(FileResult original)
{
if (original == null)
return null;
try
{
using var originalStream = await original.OpenReadAsync();
using var rotatedStream = await ImageProcessor.RotateImageAsync(originalStream, original.FileName);
// Create a temp file for the rotated image
var tempFileName = $"{Guid.NewGuid()}{Path.GetExtension(original.FileName)}";
var tempFilePath = Path.Combine(Path.GetTempPath(), tempFileName);
using (var fileStream = File.Create(tempFilePath))
{
rotatedStream.Position = 0;
await rotatedStream.CopyToAsync(fileStream);
}
return new FileResult(tempFilePath, original.FileName);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error rotating image: {ex.Message}");
return original;
}
}
| MediaPickerImplementation |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Marten/test/Data.Marten.Filters.Tests/QueryableFilterVisitorExecutableTests.cs | {
"start": 152,
"end": 4171
} | public class ____
{
private static readonly Foo[] s_fooEntities =
[
new() { Bar = true },
new() { Bar = false }
];
private static readonly FooNullable[] s_fooNullableEntities =
[
new() { Bar = true },
new() { Bar = null },
new() { Bar = false }
];
private readonly SchemaCache _cache;
public QueryableFilterVisitorExecutableTests(SchemaCache cache)
{
_cache = cache;
}
[Fact]
public async Task Create_BooleanEqual_Expression()
{
// arrange
var tester = await _cache.CreateSchemaAsync<Foo, FooFilterInput>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { eq: true}}){ bar}}")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { eq: false}}){ bar}}")
.Build());
// assert
await Snapshot.Create().AddResult(res1, "true").AddResult(res2, "false")
.MatchAsync();
}
[Fact]
public async Task Create_BooleanNotEqual_Expression()
{
// arrange
var tester = await _cache.CreateSchemaAsync<Foo, FooFilterInput>(s_fooEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { neq: true}}){ bar}}")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { neq: false}}){ bar}}")
.Build());
// assert
await Snapshot
.Create().AddResult(res1, "true").AddResult(res2, "false")
.MatchAsync();
}
[Fact]
public async Task Create_NullableBooleanEqual_Expression()
{
// arrange
var tester = await _cache.CreateSchemaAsync<FooNullable, FooNullableFilterInput>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { eq: true}}){ bar}}")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { eq: false}}){ bar}}")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { eq: null}}){ bar}}")
.Build());
// assert
await Snapshot
.Create()
.AddResult(res1, "true")
.AddResult(res2, "false")
.AddResult(res3, "null")
.MatchAsync();
}
[Fact]
public async Task Create_NullableBooleanNotEqual_Expression()
{
// arrange
var tester = await _cache.CreateSchemaAsync<FooNullable, FooNullableFilterInput>(s_fooNullableEntities);
// act
var res1 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { neq: true}}){ bar}}")
.Build());
var res2 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { neq: false}}){ bar}}")
.Build());
var res3 = await tester.ExecuteAsync(
OperationRequestBuilder.New()
.SetDocument("{ rootExecutable(where: { bar: { neq: null}}){ bar}}")
.Build());
// assert
await Snapshot
.Create().AddResult(res1, "true").AddResult(res2, "false").AddResult(res3, "null")
.MatchAsync();
}
| QueryableFilterVisitorExecutableTests |
csharp | bitwarden__server | src/Api/AdminConsole/Models/Response/Providers/ProviderUserResponseModel.cs | {
"start": 2067,
"end": 2467
} | public class ____ : ResponseModel
{
public ProviderUserPublicKeyResponseModel(Guid id, Guid userId, string key,
string obj = "providerUserPublicKeyResponseModel") : base(obj)
{
Id = id;
UserId = userId;
Key = key;
}
public Guid Id { get; set; }
public Guid UserId { get; set; }
public string Key { get; set; }
}
| ProviderUserPublicKeyResponseModel |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/PublishContentViewModel.cs | {
"start": 97,
"end": 515
} | public class ____
// {
// public PublishContentViewModel(ContentItem contentItem)
// {
// ContentItem = contentItem;
// }
// public ContentItem ContentItem { get; private set; }
// public bool HasDraft { get; }
// public bool HasPublished { get; }
// //ContentItem.ContentManager.Get(ContentItem.Id, VersionOptions.Published) != null;
// }
// }
| PublishContentViewModel |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/StaticAccessorTests.cs | {
"start": 65,
"end": 182
} | public class ____
{
public string Base { get; set; }
public string BaseField;
}
| AccessorBase |
csharp | icsharpcode__SharpZipLib | src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs | {
"start": 10567,
"end": 11213
} | record ____ data stream.
/// </summary>
/// <returns>
/// false if End-Of-File, else true.
/// </returns>
private async ValueTask<bool> ReadRecordAsync(CancellationToken ct, bool isAsync)
{
if (inputStream == null)
{
throw new TarException("no input stream defined");
}
currentBlockIndex = 0;
int offset = 0;
int bytesNeeded = RecordSize;
while (bytesNeeded > 0)
{
long numBytes = isAsync
? await inputStream.ReadAsync(recordBuffer, offset, bytesNeeded, ct).ConfigureAwait(false)
: inputStream.Read(recordBuffer, offset, bytesNeeded);
//
// NOTE
// We have found EOF, and the | from |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Commands/Handler/Newsletter/SubscriptionActivationHandler.cs | {
"start": 264,
"end": 1727
} | public class ____ : IRequestHandler<SubscriptionActivationCommand, SubscriptionActivationModel>
{
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ITranslationService _translationService;
public SubscriptionActivationHandler(INewsLetterSubscriptionService newsLetterSubscriptionService,
ITranslationService translationService)
{
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_translationService = translationService;
}
public async Task<SubscriptionActivationModel> Handle(SubscriptionActivationCommand request,
CancellationToken cancellationToken)
{
var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByGuid(request.Token);
if (subscription == null)
return null;
var model = new SubscriptionActivationModel();
if (request.Active)
{
subscription.Active = true;
await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
}
else
{
await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription);
}
model.Result = request.Active
? _translationService.GetResource("Newsletter.ResultActivated")
: _translationService.GetResource("Newsletter.ResultDeactivated");
return model;
}
} | SubscriptionActivationHandler |
csharp | dotnet__maui | src/Controls/tests/ManualTests/Views/Scrolling/IncrementalLoadingPage.xaml.cs | {
"start": 93,
"end": 530
} | public partial class ____ : ContentPage
{
public IncrementalLoadingPage()
{
InitializeComponent();
BindingContext = new AnimalsViewModel();
}
void OnCollectionViewRemainingItemsThresholdReached(object sender, EventArgs e)
{
// Retrieve more data here, or via the RemainingItemsThresholdReachedCommand.
// This sample retrieves more data using the RemainingItemsThresholdReachedCommand.
}
}
}
| IncrementalLoadingPage |
csharp | jbogard__MediatR | src/MediatR/Wrappers/NotificationHandlerWrapper.cs | {
"start": 496,
"end": 1203
} | public class ____<TNotification> : NotificationHandlerWrapper
where TNotification : INotification
{
public override Task Handle(INotification notification, IServiceProvider serviceFactory,
Func<IEnumerable<NotificationHandlerExecutor>, INotification, CancellationToken, Task> publish,
CancellationToken cancellationToken)
{
var handlers = serviceFactory
.GetServices<INotificationHandler<TNotification>>()
.Select(static x => new NotificationHandlerExecutor(x, (theNotification, theToken) => x.Handle((TNotification)theNotification, theToken)));
return publish(handlers, notification, cancellationToken);
}
} | NotificationHandlerWrapperImpl |
csharp | unoplatform__uno | src/SourceGenerators/System.Xaml/System.Xaml/XamlSchemaContextSettings.cs | {
"start": 1315,
"end": 1886
} | public class ____
{
public XamlSchemaContextSettings ()
{
}
public XamlSchemaContextSettings (XamlSchemaContextSettings settings)
{
// null is allowed.
var s = settings;
if (s == null)
return;
FullyQualifyAssemblyNamesInClrNamespaces = s.FullyQualifyAssemblyNamesInClrNamespaces;
SupportMarkupExtensionsWithDuplicateArity = s.SupportMarkupExtensionsWithDuplicateArity;
}
public bool FullyQualifyAssemblyNamesInClrNamespaces { get; set; }
public bool SupportMarkupExtensionsWithDuplicateArity { get; set; }
}
}
| XamlSchemaContextSettings |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Markup.UnitTests/Data/MultiBindingTests.cs | {
"start": 7230,
"end": 7586
} | private partial class ____ : NotifyingBase
{
private object? _notifyingValue;
public int? NonNotifyingValue { get; set; } = 0;
public object? NotifyingValue
{
get => _notifyingValue;
set => SetField(ref _notifyingValue, value);
}
}
| TestModel |
csharp | AutoMapper__AutoMapper | src/UnitTests/Bug/ConstructorParameterNamedType.cs | {
"start": 121,
"end": 693
} | public class ____
{
public DestinationClass() { }
public DestinationClass(int type)
{
Type = type;
}
public int Type { get; private set; }
}
[Fact]
public void Should_handle_constructor_parameter_named_type()
{
var config = new MapperConfiguration(c => c.CreateMap<SourceClass, DestinationClass>());
new Action(config.AssertConfigurationIsValid).ShouldThrowException<AutoMapperConfigurationException>(ex=>ex.Errors[0].UnmappedPropertyNames[0].ShouldBe("Type"));
}
} | DestinationClass |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Services/ITokenCreationService.cs | {
"start": 283,
"end": 564
} | public interface ____
{
/// <summary>
/// Creates a token.
/// </summary>
/// <param name="token">The token description.</param>
/// <returns>A protected and serialized security token</returns>
Task<string> CreateTokenAsync(Token token);
}
| ITokenCreationService |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/Specifications/server-selection/ServerSelectionTestHelpers.cs | {
"start": 2378,
"end": 6227
} | private sealed class ____
{
public ServerData[] servers { get; set; }
public ClusterTypeTest type { get; set; }
}
public static ClusterDescription BuildClusterDescription(
BsonDocument topologyDescriptionDocument,
TimeSpan? heartbeatInterval = null)
{
var clusterId = new ClusterId();
heartbeatInterval = heartbeatInterval ?? TimeSpan.FromMilliseconds(500);
var topologyDescription = BsonSerializer.Deserialize<TopologyDescription>(topologyDescriptionDocument);
var clusterType = GetClusterType(topologyDescription);
var servers = topologyDescription.servers.Select(x => BuildServerDescription(x, clusterId, heartbeatInterval.Value)).ToArray();
return new ClusterDescription(clusterId, false, null, clusterType, servers);
}
// private methods
private static ClusterType GetClusterType(TopologyDescription topologyDescription) =>
topologyDescription.type switch
{
ClusterTypeTest.ReplicaSetNoPrimary or
ClusterTypeTest.ReplicaSetWithPrimary => ClusterType.ReplicaSet,
ClusterTypeTest.Sharded => ClusterType.Sharded,
ClusterTypeTest.Single => ClusterType.Standalone,
ClusterTypeTest.Unknown => ClusterType.Unknown,
ClusterTypeTest.LoadBalanced => ClusterType.LoadBalanced,
_ => throw new NotSupportedException($"Unknown topology type: {topologyDescription.type}")
};
public static List<ServerDescription> BuildServerDescriptions(BsonArray bsonArray, ClusterId clusterId, TimeSpan heartbeatInterval) =>
bsonArray.Select(x => BuildServerDescription(BsonSerializer.Deserialize<ServerData>((BsonDocument)x), clusterId, heartbeatInterval))
.ToList();
private static ServerDescription BuildServerDescription(
ServerData serverData,
ClusterId clusterId,
TimeSpan heartbeatInterval)
{
var utcNow = DateTime.UtcNow;
var endPoint = EndPointHelper.Parse(serverData.address);
var averageRoundTripTime = TimeSpan.FromMilliseconds(serverData.avg_rtt_ms);
var type = (ServerType)serverData.type;
var tagSet = BuildTagSet(serverData);
var lastWriteTimestamp = serverData.lastWrite != null ? BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverData.lastWrite.lastWriteDate) : utcNow;
var lastUpdateTimestamp = serverData.lastUpdateTime != null ? BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverData.lastUpdateTime.Value) : utcNow;
var maxWireVersion = serverData.maxWireVersion ?? 8;
var wireVersionRange = new Range<int>(0, maxWireVersion);
var serverVersion = new SemanticVersion(4, 2, 0);
var serverId = new ServerId(clusterId, endPoint);
return new ServerDescription(
serverId,
endPoint,
averageRoundTripTime: averageRoundTripTime,
type: type,
lastUpdateTimestamp: lastUpdateTimestamp,
lastWriteTimestamp: lastWriteTimestamp,
heartbeatInterval: heartbeatInterval,
wireVersionRange: wireVersionRange,
version: serverVersion,
tags: tagSet,
state: ServerState.Connected);
}
private static TagSet BuildTagSet(ServerData serverData)
{
TagSet result = null;
if (serverData.tags != null)
{
return new TagSet(serverData.tags.Select(x => new Tag(x.Key.ToString(), x.Value)));
}
return result;
}
}
}
| TopologyDescription |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Media/GradientBrushTests/GradientsPage.cs | {
"start": 317,
"end": 425
} | partial class ____ : Page
{
public GradientsPage()
{
this.InitializeComponent();
}
}
}
| GradientsPage |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/Utils/DateTimeSerializerTests.cs | {
"start": 29900,
"end": 32232
} | public class ____
{
static readonly TimeSpan Time1Y1M1H1S1MS = TimeSpan.FromDays(365)
.Add(TimeSpan.FromHours(1))
.Add(TimeSpan.FromMinutes(1))
.Add(TimeSpan.FromSeconds(1))
.Add(TimeSpan.FromMilliseconds(1));
[Test]
public void Can_Parse_XSD_Times()
{
Assert.That("P365D".FromJson<TimeSpan>(), Is.EqualTo(TimeSpan.FromDays(365)));
Assert.That("P365DT1H1M1.001S".FromJson<TimeSpan>(), Is.EqualTo(Time1Y1M1H1S1MS));
}
[Test]
public void Can_Parse_TimeSpan_Strings()
{
Assert.That("365.00:00:00".FromJson<TimeSpan>(), Is.EqualTo(TimeSpan.FromDays(365)));
Assert.That("365.01:01:01.001".FromJson<TimeSpan>(), Is.EqualTo(Time1Y1M1H1S1MS));
}
[Test]
public void Can_Parse_TimeSpan_NSTimeSpan()
{
var culture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Assert.That("31536000".FromJson<TimeSpan>(), Is.EqualTo(TimeSpan.FromDays(365)));
Assert.That("31539661.001".FromJson<TimeSpan>(), Is.EqualTo(Time1Y1M1H1S1MS));
}
[Test]
public void Can_Parse_TimeSpan_NSTimeSpan_DifferentCulture()
{
var culture = new CultureInfo("sl-SI");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Assert.That("31536000".FromJson<TimeSpan>(), Is.EqualTo(TimeSpan.FromDays(365)));
Assert.That("31539661.001".FromJson<TimeSpan>(), Is.EqualTo(Time1Y1M1H1S1MS));
}
[Test]
public void Does_not_lose_precision()
{
Assert.Multiple(() =>
{
for (int i = 1; i <= 999; i++)
{
TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, i);
string json = JsonSerializer.SerializeToString(timeSpan);
TimeSpan timeSpanAfter = JsonSerializer.DeserializeFromString<TimeSpan>(json);
Assert.AreEqual(TimeSpan.FromMilliseconds(i), timeSpanAfter);
}
});
}
}
[TestFixture]
| TimeSpanTests |
csharp | jellyfin__jellyfin | MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | {
"start": 1205,
"end": 57236
} | public partial class ____ : IMediaEncoder, IDisposable
{
/// <summary>
/// The default SDR image extraction timeout in milliseconds.
/// </summary>
internal const int DefaultSdrImageExtractionTimeout = 10000;
/// <summary>
/// The default HDR image extraction timeout in milliseconds.
/// </summary>
internal const int DefaultHdrImageExtractionTimeout = 20000;
private readonly ILogger<MediaEncoder> _logger;
private readonly IServerConfigurationManager _configurationManager;
private readonly IFileSystem _fileSystem;
private readonly ILocalizationManager _localization;
private readonly IBlurayExaminer _blurayExaminer;
private readonly IConfiguration _config;
private readonly IServerConfigurationManager _serverConfig;
private readonly string _startupOptionFFmpegPath;
private readonly AsyncNonKeyedLocker _thumbnailResourcePool;
private readonly Lock _runningProcessesLock = new();
private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
// MediaEncoder is registered as a Singleton
private readonly JsonSerializerOptions _jsonSerializerOptions;
private List<string> _encoders = new List<string>();
private List<string> _decoders = new List<string>();
private List<string> _hwaccels = new List<string>();
private List<string> _filters = new List<string>();
private IDictionary<FilterOptionType, bool> _filtersWithOption = new Dictionary<FilterOptionType, bool>();
private IDictionary<BitStreamFilterOptionType, bool> _bitStreamFiltersWithOption = new Dictionary<BitStreamFilterOptionType, bool>();
private bool _isPkeyPauseSupported = false;
private bool _isLowPriorityHwDecodeSupported = false;
private bool _proberSupportsFirstVideoFrame = false;
private bool _isVaapiDeviceAmd = false;
private bool _isVaapiDeviceInteliHD = false;
private bool _isVaapiDeviceInteli965 = false;
private bool _isVaapiDeviceSupportVulkanDrmModifier = false;
private bool _isVaapiDeviceSupportVulkanDrmInterop = false;
private bool _isVideoToolboxAv1DecodeAvailable = false;
private static string[] _vulkanImageDrmFmtModifierExts =
{
"VK_EXT_image_drm_format_modifier",
};
private static string[] _vulkanExternalMemoryDmaBufExts =
{
"VK_KHR_external_memory_fd",
"VK_EXT_external_memory_dma_buf",
"VK_KHR_external_semaphore_fd",
"VK_EXT_external_memory_host"
};
private Version _ffmpegVersion = null;
private string _ffmpegPath = string.Empty;
private string _ffprobePath;
private int _threads;
public MediaEncoder(
ILogger<MediaEncoder> logger,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IBlurayExaminer blurayExaminer,
ILocalizationManager localization,
IConfiguration config,
IServerConfigurationManager serverConfig)
{
_logger = logger;
_configurationManager = configurationManager;
_fileSystem = fileSystem;
_blurayExaminer = blurayExaminer;
_localization = localization;
_config = config;
_serverConfig = serverConfig;
_startupOptionFFmpegPath = config.GetValue<string>(Controller.Extensions.ConfigurationExtensions.FfmpegPathKey) ?? string.Empty;
_jsonSerializerOptions = new JsonSerializerOptions(JsonDefaults.Options);
_jsonSerializerOptions.Converters.Add(new JsonBoolStringConverter());
// Although the type is not nullable, this might still be null during unit tests
var semaphoreCount = serverConfig.Configuration?.ParallelImageEncodingLimit ?? 0;
if (semaphoreCount < 1)
{
semaphoreCount = Environment.ProcessorCount;
}
_thumbnailResourcePool = new(semaphoreCount);
}
/// <inheritdoc />
public string EncoderPath => _ffmpegPath;
/// <inheritdoc />
public string ProbePath => _ffprobePath;
/// <inheritdoc />
public Version EncoderVersion => _ffmpegVersion;
/// <inheritdoc />
public bool IsPkeyPauseSupported => _isPkeyPauseSupported;
/// <inheritdoc />
public bool IsVaapiDeviceAmd => _isVaapiDeviceAmd;
/// <inheritdoc />
public bool IsVaapiDeviceInteliHD => _isVaapiDeviceInteliHD;
/// <inheritdoc />
public bool IsVaapiDeviceInteli965 => _isVaapiDeviceInteli965;
/// <inheritdoc />
public bool IsVaapiDeviceSupportVulkanDrmModifier => _isVaapiDeviceSupportVulkanDrmModifier;
/// <inheritdoc />
public bool IsVaapiDeviceSupportVulkanDrmInterop => _isVaapiDeviceSupportVulkanDrmInterop;
public bool IsVideoToolboxAv1DecodeAvailable => _isVideoToolboxAv1DecodeAvailable;
[GeneratedRegex(@"[^\/\\]+?(\.[^\/\\\n.]+)?$")]
private static partial Regex FfprobePathRegex();
/// <summary>
/// Run at startup to validate ffmpeg.
/// Sets global variables FFmpegPath.
/// Precedence is: CLI/Env var > Config > $PATH.
/// </summary>
/// <returns>bool indicates whether a valid ffmpeg is found.</returns>
public bool SetFFmpegPath()
{
var skipValidation = _config.GetFFmpegSkipValidation();
if (skipValidation)
{
_logger.LogWarning("FFmpeg: Skipping FFmpeg Validation due to FFmpeg:novalidation set to true");
return true;
}
// 1) Check if the --ffmpeg CLI switch has been given
var ffmpegPath = _startupOptionFFmpegPath;
string ffmpegPathSetMethodText = "command line or environment variable";
if (string.IsNullOrEmpty(ffmpegPath))
{
// 2) Custom path stored in config/encoding xml file under tag <EncoderAppPath> should be used as a fallback
ffmpegPath = _configurationManager.GetEncodingOptions().EncoderAppPath;
ffmpegPathSetMethodText = "encoding.xml config file";
if (string.IsNullOrEmpty(ffmpegPath))
{
// 3) Check "ffmpeg"
ffmpegPath = "ffmpeg";
ffmpegPathSetMethodText = "system $PATH";
}
}
if (!ValidatePath(ffmpegPath))
{
_ffmpegPath = null;
_logger.LogError("FFmpeg: Path set by {FfmpegPathSetMethodText} is invalid", ffmpegPathSetMethodText);
return false;
}
// Write the FFmpeg path to the config/encoding.xml file as <EncoderAppPathDisplay> so it appears in UI
var options = _configurationManager.GetEncodingOptions();
options.EncoderAppPathDisplay = _ffmpegPath ?? string.Empty;
_configurationManager.SaveConfiguration("encoding", options);
// Only if mpeg path is set, try and set path to probe
if (_ffmpegPath is not null)
{
// Determine a probe path from the mpeg path
_ffprobePath = FfprobePathRegex().Replace(_ffmpegPath, "ffprobe$1");
// Interrogate to understand what coders are supported
var validator = new EncoderValidator(_logger, _ffmpegPath);
SetAvailableDecoders(validator.GetDecoders());
SetAvailableEncoders(validator.GetEncoders());
SetAvailableFilters(validator.GetFilters());
SetAvailableFiltersWithOption(validator.GetFiltersWithOption());
SetAvailableBitStreamFiltersWithOption(validator.GetBitStreamFiltersWithOption());
SetAvailableHwaccels(validator.GetHwaccels());
SetMediaEncoderVersion(validator);
_threads = EncodingHelper.GetNumberOfThreads(null, options, null);
_isPkeyPauseSupported = validator.CheckSupportedRuntimeKey("p pause transcoding", _ffmpegVersion);
_isLowPriorityHwDecodeSupported = validator.CheckSupportedHwaccelFlag("low_priority");
_proberSupportsFirstVideoFrame = validator.CheckSupportedProberOption("only_first_vframe", _ffprobePath);
// Check the Vaapi device vendor
if (OperatingSystem.IsLinux()
&& SupportsHwaccel("vaapi")
&& !string.IsNullOrEmpty(options.VaapiDevice)
&& options.HardwareAccelerationType == HardwareAccelerationType.vaapi)
{
_isVaapiDeviceAmd = validator.CheckVaapiDeviceByDriverName("Mesa Gallium driver", options.VaapiDevice);
_isVaapiDeviceInteliHD = validator.CheckVaapiDeviceByDriverName("Intel iHD driver", options.VaapiDevice);
_isVaapiDeviceInteli965 = validator.CheckVaapiDeviceByDriverName("Intel i965 driver", options.VaapiDevice);
_isVaapiDeviceSupportVulkanDrmModifier = validator.CheckVulkanDrmDeviceByExtensionName(options.VaapiDevice, _vulkanImageDrmFmtModifierExts);
_isVaapiDeviceSupportVulkanDrmInterop = validator.CheckVulkanDrmDeviceByExtensionName(options.VaapiDevice, _vulkanExternalMemoryDmaBufExts);
if (_isVaapiDeviceAmd)
{
_logger.LogInformation("VAAPI device {RenderNodePath} is AMD GPU", options.VaapiDevice);
}
else if (_isVaapiDeviceInteliHD)
{
_logger.LogInformation("VAAPI device {RenderNodePath} is Intel GPU (iHD)", options.VaapiDevice);
}
else if (_isVaapiDeviceInteli965)
{
_logger.LogInformation("VAAPI device {RenderNodePath} is Intel GPU (i965)", options.VaapiDevice);
}
if (_isVaapiDeviceSupportVulkanDrmModifier)
{
_logger.LogInformation("VAAPI device {RenderNodePath} supports Vulkan DRM modifier", options.VaapiDevice);
}
if (_isVaapiDeviceSupportVulkanDrmInterop)
{
_logger.LogInformation("VAAPI device {RenderNodePath} supports Vulkan DRM interop", options.VaapiDevice);
}
}
// Check if VideoToolbox supports AV1 decode
if (OperatingSystem.IsMacOS() && SupportsHwaccel("videotoolbox"))
{
_isVideoToolboxAv1DecodeAvailable = validator.CheckIsVideoToolboxAv1DecodeAvailable();
}
}
_logger.LogInformation("FFmpeg: {FfmpegPath}", _ffmpegPath ?? string.Empty);
return !string.IsNullOrWhiteSpace(ffmpegPath);
}
/// <summary>
/// Validates the supplied FQPN to ensure it is a ffmpeg utility.
/// If checks pass, global variable FFmpegPath is updated.
/// </summary>
/// <param name="path">FQPN to test.</param>
/// <returns><c>true</c> if the version validation succeeded; otherwise, <c>false</c>.</returns>
private bool ValidatePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
bool rc = new EncoderValidator(_logger, path).ValidateVersion();
if (!rc)
{
_logger.LogError("FFmpeg: Failed version check: {Path}", path);
return false;
}
_ffmpegPath = path;
return true;
}
private string GetEncoderPathFromDirectory(string path, string filename, bool recursive = false)
{
try
{
var files = _fileSystem.GetFilePaths(path, recursive);
return files.FirstOrDefault(i => Path.GetFileNameWithoutExtension(i.AsSpan()).Equals(filename, StringComparison.OrdinalIgnoreCase)
&& !Path.GetExtension(i.AsSpan()).Equals(".c", StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
// Trap all exceptions, like DirNotExists, and return null
return null;
}
}
public void SetAvailableEncoders(IEnumerable<string> list)
{
_encoders = list.ToList();
}
public void SetAvailableDecoders(IEnumerable<string> list)
{
_decoders = list.ToList();
}
public void SetAvailableHwaccels(IEnumerable<string> list)
{
_hwaccels = list.ToList();
}
public void SetAvailableFilters(IEnumerable<string> list)
{
_filters = list.ToList();
}
public void SetAvailableFiltersWithOption(IDictionary<FilterOptionType, bool> dict)
{
_filtersWithOption = dict;
}
public void SetAvailableBitStreamFiltersWithOption(IDictionary<BitStreamFilterOptionType, bool> dict)
{
_bitStreamFiltersWithOption = dict;
}
public void SetMediaEncoderVersion(EncoderValidator validator)
{
_ffmpegVersion = validator.GetFFmpegVersion();
}
/// <inheritdoc />
public bool SupportsEncoder(string encoder)
{
return _encoders.Contains(encoder, StringComparer.OrdinalIgnoreCase);
}
/// <inheritdoc />
public bool SupportsDecoder(string decoder)
{
return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase);
}
/// <inheritdoc />
public bool SupportsHwaccel(string hwaccel)
{
return _hwaccels.Contains(hwaccel, StringComparer.OrdinalIgnoreCase);
}
/// <inheritdoc />
public bool SupportsFilter(string filter)
{
return _filters.Contains(filter, StringComparer.OrdinalIgnoreCase);
}
/// <inheritdoc />
public bool SupportsFilterWithOption(FilterOptionType option)
{
return _filtersWithOption.TryGetValue(option, out var val) && val;
}
public bool SupportsBitStreamFilterWithOption(BitStreamFilterOptionType option)
{
return _bitStreamFiltersWithOption.TryGetValue(option, out var val) && val;
}
public bool CanEncodeToAudioCodec(string codec)
{
if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
{
codec = "libopus";
}
else if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
{
codec = "libmp3lame";
}
return SupportsEncoder(codec);
}
public bool CanEncodeToSubtitleCodec(string codec)
{
// TODO
return true;
}
/// <inheritdoc />
public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
{
var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
var extraArgs = GetExtraArguments(request);
return GetMediaInfoInternal(
GetInputArgument(request.MediaSource.Path, request.MediaSource),
request.MediaSource.Path,
request.MediaSource.Protocol,
extractChapters,
extraArgs,
request.MediaType == DlnaProfileType.Audio,
request.MediaSource.VideoType,
cancellationToken);
}
internal string GetExtraArguments(MediaInfoRequest request)
{
var ffmpegAnalyzeDuration = _config.GetFFmpegAnalyzeDuration() ?? string.Empty;
var ffmpegProbeSize = _config.GetFFmpegProbeSize() ?? string.Empty;
var analyzeDuration = string.Empty;
var extraArgs = string.Empty;
if (request.MediaSource.AnalyzeDurationMs > 0)
{
analyzeDuration = "-analyzeduration " + (request.MediaSource.AnalyzeDurationMs * 1000);
}
else if (!string.IsNullOrEmpty(ffmpegAnalyzeDuration))
{
analyzeDuration = "-analyzeduration " + ffmpegAnalyzeDuration;
}
if (!string.IsNullOrEmpty(analyzeDuration))
{
extraArgs = analyzeDuration;
}
if (!string.IsNullOrEmpty(ffmpegProbeSize))
{
extraArgs += " -probesize " + ffmpegProbeSize;
}
if (request.MediaSource.RequiredHttpHeaders.TryGetValue("User-Agent", out var userAgent))
{
extraArgs += $" -user_agent \"{userAgent}\"";
}
if (request.MediaSource.Protocol == MediaProtocol.Rtsp)
{
extraArgs += " -rtsp_transport tcp+udp -rtsp_flags prefer_tcp";
}
return extraArgs;
}
/// <inheritdoc />
public string GetInputArgument(IReadOnlyList<string> inputFiles, MediaSourceInfo mediaSource)
{
return EncodingUtils.GetInputArgument("file", inputFiles, mediaSource.Protocol);
}
/// <inheritdoc />
public string GetInputArgument(string inputFile, MediaSourceInfo mediaSource)
{
var prefix = "file";
if (mediaSource.IsoType == IsoType.BluRay)
{
prefix = "bluray";
}
return EncodingUtils.GetInputArgument(prefix, new[] { inputFile }, mediaSource.Protocol);
}
/// <inheritdoc />
public string GetExternalSubtitleInputArgument(string inputFile)
{
const string Prefix = "file";
return EncodingUtils.GetInputArgument(Prefix, new[] { inputFile }, MediaProtocol.File);
}
/// <summary>
/// Gets the media info internal.
/// </summary>
/// <returns>Task{MediaInfoResult}.</returns>
private async Task<MediaInfo> GetMediaInfoInternal(
string inputPath,
string primaryPath,
MediaProtocol protocol,
bool extractChapters,
string probeSizeArgument,
bool isAudio,
VideoType? videoType,
CancellationToken cancellationToken)
{
var args = extractChapters
? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format"
: "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format";
if (!isAudio && _proberSupportsFirstVideoFrame)
{
args += " -show_frames -only_first_vframe";
}
args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, _threads).Trim();
var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
// Must consume both or ffmpeg may hang due to deadlocks.
RedirectStandardOutput = true,
FileName = _ffprobePath,
Arguments = args,
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false,
},
EnableRaisingEvents = true
};
_logger.LogDebug("Starting {ProcessFileName} with args {ProcessArgs}", _ffprobePath, args);
var memoryStream = new MemoryStream();
await using (memoryStream.ConfigureAwait(false))
using (var processWrapper = new ProcessWrapper(process, this))
{
StartProcess(processWrapper);
using var reader = process.StandardOutput;
await reader.BaseStream.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
memoryStream.Seek(0, SeekOrigin.Begin);
InternalMediaInfoResult result;
try
{
result = await JsonSerializer.DeserializeAsync<InternalMediaInfoResult>(
memoryStream,
_jsonSerializerOptions,
cancellationToken).ConfigureAwait(false);
}
catch
{
StopProcess(processWrapper, 100);
throw;
}
if (result is null || (result.Streams is null && result.Format is null))
{
throw new FfmpegException("ffprobe failed - streams and format are both null.");
}
if (result.Streams is not null)
{
// Normalize aspect ratio if invalid
foreach (var stream in result.Streams)
{
if (string.Equals(stream.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
{
stream.DisplayAspectRatio = string.Empty;
}
if (string.Equals(stream.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
{
stream.SampleAspectRatio = string.Empty;
}
}
}
return new ProbeResultNormalizer(_logger, _localization).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
}
}
/// <inheritdoc />
public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken)
{
var mediaSource = new MediaSourceInfo
{
Protocol = MediaProtocol.File
};
return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, ImageFormat.Jpg, cancellationToken);
}
/// <inheritdoc />
public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
{
return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, ImageFormat.Jpg, cancellationToken);
}
/// <inheritdoc />
public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, ImageFormat? targetFormat, CancellationToken cancellationToken)
{
return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, targetFormat, cancellationToken);
}
private async Task<string> ExtractImage(
string inputFile,
string container,
MediaStream videoStream,
int? imageStreamIndex,
MediaSourceInfo mediaSource,
bool isAudio,
Video3DFormat? threedFormat,
TimeSpan? offset,
ImageFormat? targetFormat,
CancellationToken cancellationToken)
{
var inputArgument = GetInputPathArgument(inputFile, mediaSource);
if (!isAudio)
{
try
{
return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, targetFormat, false, cancellationToken).ConfigureAwait(false);
}
catch (ArgumentException)
{
throw;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments}", inputArgument);
}
}
return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, targetFormat, isAudio, cancellationToken).ConfigureAwait(false);
}
private string GetImageResolutionParameter()
{
var imageResolutionParameter = _serverConfig.Configuration.ChapterImageResolution switch
{
ImageResolution.P144 => "256x144",
ImageResolution.P240 => "426x240",
ImageResolution.P360 => "640x360",
ImageResolution.P480 => "854x480",
ImageResolution.P720 => "1280x720",
ImageResolution.P1080 => "1920x1080",
ImageResolution.P1440 => "2560x1440",
ImageResolution.P2160 => "3840x2160",
_ => string.Empty
};
if (!string.IsNullOrEmpty(imageResolutionParameter))
{
imageResolutionParameter = " -s " + imageResolutionParameter;
}
return imageResolutionParameter;
}
private async Task<string> ExtractImageInternal(
string inputPath,
string container,
MediaStream videoStream,
int? imageStreamIndex,
Video3DFormat? threedFormat,
TimeSpan? offset,
bool useIFrame,
ImageFormat? targetFormat,
bool isAudio,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(inputPath);
var useTradeoff = _config.GetFFmpegImgExtractPerfTradeoff();
var outputExtension = targetFormat?.GetExtension() ?? ".jpg";
var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + outputExtension);
Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));
// deint -> scale -> thumbnail -> tonemap.
// put the SW tonemap right after the thumbnail to do it only once to reduce cpu usage.
var filters = new List<string>();
// deinterlace using bwdif algorithm for video stream.
if (videoStream is not null && videoStream.IsInterlaced)
{
filters.Add("bwdif=0:-1:0");
}
// apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar.
// This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
var scaler = threedFormat switch
{
// hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
Video3DFormat.HalfSideBySide => @"crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,setsar=sar=1",
// fsbs crop width in half,set the display aspect,crop out any black bars we may have made
Video3DFormat.FullSideBySide => @"crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,setsar=sar=1",
// htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made
Video3DFormat.HalfTopAndBottom => @"crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,setsar=sar=1",
// ftab crop height in half, set the display aspect,crop out any black bars we may have made
Video3DFormat.FullTopAndBottom => @"crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,setsar=sar=1",
_ => "scale=round(iw*sar/2)*2:round(ih/2)*2"
};
filters.Add(scaler);
// Use ffmpeg to sample N frames and pick the best thumbnail. Have a fall back just in case.
var enableThumbnail = !useTradeoff && useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase);
if (enableThumbnail)
{
filters.Add("thumbnail=n=24");
}
// Use SW tonemap on HDR video stream only when the zscale or tonemapx filter is available.
// Only enable Dolby Vision tonemap when tonemapx is available
var enableHdrExtraction = false;
if (videoStream?.VideoRange == VideoRange.HDR)
{
if (SupportsFilter("tonemapx"))
{
var peak = videoStream.VideoRangeType == VideoRangeType.DOVI ? "400" : "100";
enableHdrExtraction = true;
filters.Add($"tonemapx=tonemap=bt2390:desat=0:peak={peak}:t=bt709:m=bt709:p=bt709:format=yuv420p:range=full");
}
else if (SupportsFilter("zscale") && videoStream.VideoRangeType != VideoRangeType.DOVI)
{
enableHdrExtraction = true;
filters.Add("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709:out_range=full,format=yuv420p");
}
}
var vf = string.Join(',', filters);
var mapArg = imageStreamIndex.HasValue ? (" -map 0:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
var args = string.Format(
CultureInfo.InvariantCulture,
"-i {0}{1} -threads {2} -v quiet -vframes 1 -vf {3}{4}{5} -f image2 \"{6}\"",
inputPath,
mapArg,
_threads,
vf,
isAudio ? string.Empty : GetImageResolutionParameter(),
EncodingHelper.GetVideoSyncOption("-1", EncoderVersion), // auto decide fps mode
tempExtractPath);
if (offset.HasValue)
{
args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args;
}
// The mpegts demuxer cannot seek to keyframes, so we have to let the
// decoder discard non-keyframes, which may contain corrupted images.
var seekMpegTs = offset.HasValue && string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase);
if (useIFrame && (useTradeoff || seekMpegTs))
{
args = "-skip_frame nokey " + args;
}
if (!string.IsNullOrWhiteSpace(container))
{
var inputFormat = EncodingHelper.GetInputFormat(container);
if (!string.IsNullOrWhiteSpace(inputFormat))
{
args = "-f " + inputFormat + " " + args;
}
}
var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = _ffmpegPath,
Arguments = args,
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false,
},
EnableRaisingEvents = true
};
_logger.LogDebug("{ProcessFileName} {ProcessArguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
using (var processWrapper = new ProcessWrapper(process, this))
{
using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
StartProcess(processWrapper);
var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs;
if (timeoutMs <= 0)
{
timeoutMs = enableHdrExtraction ? DefaultHdrImageExtractionTimeout : DefaultSdrImageExtractionTimeout;
}
try
{
await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false);
}
catch (OperationCanceledException ex)
{
process.Kill(true);
throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction timed out for {0} after {1}ms", inputPath, timeoutMs), ex);
}
}
var file = _fileSystem.GetFileInfo(tempExtractPath);
if (processWrapper.ExitCode > 0 || !file.Exists || file.Length == 0)
{
throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputPath));
}
return tempExtractPath;
}
}
/// <inheritdoc />
public async Task<string> ExtractVideoImagesOnIntervalAccelerated(
string inputFile,
string container,
MediaSourceInfo mediaSource,
MediaStream imageStream,
int maxWidth,
TimeSpan interval,
bool allowHwAccel,
bool enableHwEncoding,
int? threads,
int? qualityScale,
ProcessPriorityClass? priority,
bool enableKeyFrameOnlyExtraction,
EncodingHelper encodingHelper,
CancellationToken cancellationToken)
{
var options = allowHwAccel ? _configurationManager.GetEncodingOptions() : new EncodingOptions();
threads ??= _threads;
if (allowHwAccel && enableKeyFrameOnlyExtraction)
{
var hardwareAccelerationType = options.HardwareAccelerationType;
var supportsKeyFrameOnly = (hardwareAccelerationType == HardwareAccelerationType.nvenc && options.EnableEnhancedNvdecDecoder)
|| (hardwareAccelerationType == HardwareAccelerationType.amf && OperatingSystem.IsWindows())
|| (hardwareAccelerationType == HardwareAccelerationType.qsv && options.PreferSystemNativeHwDecoder)
|| hardwareAccelerationType == HardwareAccelerationType.vaapi
|| hardwareAccelerationType == HardwareAccelerationType.videotoolbox
|| hardwareAccelerationType == HardwareAccelerationType.rkmpp;
if (!supportsKeyFrameOnly)
{
// Disable hardware acceleration when the hardware decoder does not support keyframe only mode.
allowHwAccel = false;
options = new EncodingOptions();
}
}
// A new EncodingOptions instance must be used as to not disable HW acceleration for all of Jellyfin.
// Additionally, we must set a few fields without defaults to prevent null pointer exceptions.
if (!allowHwAccel)
{
options.EnableHardwareEncoding = false;
options.HardwareAccelerationType = HardwareAccelerationType.none;
options.EnableTonemapping = false;
}
if (imageStream.Width is not null && imageStream.Height is not null && !string.IsNullOrEmpty(imageStream.AspectRatio))
{
// For hardware trickplay encoders, we need to re-calculate the size because they used fixed scale dimensions
var darParts = imageStream.AspectRatio.Split(':');
var (wa, ha) = (double.Parse(darParts[0], CultureInfo.InvariantCulture), double.Parse(darParts[1], CultureInfo.InvariantCulture));
// When dimension / DAR does not equal to 1:1, then the frames are most likely stored stretched.
// Note: this might be incorrect for 3D videos as the SAR stored might be per eye instead of per video, but we really can do little about it.
var shouldResetHeight = Math.Abs((imageStream.Width.Value * ha) - (imageStream.Height.Value * wa)) > .05;
if (shouldResetHeight)
{
// SAR = DAR * Height / Width
// RealHeight = Height / SAR = Height / (DAR * Height / Width) = Width / DAR
imageStream.Height = Convert.ToInt32(imageStream.Width.Value * ha / wa);
}
}
var baseRequest = new BaseEncodingJobOptions { MaxWidth = maxWidth, MaxFramerate = (float)(1.0 / interval.TotalSeconds) };
var jobState = new EncodingJobInfo(TranscodingJobType.Progressive)
{
IsVideoRequest = true, // must be true for InputVideoHwaccelArgs to return non-empty value
MediaSource = mediaSource,
VideoStream = imageStream,
BaseRequest = baseRequest, // GetVideoProcessingFilterParam errors if null
MediaPath = inputFile,
OutputVideoCodec = "mjpeg"
};
var vidEncoder = enableHwEncoding ? encodingHelper.GetVideoEncoder(jobState, options) : jobState.OutputVideoCodec;
// Get input and filter arguments
var inputArg = encodingHelper.GetInputArgument(jobState, options, container).Trim();
if (string.IsNullOrWhiteSpace(inputArg))
{
throw new InvalidOperationException("EncodingHelper returned empty input arguments.");
}
if (!allowHwAccel)
{
inputArg = "-threads " + threads + " " + inputArg; // HW accel args set a different input thread count, only set if disabled
}
if (options.HardwareAccelerationType == HardwareAccelerationType.videotoolbox && _isLowPriorityHwDecodeSupported)
{
// VideoToolbox supports low priority decoding, which is useful for trickplay
inputArg = "-hwaccel_flags +low_priority " + inputArg;
}
var filterParam = encodingHelper.GetVideoProcessingFilterParam(jobState, options, vidEncoder).Trim();
if (string.IsNullOrWhiteSpace(filterParam))
{
throw new InvalidOperationException("EncodingHelper returned empty or invalid filter parameters.");
}
try
{
return await ExtractVideoImagesOnIntervalInternal(
(enableKeyFrameOnlyExtraction ? "-skip_frame nokey " : string.Empty) + inputArg,
filterParam,
vidEncoder,
threads,
qualityScale,
priority,
cancellationToken).ConfigureAwait(false);
}
catch (FfmpegException ex)
{
if (!enableKeyFrameOnlyExtraction)
{
throw;
}
_logger.LogWarning(ex, "I-frame trickplay extraction failed, will attempt standard way. Input: {InputFile}", inputFile);
}
return await ExtractVideoImagesOnIntervalInternal(inputArg, filterParam, vidEncoder, threads, qualityScale, priority, cancellationToken).ConfigureAwait(false);
}
private async Task<string> ExtractVideoImagesOnIntervalInternal(
string inputArg,
string filterParam,
string vidEncoder,
int? outputThreads,
int? qualityScale,
ProcessPriorityClass? priority,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(inputArg))
{
throw new InvalidOperationException("Empty or invalid input argument.");
}
// ffmpeg qscale is a value from 1-31, with 1 being best quality and 31 being worst
// jpeg quality is a value from 0-100, with 0 being worst quality and 100 being best
var encoderQuality = Math.Clamp(qualityScale ?? 4, 1, 31);
var encoderQualityOption = "-qscale:v ";
if (vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase)
|| vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase))
{
// vaapi and qsv's mjpeg encoder use jpeg quality as input, instead of ffmpeg defined qscale
encoderQuality = 100 - ((encoderQuality - 1) * (100 / 30));
encoderQualityOption = "-global_quality:v ";
}
if (vidEncoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase))
{
// videotoolbox's mjpeg encoder uses jpeg quality scaled to QP2LAMBDA (118) instead of ffmpeg defined qscale
encoderQuality = 118 - ((encoderQuality - 1) * (118 / 30));
}
if (vidEncoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase))
{
// rkmpp's mjpeg encoder uses jpeg quality as input (max is 99, not 100), instead of ffmpeg defined qscale
encoderQuality = 99 - ((encoderQuality - 1) * (99 / 30));
encoderQualityOption = "-qp_init:v ";
}
// Output arguments
var targetDirectory = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(targetDirectory);
var outputPath = Path.Combine(targetDirectory, "%08d.jpg");
// Final command arguments
var args = string.Format(
CultureInfo.InvariantCulture,
"-loglevel error {0} -an -sn {1} -threads {2} -c:v {3} {4}{5}{6}-f {7} \"{8}\"",
inputArg,
filterParam,
outputThreads.GetValueOrDefault(_threads),
vidEncoder,
encoderQualityOption + encoderQuality + " ",
vidEncoder.Contains("videotoolbox", StringComparison.InvariantCultureIgnoreCase) ? "-allow_sw 1 " : string.Empty, // allow_sw fallback for some intel macs
EncodingHelper.GetVideoSyncOption("0", EncoderVersion).Trim() + " ", // passthrough timestamp
"image2",
outputPath);
// Start ffmpeg process
var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = _ffmpegPath,
Arguments = args,
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false,
},
EnableRaisingEvents = true
};
var processDescription = string.Format(CultureInfo.InvariantCulture, "{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
_logger.LogInformation("Trickplay generation: {ProcessDescription}", processDescription);
using (var processWrapper = new ProcessWrapper(process, this))
{
bool ranToCompletion = false;
using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
StartProcess(processWrapper);
// Set process priority
if (priority.HasValue)
{
try
{
processWrapper.Process.PriorityClass = priority.Value;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Unable to set process priority to {Priority} for {Description}", priority.Value, processDescription);
}
}
// Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
// but we still need to detect if the process hangs.
// Making the assumption that as long as new jpegs are showing up, everything is good.
bool isResponsive = true;
int lastCount = 0;
var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs;
timeoutMs = timeoutMs <= 0 ? DefaultHdrImageExtractionTimeout : timeoutMs;
while (isResponsive && !cancellationToken.IsCancellationRequested)
{
try
{
await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false);
ranToCompletion = true;
break;
}
catch (OperationCanceledException)
{
// We don't actually expect the process to be finished in one timeout span, just that one image has been generated.
}
var jpegCount = _fileSystem.GetFilePaths(targetDirectory).Count();
isResponsive = jpegCount > lastCount;
lastCount = jpegCount;
}
if (!ranToCompletion)
{
if (!isResponsive)
{
_logger.LogInformation("Trickplay process unresponsive.");
}
_logger.LogInformation("Stopping trickplay extraction.");
StopProcess(processWrapper, 1000);
}
}
if (!ranToCompletion || processWrapper.ExitCode != 0)
{
// Cleanup temp folder here, because the targetDirectory is not returned and the cleanup for failed ffmpeg process is not possible for caller.
// Ideally the ffmpeg should not write any files if it fails, but it seems like it is not guaranteed.
try
{
Directory.Delete(targetDirectory, true);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to delete ffmpeg temp directory {TargetDirectory}", targetDirectory);
}
throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", processDescription));
}
return targetDirectory;
}
}
public string GetTimeParameter(long ticks)
{
var time = TimeSpan.FromTicks(ticks);
return GetTimeParameter(time);
}
public string GetTimeParameter(TimeSpan time)
{
return time.ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture);
}
private void StartProcess(ProcessWrapper process)
{
process.Process.Start();
try
{
process.Process.PriorityClass = ProcessPriorityClass.BelowNormal;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Unable to set process priority to BelowNormal for {ProcessFileName}", process.Process.StartInfo.FileName);
}
lock (_runningProcessesLock)
{
_runningProcesses.Add(process);
}
}
private void StopProcess(ProcessWrapper process, int waitTimeMs)
{
try
{
if (process.Process.WaitForExit(waitTimeMs))
{
return;
}
_logger.LogInformation("Killing ffmpeg process");
process.Process.Kill();
}
catch (InvalidOperationException)
{
// The process has already exited or
// there is no process associated with this Process object.
}
catch (Exception ex)
{
_logger.LogError(ex, "Error killing process");
}
}
private void StopProcesses()
{
List<ProcessWrapper> processes;
lock (_runningProcessesLock)
{
processes = _runningProcesses.ToList();
_runningProcesses.Clear();
}
foreach (var process in processes)
{
if (!process.HasExited)
{
StopProcess(process, 500);
}
}
}
public string EscapeSubtitleFilterPath(string path)
{
// https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping
// We need to double escape
return path
.Replace('\\', '/')
.Replace(":", "\\:", StringComparison.Ordinal)
.Replace("'", @"'\\\''", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal);
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
StopProcesses();
_thumbnailResourcePool.Dispose();
}
}
/// <inheritdoc />
public Task ConvertImage(string inputPath, string outputPath)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public IReadOnlyList<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber)
{
// Eliminate menus and intros by omitting VIDEO_TS.VOB and all subsequent title .vob files ending with _0.VOB
var allVobs = _fileSystem.GetFiles(path, true)
.Where(file => string.Equals(file.Extension, ".VOB", StringComparison.OrdinalIgnoreCase))
.Where(file => !string.Equals(file.Name, "VIDEO_TS.VOB", StringComparison.OrdinalIgnoreCase))
.Where(file => !file.Name.EndsWith("_0.VOB", StringComparison.OrdinalIgnoreCase))
.OrderBy(i => i.FullName)
.ToList();
if (titleNumber.HasValue)
{
var prefix = string.Format(CultureInfo.InvariantCulture, "VTS_{0:D2}_", titleNumber.Value);
var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
if (vobs.Count > 0)
{
return vobs.Select(i => i.FullName).ToList();
}
_logger.LogWarning("Could not determine .vob files for title {Title} of {Path}.", titleNumber, path);
}
// Check for multiple big titles (> 900 MB)
var titles = allVobs
.Where(vob => vob.Length >= 900 * 1024 * 1024)
.Select(vob => _fileSystem.GetFileNameWithoutExtension(vob).AsSpan().RightPart('_').ToString())
.Distinct()
.ToList();
// Fall back to first title if no big title is found
if (titles.Count == 0)
{
titles.Add(_fileSystem.GetFileNameWithoutExtension(allVobs[0]).AsSpan().RightPart('_').ToString());
}
// Aggregate all .vob files of the titles
return allVobs
.Where(vob => titles.Contains(_fileSystem.GetFileNameWithoutExtension(vob).AsSpan().RightPart('_').ToString()))
.Select(i => i.FullName)
.Order()
.ToList();
}
/// <inheritdoc />
public IReadOnlyList<string> GetPrimaryPlaylistM2tsFiles(string path)
=> _blurayExaminer.GetDiscInfo(path).Files;
/// <inheritdoc />
public string GetInputPathArgument(EncodingJobInfo state)
=> GetInputPathArgument(state.MediaPath, state.MediaSource);
/// <inheritdoc />
public string GetInputPathArgument(string path, MediaSourceInfo mediaSource)
{
return mediaSource.VideoType switch
{
VideoType.Dvd => GetInputArgument(GetPrimaryPlaylistVobFiles(path, null), mediaSource),
VideoType.BluRay => GetInputArgument(GetPrimaryPlaylistM2tsFiles(path), mediaSource),
_ => GetInputArgument(path, mediaSource)
};
}
/// <inheritdoc />
public void GenerateConcatConfig(MediaSourceInfo source, string concatFilePath)
{
// Get all playable files
IReadOnlyList<string> files;
var videoType = source.VideoType;
if (videoType == VideoType.Dvd)
{
files = GetPrimaryPlaylistVobFiles(source.Path, null);
}
else if (videoType == VideoType.BluRay)
{
files = GetPrimaryPlaylistM2tsFiles(source.Path);
}
else
{
return;
}
// Generate concat configuration entries for each file and write to file
Directory.CreateDirectory(Path.GetDirectoryName(concatFilePath));
using var sw = new FormattingStreamWriter(concatFilePath, CultureInfo.InvariantCulture);
foreach (var path in files)
{
var mediaInfoResult = GetMediaInfo(
new MediaInfoRequest
{
MediaType = DlnaProfileType.Video,
MediaSource = new MediaSourceInfo
{
Path = path,
Protocol = MediaProtocol.File,
VideoType = videoType
}
},
CancellationToken.None).GetAwaiter().GetResult();
var duration = TimeSpan.FromTicks(mediaInfoResult.RunTimeTicks.Value).TotalSeconds;
// Add file path stanza to concat configuration
sw.WriteLine("file '{0}'", path.Replace("'", @"'\''", StringComparison.Ordinal));
// Add duration stanza to concat configuration
sw.WriteLine("duration {0}", duration);
}
}
public bool CanExtractSubtitles(string codec)
{
// TODO is there ever a case when a subtitle can't be extracted??
return true;
}
| MediaEncoder |
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/Kernel/NodeComparer.cs | {
"start": 12372,
"end": 12810
} | private class ____<T, TProperty> : GenericEquatable<BindingCommand<T, TProperty>>
{
public BindingCommandEquatable(BindingCommand<T, TProperty> item)
: base(item)
{
}
protected override bool EqualsInstance(BindingCommand<T, TProperty> other)
{
return this.Item.Member == other.Member;
}
}
| BindingCommandEquatable |
csharp | MapsterMapper__Mapster | src/Mapster.Tests/WhenCompilingConfig.cs | {
"start": 1205,
"end": 1350
} | public class ____
{
public int ItemId { get; set; }
public string StringData { get; set; }
}
}
}
| DestItem |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeExtensionTests.cs | {
"start": 6994,
"end": 7308
} | public class ____
{
public Foo()
{
}
public Foo(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; } = "hello";
public string Description { get; } = "hello";
}
| Foo |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Areas/Admin/Validators/Messages/NewsLetterSubscriptionTypeValidator.cs | {
"start": 222,
"end": 666
} | public partial class ____ : BaseNopValidator<NewsLetterSubscriptionTypeModel>
{
public NewsLetterSubscriptionTypeValidator(ILocalizationService localizationService)
{
RuleFor(x => x.Name).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Admin.Promotions.NewsLetterSubscriptionType.Fields.Name.Required"));
SetDatabaseValidationRules<NewsLetterSubscriptionType>();
}
} | NewsLetterSubscriptionTypeValidator |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/IItemsControl.cs | {
"start": 41,
"end": 282
} | internal interface ____ : IFrameworkElement
{
object ItemsSource { get; set; }
DataTemplate ItemTemplate { get; set; }
DataTemplateSelector ItemTemplateSelector { get; set; }
string DisplayMemberPath { get; set; }
}
}
| IItemsControl |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs | {
"start": 691,
"end": 11575
} | public interface ____
{
}
private static dynamic field;
private static volatile dynamic volatileField;
private static object objectField;
public dynamic Property { get; set; }
public DynamicTests()
{
}
public DynamicTests(dynamic test)
{
}
public DynamicTests(DynamicTests test)
{
}
private static void CallWithOut(out dynamic d)
{
d = null;
}
#if CS70
private static void CallWithIn(in dynamic d)
{
}
#endif
#if CS120
private static void CallWithRefReadonly(ref readonly Dictionary<object, dynamic> d)
{
}
#endif
private static void CallWithRef(ref dynamic d)
{
}
private static void RefCallSiteTests()
{
#if CS70
CallWithOut(out var d);
CallWithIn(in d);
#else
dynamic d;
CallWithOut(out d);
#endif
CallWithRef(ref d);
d.SomeCall();
}
private static void InvokeConstructor()
{
DynamicTests dynamicTests = new DynamicTests();
dynamic val = new DynamicTests();
val.Test(new UnauthorizedAccessException());
dynamic val2 = new DynamicTests(val);
val2.Get(new DynamicTests((DynamicTests)val));
val2.Call(new DynamicTests((dynamic)dynamicTests));
}
private static dynamic InlineAssign(object a, out dynamic b)
{
return b = ((dynamic)a).Test;
}
private static dynamic SelfReference(dynamic d)
{
return d[d, d] = d;
}
private static dynamic LongArgumentListFunc(dynamic d)
{
// Func`13
return d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
private static void LongArgumentListAction(dynamic d)
{
// Action`13
d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
}
private static void DynamicThrow()
{
try
{
throw (Exception)field;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
private static void MemberAccess(dynamic a)
{
a.Test1();
a.GenericTest<int, int>();
a.Test2(1);
a.Test3(a.InnerTest(1, 2, 3, 4, 5));
a.Test4(2, null, a.Index[0]);
a.Test5(a, a.Number, a.String);
a[0] = 3;
a.Index[a.Number] = 5;
a.Index[a.Number] += 5;
a.Setter = new DynamicTests();
a.Setter2 = 5;
}
private static void StructMemberAccess(MyValueType valueType)
{
valueType.Field = 0;
valueType.Field += 5;
valueType.Field[1] = 5;
valueType.Field.CallMe();
DynamicTests.Casts(valueType.GetOnlyProperty);
valueType.GetOnlyProperty.CallMe();
valueType.Property = 0;
valueType.Property += 5;
valueType.Property[1] = 5;
valueType.Property.CallMe(5.ToDynamic((object)valueType.Property.Call()));
valueType.Method(valueType.GetOnlyProperty + valueType.Field);
}
private static void RequiredCasts()
{
((dynamic)objectField).A = 5;
((dynamic)objectField).B += 5;
((dynamic)objectField).Call();
((object)field).ToString();
field.Call("Hello World");
field.Call((object)"Hello World");
field.Call((dynamic)"Hello World");
}
private void StaticCallWithDynamicArgument(dynamic d)
{
M3(d + 5);
}
private static void StaticCallWithDynamicArgumentInStaticContext(dynamic d)
{
DynamicTests.M3(d + 5);
}
private static void DynamicCallWithString()
{
field.Call("Hello World");
}
private static void DynamicCallWithNamedArgs()
{
field.Call(a: "Hello World");
}
private static void DynamicCallWithRefOutArg(int a, out int b)
{
field.Call(ref a, out b);
}
private static void DynamicCallWithStringCastToObj()
{
field.Call((object)"Hello World");
}
private static void DynamicCallWithStringCastToDynamic()
{
field.Call((dynamic)"Hello World");
}
private static void DynamicCallWithStringCastToDynamic2()
{
field.Call((dynamic)"Hello World", 5, null);
}
private static void DynamicCallWithStringCastToDynamic3()
{
field.Call((dynamic)"Hello World", 5u, null);
}
private static void Invocation(dynamic a, dynamic b)
{
a(null, b.Test());
}
private static dynamic Test1(dynamic a)
{
dynamic val = a.IndexedProperty;
return val[0];
}
private static dynamic Test2(dynamic a)
{
return a.IndexedProperty[0];
}
private static void ArithmeticBinaryOperators(dynamic a, dynamic b)
{
DynamicTests.MemberAccess(a + b);
DynamicTests.MemberAccess(a + 1);
DynamicTests.MemberAccess(a + null);
DynamicTests.MemberAccess(a - b);
DynamicTests.MemberAccess(a - 1);
DynamicTests.MemberAccess(a - null);
DynamicTests.MemberAccess(a * b);
DynamicTests.MemberAccess(a * 1);
DynamicTests.MemberAccess(a * null);
DynamicTests.MemberAccess(a / b);
DynamicTests.MemberAccess(a / 1);
DynamicTests.MemberAccess(a / null);
DynamicTests.MemberAccess(a % b);
DynamicTests.MemberAccess(a % 1);
DynamicTests.MemberAccess(a % null);
}
private static void CheckedArithmeticBinaryOperators(dynamic a, dynamic b)
{
checked
{
DynamicTests.MemberAccess(a + b);
DynamicTests.MemberAccess(a + 1);
DynamicTests.MemberAccess(a + null);
DynamicTests.MemberAccess(a - b);
DynamicTests.MemberAccess(a - 1);
DynamicTests.MemberAccess(a - null);
DynamicTests.MemberAccess(a * b);
DynamicTests.MemberAccess(a * 1);
DynamicTests.MemberAccess(a * null);
DynamicTests.MemberAccess(a / b);
DynamicTests.MemberAccess(a / 1);
DynamicTests.MemberAccess(a / null);
DynamicTests.MemberAccess(a % b);
DynamicTests.MemberAccess(a % 1);
DynamicTests.MemberAccess(a % null);
}
}
private static void UncheckedArithmeticBinaryOperators(dynamic a, dynamic b)
{
checked
{
DynamicTests.MemberAccess(a + b);
DynamicTests.MemberAccess(a + 1);
DynamicTests.MemberAccess(a + null);
DynamicTests.MemberAccess(unchecked(a - b));
DynamicTests.MemberAccess(a - 1);
DynamicTests.MemberAccess(a - null);
DynamicTests.MemberAccess(unchecked(a * b));
DynamicTests.MemberAccess(a * 1);
DynamicTests.MemberAccess(a * null);
DynamicTests.MemberAccess(a / b);
DynamicTests.MemberAccess(a / 1);
DynamicTests.MemberAccess(a / null);
DynamicTests.MemberAccess(a % b);
DynamicTests.MemberAccess(a % 1);
DynamicTests.MemberAccess(a % null);
}
}
private static void RelationalOperators(dynamic a, dynamic b)
{
DynamicTests.MemberAccess(a == b);
DynamicTests.MemberAccess(a == 1);
DynamicTests.MemberAccess(a == null);
DynamicTests.MemberAccess(a != b);
DynamicTests.MemberAccess(a != 1);
DynamicTests.MemberAccess(a != null);
DynamicTests.MemberAccess(a < b);
DynamicTests.MemberAccess(a < 1);
DynamicTests.MemberAccess(a < null);
DynamicTests.MemberAccess(a > b);
DynamicTests.MemberAccess(a > 1);
DynamicTests.MemberAccess(a > null);
DynamicTests.MemberAccess(a >= b);
DynamicTests.MemberAccess(a >= 1);
DynamicTests.MemberAccess(a >= null);
DynamicTests.MemberAccess(a <= b);
DynamicTests.MemberAccess(a <= 1);
DynamicTests.MemberAccess(a <= null);
}
private static void Casts(dynamic a)
{
Console.WriteLine();
MemberAccess((int)a);
MemberAccess(checked((int)a));
}
private static void M(object o)
{
}
private static void M2(dynamic d)
{
}
private static void M3(int i)
{
}
private static void NotDynamicDispatch(dynamic d)
{
DynamicTests.M(d);
M((object)d);
DynamicTests.M2(d);
M2((object)d);
}
private static void CompoundAssignment(dynamic a, dynamic b)
{
a.Setter2 += 5;
a.Setter2 -= 1;
a.Setter2 *= 2;
a.Setter2 /= 5;
a.Setter2 += b;
a.Setter2 -= b;
a.Setter2 *= b;
a.Setter2 /= b;
field.Setter += 5;
field.Setter -= 5;
}
private static void InlineCompoundAssignment(dynamic a, dynamic b)
{
Console.WriteLine(a.Setter2 += 5);
Console.WriteLine(a.Setter2 -= 1);
Console.WriteLine(a.Setter2 *= 2);
Console.WriteLine(a.Setter2 /= 5);
Console.WriteLine(a.Setter2 += b);
Console.WriteLine(a.Setter2 -= b);
Console.WriteLine(a.Setter2 *= b);
Console.WriteLine(a.Setter2 /= b);
}
private static void UnaryOperators(dynamic a)
{
// TODO : beautify inc/dec on locals and fields
//a--;
//a++;
//--a;
//++a;
DynamicTests.Casts(-a);
DynamicTests.Casts(+a);
}
private static void Loops(dynamic list)
{
foreach (dynamic item in list)
{
DynamicTests.UnaryOperators(item);
}
}
private static void If(dynamic a, dynamic b)
{
if (a == b)
{
Console.WriteLine("Equal");
}
}
private static void If2(dynamic a, dynamic b)
{
if (a == null || b == null)
{
Console.WriteLine("One is null");
}
}
private static void If3(dynamic a, dynamic b)
{
if (a == null && b == null)
{
Console.WriteLine("Both are null");
}
}
private static void If4(dynamic a, dynamic b)
{
if ((a == null || b == null) && GetDynamic(1) && !(GetDynamic(2) && GetDynamic(3)))
{
Console.WriteLine("then");
}
else
{
Console.WriteLine("else");
}
}
private static bool ConstantTarget(dynamic a)
{
return true.Equals(a);
}
#if CS110 && NET70
private static nint NewIntPtr(dynamic a)
{
return new nint(a);
}
#else
private static IntPtr NewIntPtr(dynamic a)
{
return new IntPtr(a);
}
#endif
private static dynamic GetDynamic(int i)
{
return null;
}
private static bool GetBool(int i)
{
return false;
}
private static dynamic LogicAnd()
{
return GetDynamic(1) && GetDynamic(2);
}
private static dynamic LogicAnd(dynamic a, dynamic b)
{
return a && b;
}
private static void LogicAndExtended(int i, dynamic d)
{
Console.WriteLine(GetDynamic(1) && GetDynamic(2));
Console.WriteLine(GetDynamic(1) && GetBool(2));
Console.WriteLine(GetBool(1) && GetDynamic(2));
Console.WriteLine(i == 1 && d == null);
}
private static dynamic LogicOr()
{
return GetDynamic(1) || GetDynamic(2);
}
private static dynamic LogicOr(dynamic a, dynamic b)
{
return a || b;
}
private static void LogicOrExtended(int i, dynamic d)
{
Console.WriteLine(GetDynamic(1) || GetDynamic(2));
Console.WriteLine(GetDynamic(1) || GetBool(2));
Console.WriteLine(GetBool(1) || GetDynamic(2));
Console.WriteLine(i == 1 || d == null);
}
private static int ImplicitCast(object o)
{
return (dynamic)o;
}
private static int ExplicitCast(object o)
{
return (int)(dynamic)o;
}
private static dynamic GetI()
{
return null;
}
public I Test()
{
return GetI();
}
public I Test1()
{
return (I)GetI();
}
public I Test2()
{
return (I)(object)GetI();
}
#if CS72
public void RefParams(ref object a, ref dynamic b, ref dynamic c)
{
}
public void RefParams2(in object a, ref dynamic b, out dynamic c)
{
c = null;
}
public ref dynamic RefReturn(ref object o)
{
return ref o;
}
public ref readonly dynamic RefReadonlyReturn(in object o)
{
return ref o;
}
#endif
}
| I |
csharp | dotnet__maui | src/Core/src/Platform/Windows/RootNavigationView.cs | {
"start": 12717,
"end": 14470
} |
partial class ____ : Panel
{
public Maui.IView? FlyoutView { get; set; }
UIElementCollection? _cachedChildren;
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs", Justification = "Panel.Children property is banned to enforce use of this CachedChildren property.")]
internal UIElementCollection CachedChildren
{
get
{
_cachedChildren ??= Children;
return _cachedChildren;
}
}
public FlyoutPanel()
{
}
public double ContentWidth { get; set; }
FrameworkElement? FlyoutContent =>
CachedChildren.Count > 0 ? (FrameworkElement?)CachedChildren[0] : null;
protected override Size MeasureOverride(Size availableSize)
{
if (FlyoutContent == null)
return new Size(0, 0);
if (ContentWidth == 0)
return new Size(0, 0);
if (FlyoutView != null)
FlyoutView.Measure(ContentWidth, availableSize.Height);
else
FlyoutContent.Measure(new Size(ContentWidth, availableSize.Height));
return FlyoutContent.DesiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
if (FlyoutContent == null)
return new Size(0, 0);
if (finalSize.Width * finalSize.Height == 0 &&
FlyoutContent.ActualWidth * FlyoutContent.ActualHeight == 0)
{
return finalSize;
}
if (FlyoutView != null)
FlyoutView.Arrange(new Graphics.Rect(0, 0, finalSize.Width, finalSize.Height));
else
FlyoutContent.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
return new Size(FlyoutContent.ActualWidth, FlyoutContent.ActualHeight);
}
}
private protected override void UpdateFlyoutCustomContent()
{
ReplacePaneMenuItemsWithCustomContent(FlyoutCustomContent as UIElement);
}
}
}
| FlyoutPanel |
csharp | exceptionless__Exceptionless | tests/Exceptionless.Tests/Extensions/TaskExtensions.cs | {
"start": 70,
"end": 291
} | public static class ____
{
public static Task WaitAsync(this AsyncCountdownEvent countdownEvent, TimeSpan timeout)
{
return Task.WhenAny(countdownEvent.WaitAsync(), Task.Delay(timeout));
}
}
| TaskExtensions |
csharp | xunit__xunit | src/xunit.v3.core.tests/ObjectModel/XunitTestCaseTests.cs | {
"start": 3177,
"end": 5082
} | class ____
{
[Fact]
public void Passing() { }
}
[Fact]
public void ManagedTestCasePropertiesTest()
{
var type = typeof(XunitTestCaseTestsNamespace.ParentClass.GenericTestClass<,>);
var testClass = TestData.XunitTestClass(type);
var method1 = type.GetMethod("TestMethod1")!;
var testMethod1 = TestData.XunitTestMethod(testClass, method1);
var testCase1 = new XunitTestCase(testMethod1, "display name", "id", @explicit: false);
Assert.Equal(typeof(XunitTestCaseTestsNamespace.ParentClass.GenericTestClass<,>).FullName, testCase1.TestClassName);
Assert.Equal("TestMethod1", testCase1.TestMethodName);
Assert.Collection(
testCase1.TestMethodParameterTypesVSTest,
p => Assert.Equal("!0", p),
p => Assert.Equal("!1", p),
p => Assert.Equal(typeof(string[,]).FullName, p)
);
Assert.Equal("System.Void", testCase1.TestMethodReturnTypeVSTest);
var method2 = type.GetMethod("TestMethod2")!;
var testMethod2 = TestData.XunitTestMethod(testClass, method2);
var testCase2 = new XunitTestCase(testMethod2, "display name", "id", @explicit: false);
Assert.Equal(typeof(XunitTestCaseTestsNamespace.ParentClass.GenericTestClass<,>).FullName, testCase2.TestClassName);
Assert.Equal("TestMethod2", testCase2.TestMethodName);
Assert.Collection(
testCase2.TestMethodParameterTypesVSTest,
p => Assert.Equal("!0", p),
p => Assert.Equal("XunitTestCaseTestsNamespace.ParentClass+MyList`1<!1>", p),
p => Assert.Equal("!!0", p),
p => Assert.Equal("!!1", p),
p => Assert.Equal("XunitTestCaseTestsNamespace.ParentClass+MyList`1<System.String>", p)
);
Assert.Equal("System.Threading.Tasks.Task`1<System.Int32>", testCase2.TestMethodReturnTypeVSTest);
}
}
namespace XunitTestCaseTestsNamespace
{
#pragma warning disable xUnit1003 // Theory methods must have test data
#pragma warning disable xUnit1028 // Test method must have valid return type
| ClassUnderTest |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Extensions/Grpc/GrpcResponse.cs | {
"start": 236,
"end": 2790
} | public class ____ : IHttpResponse, IHasHeaders, IWriteEvent, IWriteEventAsync
{
private readonly GrpcRequest request;
public Dictionary<string, string> Headers { get; }
public GrpcResponse(GrpcRequest request)
{
this.request = request;
this.OriginalResponse = request.Context;
this.Headers = new Dictionary<string, string>();
this.Items = new Dictionary<string, object>();
Cookies = new Cookies(this);
this.OutputStream = Stream.Null;
}
public object OriginalResponse { get; set; }
public IRequest Request => request;
public int StatusCode { get; set; } = 200;
public string? StatusDescription { get; set; }
public string ContentType
{
get => request.ResponseContentType;
set => request.ResponseContentType = value;
}
public void AddHeader(string name, string value)
{
Headers[name] = value;
}
public void RemoveHeader(string name)
{
Headers.Remove(name);
}
public string? GetHeader(string name)
{
this.Headers.TryGetValue(name, out var value);
return value;
}
public void Redirect(string url) { }
public Stream OutputStream { get; }
public object? Dto { get; set; }
public void Write(string text) { }
public bool UseBufferedStream { get; set; }
public void Close()
{
IsClosed = true;
}
public Task CloseAsync(CancellationToken token = default)
{
Close();
return TypeConstants.EmptyTask;
}
public void End()
{
Close();
}
public void Flush() { }
public Task FlushAsync(CancellationToken token = default) => TypeConstants.EmptyTask;
public bool IsClosed { get; set; }
public void SetContentLength(long contentLength) { }
public bool KeepAlive { get; set; }
public bool HasStarted { get; set; }
public Dictionary<string, object> Items { get; }
public ICookies Cookies { get; }
public void SetCookie(Cookie cookie) { }
public void ClearCookies() { }
private Channel<string>? eventsChannel;
public Channel<string> EventsChannel =>
eventsChannel ??= Channel.CreateUnbounded<string>(new UnboundedChannelOptions {SingleReader = true});
public void WriteEvent(string msg)
{
while (!EventsChannel.Writer.TryWrite(msg)) { }
}
public async Task WriteEventAsync(string msg, CancellationToken token = default)
{
await EventsChannel.Writer.WriteAsync(msg, token);
}
} | GrpcResponse |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs | {
"start": 39337,
"end": 39652
} | public class ____ : Optional1Derived
{
protected Optional1MoreDerived()
{
}
public override bool Equals(object obj)
=> base.Equals(obj as Optional1MoreDerived);
public override int GetHashCode()
=> base.GetHashCode();
}
| Optional1MoreDerived |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/Attributes/ArgumentsAttributeAnalyzerTests.cs | {
"start": 38177,
"end": 39565
} | public class ____
{
[Benchmark]
[{{dummyAttributeUsage}}{{string.Format(scalarValuesContainerAttributeArgument, "42, \"test\"")}}]
[{{dummyAttributeUsage}}{{string.Format(scalarValuesContainerAttributeArgument, "43, \"test2\"")}}]
public void BenchmarkMethod(unkown a, string b)
{
}
}
""";
TestCode = testCode;
ReferenceDummyAttribute();
DisableCompilerDiagnostics();
await RunAsync();
}
[Theory, CombinatorialData]
public async Task Providing_an_unexpected_or_not_implicitly_convertible_value_type_should_trigger_diagnostic(
[CombinatorialMemberData(nameof(DummyAttributeUsage))] string dummyAttributeUsage,
[CombinatorialMemberData(nameof(NotConvertibleValuesAndTypes))] ValueTupleDouble<string, string> valueAndType,
[CombinatorialMemberData(nameof(ScalarValuesContainerAttributeArgumentEnumerableLocal))] string scalarValuesContainerAttributeArgument)
{
const string expectedArgumentType = "decimal";
var testCode = /* lang=c#-test */ $$"""
using BenchmarkDotNet.Attributes;
| BenchmarkClass |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/ReSharper/ReSharper.Generated.cs | {
"start": 39871,
"end": 40650
} | public partial class ____ : ToolOptions
{
/// <summary>Allows adding ReSharper plugins that will get included during execution. To add a plugin, specify its ID and version. Available plugins are listed in the <a href="https://resharper-plugins.jetbrains.com/">Plugin Repository</a>. The ID can be grabbed from the download URL. Using <c>ReSharperPluginLatest</c> or <c>null</c> will download the latest version.</summary>
public IReadOnlyDictionary<string, string> Plugins => Get<Dictionary<string, string>>(() => Plugins);
}
#endregion
#region ReSharperInspectCodeSettingsExtensions
/// <inheritdoc cref="ReSharperTasks.ReSharperInspectCode(Nuke.Common.Tools.ReSharper.ReSharperInspectCodeSettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static | ReSharperSettingsBase |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Startup.cs | {
"start": 1769,
"end": 2184
} | public sealed class ____ : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IContentTypePartDefinitionDisplayDriver, ContentTypePartIndexSettingsDisplayDriver>();
services.AddScoped<IContentPartFieldDefinitionDisplayDriver, ContentPartFieldIndexSettingsDisplayDriver>();
}
}
[RequireFeatures("OrchardCore.Contents")]
| ContentTypesStartup |
csharp | cake-build__cake | src/Cake.Common.Tests/Fixtures/Tools/DotNetCore/NuGet/Source/DotNetCoreNuGetListSourceFixture.cs | {
"start": 320,
"end": 659
} | internal sealed class ____ : DotNetNuGetSourcerFixture
{
public string Format { get; set; }
protected override void RunTool()
{
var tool = new DotNetNuGetSourcer(FileSystem, Environment, ProcessRunner, Tools);
tool.ListSource(Format, Settings);
}
}
} | DotNetNuGetListSourceFixture |
csharp | microsoft__semantic-kernel | dotnet/samples/Demos/ProcessWithDapr/Controllers/ProcessController.cs | {
"start": 3819,
"end": 3886
} | private sealed class ____ : KernelProcessStep
{
| KickoffStep |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Core/Domain/Translation/TranslationServiceType.cs | {
"start": 112,
"end": 308
} | public enum ____
{
/// <summary>
/// Google cloud translate API
/// </summary>
GoogleTranslate,
/// <summary>
/// DeepL API
/// </summary>
DeepL
} | TranslationServiceType |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Types/DateTimeOffsetGraphTypeTests.cs | {
"start": 110,
"end": 2552
} | public class ____
{
private readonly DateTimeOffsetGraphType _type = new();
[Fact]
public void coerces_valid_date()
{
CultureTestHelper.UseCultures(() =>
{
var expected = DateTimeOffset.UtcNow;
string input = expected.ToString("O", DateTimeFormatInfo.InvariantInfo);
object? actual = _type.ParseValue(input);
actual.ShouldBe(expected);
});
}
[Fact]
public void coerces_invalid_string_to_exception()
{
CultureTestHelper.UseCultures(() => Should.Throw<FormatException>(() => _type.ParseValue("some unknown date")));
}
[Fact]
public void coerces_invalidly_formatted_date_to_exception()
{
CultureTestHelper.UseCultures(() => Should.Throw<FormatException>(() => _type.ParseValue("Dec 32 2012")));
}
[Fact]
public void coerces_iso8601_utc_formatted_string_to_date()
{
CultureTestHelper.UseCultures(() =>
{
_type.ParseValue("2015-12-01T14:15:07.123Z").ShouldBe(
new DateTimeOffset(2015, 12, 01, 14, 15, 7, 123, TimeSpan.Zero));
});
}
[Fact]
public void coerces_iso8601_string_with_tzone_to_date()
{
CultureTestHelper.UseCultures(() =>
{
var dateTimeOffset = (DateTimeOffset)_type.ParseValue("2015-11-21T19:59:32.987+0200")!;
dateTimeOffset.Date.ShouldBe(new DateTime(2015, 11, 21));
dateTimeOffset.TimeOfDay.ShouldBe(new TimeSpan(0, 19, 59, 32, 987));
dateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(2));
});
}
public static object[][] DateTimeTypeTests()
{
var dateTimeNow = DateTime.Now;
var dateTimeUtcNow = DateTime.UtcNow;
var dateTimeUnspecified = new DateTime(2015, 11, 21, 17, 59, 32, DateTimeKind.Unspecified);
return new object[][]
{
new object[] { dateTimeNow, new DateTimeOffset(dateTimeNow) },
new object[] { dateTimeUtcNow, new DateTimeOffset(dateTimeUtcNow) },
new object[] { dateTimeUnspecified, new DateTimeOffset(dateTimeUnspecified, TimeSpan.Zero) }
};
}
[Theory]
[MemberData(nameof(DateTimeTypeTests))]
public void coerces_dateTime_type_to_date(DateTime input, DateTimeOffset expected)
{
CultureTestHelper.UseCultures(() => _type.ParseValue(input).ShouldBe(expected));
}
}
| DateTimeOffsetGraphTypeTests |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.Markdown/Parsers/Markdown/Render/MarkdownRendererBase.cs | {
"start": 529,
"end": 8994
} | partial class ____
{
#pragma warning disable CS0618 // Type or member is obsolete
/// <summary>
/// Initializes a new instance of the <see cref="MarkdownRendererBase"/> class.
/// </summary>
/// <param name="document">Markdown Document to Render</param>
public MarkdownRendererBase(MarkdownDocument document)
{
Document = document;
}
/// <summary>
/// Renders all Content to the Provided Parent UI.
/// </summary>
/// <param name="context">UI Context</param>
public virtual void Render(IRenderContext context)
{
RenderBlocks(Document.Blocks, context);
}
/// <summary>
/// Renders a list of block elements.
/// </summary>
protected virtual void RenderBlocks(IEnumerable<MarkdownBlock> blockElements, IRenderContext context)
{
foreach (MarkdownBlock element in blockElements)
{
RenderBlock(element, context);
}
}
/// <summary>
/// Called to render a block element.
/// </summary>
protected void RenderBlock(MarkdownBlock element, IRenderContext context)
{
{
switch (element.Type)
{
case MarkdownBlockType.Paragraph:
RenderParagraph((ParagraphBlock)element, context);
break;
case MarkdownBlockType.Quote:
RenderQuote((QuoteBlock)element, context);
break;
case MarkdownBlockType.Code:
RenderCode((CodeBlock)element, context);
break;
case MarkdownBlockType.Header:
RenderHeader((HeaderBlock)element, context);
break;
case MarkdownBlockType.List:
RenderListElement((ListBlock)element, context);
break;
case MarkdownBlockType.HorizontalRule:
RenderHorizontalRule(context);
break;
case MarkdownBlockType.Table:
RenderTable((TableBlock)element, context);
break;
case MarkdownBlockType.YamlHeader:
RenderYamlHeader((YamlHeaderBlock)element, context);
break;
}
}
}
/// <summary>
/// Renders all of the children for the given element.
/// </summary>
/// <param name="inlineElements"> The parsed inline elements to render. </param>
/// <param name="context"> Persistent state. </param>
protected void RenderInlineChildren(IList<MarkdownInline> inlineElements, IRenderContext context)
{
foreach (MarkdownInline element in inlineElements)
{
switch (element.Type)
{
case MarkdownInlineType.Comment:
case MarkdownInlineType.LinkReference:
break;
default:
RenderInline(element, context);
break;
}
}
}
/// <summary>
/// Called to render an inline element.
/// </summary>
/// <param name="element"> The parsed inline element to render. </param>
/// <param name="context"> Persistent state. </param>
protected void RenderInline(MarkdownInline element, IRenderContext context)
{
switch (element.Type)
{
case MarkdownInlineType.TextRun:
RenderTextRun((TextRunInline)element, context);
break;
case MarkdownInlineType.Italic:
RenderItalicRun((ItalicTextInline)element, context);
break;
case MarkdownInlineType.Bold:
RenderBoldRun((BoldTextInline)element, context);
break;
case MarkdownInlineType.MarkdownLink:
CheckRenderMarkdownLink((MarkdownLinkInline)element, context);
break;
case MarkdownInlineType.RawHyperlink:
RenderHyperlink((HyperlinkInline)element, context);
break;
case MarkdownInlineType.Strikethrough:
RenderStrikethroughRun((StrikethroughTextInline)element, context);
break;
case MarkdownInlineType.Superscript:
RenderSuperscriptRun((SuperscriptTextInline)element, context);
break;
case MarkdownInlineType.Subscript:
RenderSubscriptRun((SubscriptTextInline)element, context);
break;
case MarkdownInlineType.Code:
RenderCodeRun((CodeInline)element, context);
break;
case MarkdownInlineType.Image:
RenderImage((ImageInline)element, context);
break;
case MarkdownInlineType.Emoji:
RenderEmoji((EmojiInline)element, context);
break;
}
}
/// <summary>
/// Removes leading whitespace, but only if this is the first run in the block.
/// </summary>
/// <returns>The corrected string</returns>
protected string CollapseWhitespace(IRenderContext context, string text)
{
bool dontOutputWhitespace = context.TrimLeadingWhitespace;
StringBuilder result = null;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == ' ' || c == '\t')
{
if (dontOutputWhitespace)
{
if (result == null)
{
result = new StringBuilder(text.Substring(0, i), text.Length);
}
}
else
{
result?.Append(c);
dontOutputWhitespace = true;
}
}
else
{
result?.Append(c);
dontOutputWhitespace = false;
}
}
context.TrimLeadingWhitespace = false;
return result == null ? text : result.ToString();
}
/// <summary>
/// Verifies if the link is valid, before processing into a link, or plain text.
/// </summary>
/// <param name="element"> The parsed inline element to render. </param>
/// <param name="context"> Persistent state. </param>
protected void CheckRenderMarkdownLink(MarkdownLinkInline element, IRenderContext context)
{
// Avoid processing when link text is empty.
if (element.Inlines.Count == 0)
{
return;
}
// Attempt to resolve references.
element.ResolveReference(Document);
if (element.Url == null)
{
// The element couldn't be resolved, just render it as text.
RenderInlineChildren(element.Inlines, context);
return;
}
foreach (MarkdownInline inline in element.Inlines)
{
if (inline is ImageInline imageInline)
{
// this is an image, create Image.
if (!string.IsNullOrEmpty(imageInline.ReferenceId))
{
imageInline.ResolveReference(Document);
}
imageInline.Url = element.Url;
RenderImage(imageInline, context);
return;
}
}
RenderMarkdownLink(element, context);
}
/// <summary>
/// Gets the markdown document that will be rendered.
/// </summary>
protected MarkdownDocument Document { get; }
#pragma warning restore CS0618 // Type or member is obsolete
}
} | MarkdownRendererBase |
csharp | dotnet__aspnetcore | src/Middleware/ResponseCaching/src/ResponseCachingServicesExtensions.cs | {
"start": 421,
"end": 1671
} | public static class ____
{
/// <summary>
/// Add response caching services.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
/// <returns></returns>
public static IServiceCollection AddResponseCaching(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
return services;
}
/// <summary>
/// Add response caching services and configure the related options.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
/// <param name="configureOptions">A delegate to configure the <see cref="ResponseCachingOptions"/>.</param>
/// <returns></returns>
public static IServiceCollection AddResponseCaching(this IServiceCollection services, Action<ResponseCachingOptions> configureOptions)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configureOptions);
services.Configure(configureOptions);
services.AddResponseCaching();
return services;
}
}
| ResponseCachingServicesExtensions |
csharp | dotnet__efcore | src/EFCore.Relational/Storage/SByteTypeMapping.cs | {
"start": 781,
"end": 2560
} | public class ____ : RelationalTypeMapping
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static SByteTypeMapping Default { get; } = new("tinyint");
/// <summary>
/// Initializes a new instance of the <see cref="SByteTypeMapping" /> class.
/// </summary>
/// <param name="storeType">The name of the database type.</param>
/// <param name="dbType">The <see cref="DbType" /> to be used.</param>
public SByteTypeMapping(
string storeType,
DbType? dbType = System.Data.DbType.SByte)
: base(storeType, typeof(sbyte), dbType, jsonValueReaderWriter: JsonSByteReaderWriter.Instance)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SByteTypeMapping" /> class.
/// </summary>
/// <param name="parameters">Parameter object for <see cref="RelationalTypeMapping" />.</param>
protected SByteTypeMapping(RelationalTypeMappingParameters parameters)
: base(parameters)
{
}
/// <summary>
/// Creates a copy of this mapping.
/// </summary>
/// <param name="parameters">The parameters for this mapping.</param>
/// <returns>The newly created mapping.</returns>
protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
=> new SByteTypeMapping(parameters);
}
| SByteTypeMapping |
csharp | ardalis__CleanArchitecture | sample/tests/NimblePros.SampleToDo.FunctionalTests/Projects/ProjectAddToDoItem.cs | {
"start": 231,
"end": 12349
} | public class ____ : TestBase
{
public ProjectAddToDoItem(CustomWebApplicationFactory<Program> factory) : base(factory)
{
}
//[Fact] - Broken due to CachingBehavior without cache invalidation logic
private async Task AddsItemAndReturnsRouteToProject()
{
// Arrange
var uniqueId = Guid.NewGuid().ToString();
var toDoTitle = $"AddsItem-{uniqueId}";
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(toDoTitle)
.WithDescription($"Description for {toDoTitle}")
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
result.Headers!.Location!.ToString().ShouldBe(expectedRoute);
// Verify the item was actually added
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute);
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == toDoTitle);
addedItem.ShouldNotBeNull();
addedItem.Description.ShouldBe(request.Description);
addedItem.IsDone.ShouldBe(false);
addedItem.ContributorId.ShouldBeNull();
}
[Fact]
public async Task ReturnsBadRequestWhenTitleIsMissing()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(string.Empty) // Missing required title
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task ReturnsBadRequestWhenDescriptionIsMissing()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithDescription(string.Empty) // Missing required description
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task ReturnsBadRequestWhenProjectIdIsZero()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithProjectId(0) // Invalid project ID
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task ReturnsNotFoundWhenProjectDoesNotExist()
{
// Arrange
int nonExistentProjectId = 9999;
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithProjectId(nonExistentProjectId)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureNotFoundAsync(
CreateToDoItemRequest.BuildRoute(nonExistentProjectId), content);
}
[Fact]
public async Task AddsItemWithValidContributor()
{
// Arrange
var uniqueId = Guid.NewGuid().ToString();
var toDoTitle = $"WithContributor-{uniqueId}";
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(toDoTitle)
.WithContributorId(SeedData.Contributor1.Id.Value)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute);
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == toDoTitle);
addedItem.ShouldNotBeNull();
addedItem.ContributorId.ShouldBe(SeedData.Contributor1.Id.Value);
}
//[Fact] - Broken due to CachingBehavior without cache invalidation logic
private async Task AddsItemWithNullContributor()
{
// Arrange
var uniqueId = Guid.NewGuid().ToString();
var toDoTitle = $"NullContributor-{uniqueId}";
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(toDoTitle)
.WithContributorId(null)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute);
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == toDoTitle);
addedItem.ShouldNotBeNull();
addedItem.ContributorId.ShouldBeNull();
}
//[Fact] - Broken due to CachingBehavior without cache invalidation logic
private async Task HandlesSpecialCharactersInTitleAndDescription()
{
// Arrange
var uniqueId = Guid.NewGuid().ToString()[..8];
var toDoTitle = $"Special-{uniqueId}-àáâãäåæçèéêë@#$%^&*()";
var description = $"Desc-{uniqueId}-ñöø¿¡™£¢∞§¶•ªº";
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(toDoTitle)
.WithDescription(description)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute);
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == toDoTitle);
addedItem.ShouldNotBeNull();
addedItem.Title.ShouldBe(toDoTitle);
addedItem.Description.ShouldBe(description);
}
//[Fact] - Broken due to CachingBehavior without cache invalidation logic
private async Task HandlesLongTitleAndDescription()
{
// Arrange - use lengths within the constraints (100 for title, 200 for description)
var uniqueId = Guid.NewGuid().ToString()[..8];
var longTitle = $"Long-{uniqueId}-" + new string('A', 80); // Stay within the 100 character limit
var longDescription = $"LongDesc-{uniqueId}-" + new string('B', 170); // Stay within the 200 character limit
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(longTitle)
.WithDescription(longDescription)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute);
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == longTitle);
addedItem.ShouldNotBeNull();
addedItem.Title.ShouldBe(longTitle);
addedItem.Description.ShouldBe(longDescription);
}
[Fact]
public async Task ReturnsBadRequestWhenTitleExceedsMaxLength()
{
// Arrange - exceed the 100 character limit
var tooLongTitle = new string('A', 101);
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(tooLongTitle)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task ReturnsBadRequestWhenDescriptionExceedsMaxLength()
{
// Arrange - exceed the 200 character limit
var tooLongDescription = new string('B', 201);
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithDescription(tooLongDescription)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task HandlesWhitespaceOnlyTitleAndDescription()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithTitle(" ") // Whitespace only
.WithDescription(" ") // Whitespace only
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act & Assert
// This should fail validation since whitespace-only strings are typically not valid
_ = await _client.PostAndEnsureBadRequestAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
}
[Fact]
public async Task ReturnsCorrectStatusCodeAndContentType()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.StatusCode.ShouldBe(System.Net.HttpStatusCode.Created);
result.Headers.Location.ShouldNotBeNull();
// Verify the location header points to the correct project
var expectedRoute = GetProjectByIdRequest.BuildRoute(request.ProjectId);
result.Headers.Location.ToString().ShouldBe(expectedRoute);
}
[Fact]
public async Task DoesNotReturnResponseBodyOnSuccess()
{
// Arrange
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(request.ProjectId), content);
// Assert
result.EnsureSuccessStatusCode();
// According to REST conventions, POST should return 201 Created with Location header
// but no response body for this endpoint
var responseContent = await result.Content.ReadAsStringAsync();
responseContent.ShouldBeNullOrEmpty();
}
//[Fact] - Broken due to CachingBehavior without cache invalidation logic
private async Task IncreasesTotalItemCountInProject()
{
// Arrange
var uniqueId = Guid.NewGuid().ToString();
var projectId = SeedData.TestProject1.Id.Value;
// Get initial count
var initialProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(
GetProjectByIdRequest.BuildRoute(projectId));
var initialCount = initialProject.Items.Count;
var toDoTitle = $"CountTest-{uniqueId}";
var request = CreateToDoItemRequestBuilder.Create()
.WithValidDefaults()
.WithProjectId(projectId)
.WithTitle(toDoTitle)
.Build();
var content = StringContentHelpers.FromModelAsJson(request);
// Act
var result = await _client.PostAsync(
CreateToDoItemRequest.BuildRoute(projectId), content);
// Assert
result.EnsureSuccessStatusCode();
var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(
GetProjectByIdRequest.BuildRoute(projectId));
// Verify the count increased by exactly 1
updatedProject.Items.Count.ShouldBe(initialCount + 1);
// Verify our specific item was added
var addedItem = updatedProject.Items.FirstOrDefault(item => item.Title == toDoTitle);
addedItem.ShouldNotBeNull();
}
}
| ProjectAddToDoItem |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs | {
"start": 2122021,
"end": 2136441
} | partial class ____ : pb::IMessage<QueryRockstarsIFilter>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<QueryRockstarsIFilter> _parser = new pb::MessageParser<QueryRockstarsIFilter>(() => new QueryRockstarsIFilter());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<QueryRockstarsIFilter> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::ServiceStack.Extensions.Tests.Protoc.ServicesReflection.Descriptor.MessageTypes[164]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public QueryRockstarsIFilter() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public QueryRockstarsIFilter(QueryRockstarsIFilter other) : this() {
skip_ = other.skip_;
take_ = other.take_;
orderBy_ = other.orderBy_;
orderByDesc_ = other.orderByDesc_;
include_ = other.include_;
fields_ = other.fields_;
meta_ = other.meta_.Clone();
age_ = other.age_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public QueryRockstarsIFilter Clone() {
return new QueryRockstarsIFilter(this);
}
/// <summary>Field number for the "Skip" field.</summary>
public const int SkipFieldNumber = 1;
private int skip_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Skip {
get { return skip_; }
set {
skip_ = value;
}
}
/// <summary>Field number for the "Take" field.</summary>
public const int TakeFieldNumber = 2;
private int take_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Take {
get { return take_; }
set {
take_ = value;
}
}
/// <summary>Field number for the "OrderBy" field.</summary>
public const int OrderByFieldNumber = 3;
private string orderBy_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string OrderBy {
get { return orderBy_; }
set {
orderBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "OrderByDesc" field.</summary>
public const int OrderByDescFieldNumber = 4;
private string orderByDesc_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string OrderByDesc {
get { return orderByDesc_; }
set {
orderByDesc_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Include" field.</summary>
public const int IncludeFieldNumber = 5;
private string include_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Include {
get { return include_; }
set {
include_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Fields" field.</summary>
public const int FieldsFieldNumber = 6;
private string fields_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Fields {
get { return fields_; }
set {
fields_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Meta" field.</summary>
public const int MetaFieldNumber = 7;
private static readonly pbc::MapField<string, string>.Codec _map_meta_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 58);
private readonly pbc::MapField<string, string> meta_ = new pbc::MapField<string, string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::MapField<string, string> Meta {
get { return meta_; }
}
/// <summary>Field number for the "Age" field.</summary>
public const int AgeFieldNumber = 201;
private int age_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Age {
get { return age_; }
set {
age_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as QueryRockstarsIFilter);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(QueryRockstarsIFilter other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Skip != other.Skip) return false;
if (Take != other.Take) return false;
if (OrderBy != other.OrderBy) return false;
if (OrderByDesc != other.OrderByDesc) return false;
if (Include != other.Include) return false;
if (Fields != other.Fields) return false;
if (!Meta.Equals(other.Meta)) return false;
if (Age != other.Age) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Skip != 0) hash ^= Skip.GetHashCode();
if (Take != 0) hash ^= Take.GetHashCode();
if (OrderBy.Length != 0) hash ^= OrderBy.GetHashCode();
if (OrderByDesc.Length != 0) hash ^= OrderByDesc.GetHashCode();
if (Include.Length != 0) hash ^= Include.GetHashCode();
if (Fields.Length != 0) hash ^= Fields.GetHashCode();
hash ^= Meta.GetHashCode();
if (Age != 0) hash ^= Age.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Skip != 0) {
output.WriteRawTag(8);
output.WriteInt32(Skip);
}
if (Take != 0) {
output.WriteRawTag(16);
output.WriteInt32(Take);
}
if (OrderBy.Length != 0) {
output.WriteRawTag(26);
output.WriteString(OrderBy);
}
if (OrderByDesc.Length != 0) {
output.WriteRawTag(34);
output.WriteString(OrderByDesc);
}
if (Include.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Include);
}
if (Fields.Length != 0) {
output.WriteRawTag(50);
output.WriteString(Fields);
}
meta_.WriteTo(output, _map_meta_codec);
if (Age != 0) {
output.WriteRawTag(200, 12);
output.WriteInt32(Age);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Skip != 0) {
output.WriteRawTag(8);
output.WriteInt32(Skip);
}
if (Take != 0) {
output.WriteRawTag(16);
output.WriteInt32(Take);
}
if (OrderBy.Length != 0) {
output.WriteRawTag(26);
output.WriteString(OrderBy);
}
if (OrderByDesc.Length != 0) {
output.WriteRawTag(34);
output.WriteString(OrderByDesc);
}
if (Include.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Include);
}
if (Fields.Length != 0) {
output.WriteRawTag(50);
output.WriteString(Fields);
}
meta_.WriteTo(ref output, _map_meta_codec);
if (Age != 0) {
output.WriteRawTag(200, 12);
output.WriteInt32(Age);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Skip != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Skip);
}
if (Take != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Take);
}
if (OrderBy.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderBy);
}
if (OrderByDesc.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderByDesc);
}
if (Include.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Include);
}
if (Fields.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Fields);
}
size += meta_.CalculateSize(_map_meta_codec);
if (Age != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(Age);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(QueryRockstarsIFilter other) {
if (other == null) {
return;
}
if (other.Skip != 0) {
Skip = other.Skip;
}
if (other.Take != 0) {
Take = other.Take;
}
if (other.OrderBy.Length != 0) {
OrderBy = other.OrderBy;
}
if (other.OrderByDesc.Length != 0) {
OrderByDesc = other.OrderByDesc;
}
if (other.Include.Length != 0) {
Include = other.Include;
}
if (other.Fields.Length != 0) {
Fields = other.Fields;
}
meta_.Add(other.meta_);
if (other.Age != 0) {
Age = other.Age;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Skip = input.ReadInt32();
break;
}
case 16: {
Take = input.ReadInt32();
break;
}
case 26: {
OrderBy = input.ReadString();
break;
}
case 34: {
OrderByDesc = input.ReadString();
break;
}
case 42: {
Include = input.ReadString();
break;
}
case 50: {
Fields = input.ReadString();
break;
}
case 58: {
meta_.AddEntriesFrom(input, _map_meta_codec);
break;
}
case 1608: {
Age = input.ReadInt32();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Skip = input.ReadInt32();
break;
}
case 16: {
Take = input.ReadInt32();
break;
}
case 26: {
OrderBy = input.ReadString();
break;
}
case 34: {
OrderByDesc = input.ReadString();
break;
}
case 42: {
Include = input.ReadString();
break;
}
case 50: {
Fields = input.ReadString();
break;
}
case 58: {
meta_.AddEntriesFrom(ref input, _map_meta_codec);
break;
}
case 1608: {
Age = input.ReadInt32();
break;
}
}
}
}
#endif
}
public sealed | QueryRockstarsIFilter |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Max.cs | {
"start": 1910,
"end": 6364
} | partial class ____
{
public static async UniTask<TSource> MaxAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
TSource value = default;
var comparer = Comparer<TSource>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = e.Current;
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = e.Current;
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = selector(e.Current);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = selector(e.Current);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAwaitAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<TResult>> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = await selector(e.Current);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = await selector(e.Current);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
public static async UniTask<TResult> MaxAwaitWithCancellationAsync<TSource, TResult>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<TResult>> selector, CancellationToken cancellationToken)
{
TResult value = default;
var comparer = Comparer<TResult>.Default;
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
while (await e.MoveNextAsync())
{
value = await selector(e.Current, cancellationToken);
goto NEXT_LOOP;
}
return value;
NEXT_LOOP:
while (await e.MoveNextAsync())
{
var x = await selector(e.Current, cancellationToken);
if (comparer.Compare(value, x) < 0)
{
value = x;
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
return value;
}
}
} | Max |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/ChatCompletion/ChatHistoryReducers/ChatHistoryReducerTests.cs | {
"start": 4784,
"end": 6034
} | private sealed class ____(string result) : IChatCompletionService
{
public IReadOnlyDictionary<string, object?> Attributes { get; } = new Dictionary<string, object?>();
public Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
return Task.FromResult<IReadOnlyList<ChatMessageContent>>([new(AuthorRole.Assistant, result)]);
}
#pragma warning disable IDE0036 // Order modifiers
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
public async IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
#pragma warning restore IDE0036 // Order modifiers
{
yield return new StreamingChatMessageContent(AuthorRole.Assistant, result);
}
}
}
| FakeChatCompletionService |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 137570,
"end": 139416
} | public partial class ____ : global::System.IEquatable<DeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation>, IDeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation
{
public DeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation(global::System.String message)
{
Message = message;
}
public global::System.String Message { get; }
public virtual global::System.Boolean Equals(DeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (Message.Equals(other.Message));
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((DeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * Message.GetHashCode();
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| DeleteApiCommandMutation_DeleteApiById_Errors_UnauthorizedOperation |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/GossipService/NodeGossipServiceTests.cs | {
"start": 14811,
"end": 16095
} | public class ____ : NodeGossipServiceTestFixture {
private Message _capturedMessage;
protected override Message[] Given() =>
GivenSystemInitializedWithKnownGossipSeedSources(new GossipMessage.GossipReceived(
new CallbackEnvelope(CaptureGossipReply), new ClusterInfo(
MemberInfoForVNode(_nodeTwo, _timeProvider.UtcNow, epochNumber: 1, esVersion: "1.1.1.2"),
MemberInfoForVNode(_nodeThree, _timeProvider.UtcNow, epochNumber: 1, esVersion: "1.1.1.3")),
_nodeTwo.HttpEndPoint));
protected override Message When() =>
new GossipMessage.ReadGossip(new CallbackEnvelope(CaptureGossipReply));
private ClusterInfo GetExpectedClusterInfo() {
return new ClusterInfo(
MemberInfoForVNode(_currentNode, _timeProvider.UtcNow, esVersion: VersionInfo.DefaultVersion),
MemberInfoForVNode(_nodeTwo, _timeProvider.UtcNow, epochNumber: 1, esVersion: "1.1.1.2"),
MemberInfoForVNode(_nodeThree, _timeProvider.UtcNow, epochNumber: 1, esVersion: "1.1.1.3"));
}
[Test]
public void reply_should_have_version_info() {
_capturedMessage.Should()
.BeEquivalentTo(new GossipMessage.SendGossip(GetExpectedClusterInfo(), _currentNode.HttpEndPoint));
}
private void CaptureGossipReply(Message message) => _capturedMessage = message;
}
| if_gossip_read_reply_includes_es_version |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Saga/Injecting_Specs.cs | {
"start": 215,
"end": 1705
} | public class ____ :
InMemoryTestFixture
{
[Test]
public async Task The_saga_should_be_created_when_an_initiating_message_is_received()
{
var message = new InitiateSimpleSaga(_sagaId);
await InputQueueSendEndpoint.Send(message);
Guid? sagaId = await _repository.ShouldContainSaga(_sagaId, TestTimeout);
Assert.That(sagaId.HasValue, Is.True);
}
ISagaRepository<InjectingSampleSaga> _repository;
Dependency _dependency;
Guid _sagaId;
protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator)
{
_sagaId = NewId.NextGuid();
// this is our dependency, but could be dynamically resolved from a container in method
// below is so desired.
_dependency = new Dependency();
// create the actual saga repository
_repository = SetupSagaRepository<InjectingSampleSaga>();
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository, x => x.UseExecute(context => context.Saga.Dependency = _dependency));
}
static InMemorySagaRepository<TSaga> SetupSagaRepository<TSaga>()
where TSaga : class, ISaga
{
return new InMemorySagaRepository<TSaga>();
}
| Injecting_properties_into_a_saga |
csharp | AvaloniaUI__Avalonia | samples/VirtualizationDemo/ViewModels/PlaygroundItemViewModel.cs | {
"start": 60,
"end": 413
} | public class ____ : ViewModelBase
{
private string? _header;
public PlaygroundItemViewModel(int index) => Header = $"Item {index}";
public PlaygroundItemViewModel(string? header) => Header = header;
public string? Header
{
get => _header;
set => RaiseAndSetIfChanged(ref _header, value);
}
}
| PlaygroundItemViewModel |
csharp | dotnet__aspnetcore | src/Features/JsonPatch/src/Adapters/IAdapterFactory.cs | {
"start": 425,
"end": 893
} | public interface ____
{
/// <summary>
/// Creates an <see cref="IAdapter"/> for the current object
/// </summary>
/// <param name="target">The target object</param>
/// <param name="contractResolver">The current contract resolver</param>
/// <returns>The needed <see cref="IAdapter"/></returns>
#pragma warning disable PUB0001
IAdapter Create(object target, IContractResolver contractResolver);
#pragma warning restore PUB0001
}
| IAdapterFactory |
csharp | protobuf-net__protobuf-net | src/protobuf-net.Reflection/Parsers.cs | {
"start": 526,
"end": 782
} | internal interface ____<TRange, TField>
where TRange : IReservedRange
where TField : IField
{
List<string> ReservedNames { get; }
List<TRange> ReservedRanges { get; }
List<TField> Fields { get; }
}
| IReserved |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/Shapes/Shape.cs | {
"start": 366,
"end": 15755
} | public abstract class ____ : Control
{
/// <summary>
/// Defines the <see cref="Fill"/> property.
/// </summary>
public static readonly StyledProperty<IBrush?> FillProperty =
AvaloniaProperty.Register<Shape, IBrush?>(nameof(Fill));
/// <summary>
/// Defines the <see cref="Stretch"/> property.
/// </summary>
public static readonly StyledProperty<Stretch> StretchProperty =
AvaloniaProperty.Register<Shape, Stretch>(nameof(Stretch));
/// <summary>
/// Defines the <see cref="Stroke"/> property.
/// </summary>
public static readonly StyledProperty<IBrush?> StrokeProperty =
AvaloniaProperty.Register<Shape, IBrush?>(nameof(Stroke));
/// <summary>
/// Defines the <see cref="StrokeDashArray"/> property.
/// </summary>
public static readonly StyledProperty<AvaloniaList<double>?> StrokeDashArrayProperty =
AvaloniaProperty.Register<Shape, AvaloniaList<double>?>(nameof(StrokeDashArray));
/// <summary>
/// Defines the <see cref="StrokeDashOffset"/> property.
/// </summary>
public static readonly StyledProperty<double> StrokeDashOffsetProperty =
AvaloniaProperty.Register<Shape, double>(nameof(StrokeDashOffset));
/// <summary>
/// Defines the <see cref="StrokeThickness"/> property.
/// </summary>
public static readonly StyledProperty<double> StrokeThicknessProperty =
AvaloniaProperty.Register<Shape, double>(nameof(StrokeThickness));
/// <summary>
/// Defines the <see cref="StrokeLineCap"/> property.
/// </summary>
public static readonly StyledProperty<PenLineCap> StrokeLineCapProperty =
AvaloniaProperty.Register<Shape, PenLineCap>(nameof(StrokeLineCap), PenLineCap.Flat);
/// <summary>
/// Defines the <see cref="StrokeJoin"/> property.
/// </summary>
public static readonly StyledProperty<PenLineJoin> StrokeJoinProperty =
AvaloniaProperty.Register<Shape, PenLineJoin>(nameof(StrokeJoin), PenLineJoin.Miter);
/// <summary>
/// Defines the <see cref="StrokeMiterLimit"/> property.
/// </summary>
public static readonly StyledProperty<double> StrokeMiterLimitProperty =
AvaloniaProperty.Register<Shape, double>(nameof(StrokeMiterLimit), 10.0);
private Matrix _transform = Matrix.Identity;
private Geometry? _definingGeometry;
private Geometry? _renderedGeometry;
private IPen? _strokePen;
private EventHandler? _geometryChangedHandler;
/// <summary>
/// Gets a value that represents the <see cref="Geometry"/> of the shape.
/// </summary>
public Geometry? DefiningGeometry
{
get
{
if (_definingGeometry == null)
{
_definingGeometry = CreateDefiningGeometry();
if (_definingGeometry is not null && VisualRoot is not null)
{
_definingGeometry.Changed += GeometryChangedHandler;
}
}
return _definingGeometry;
}
}
/// <summary>
/// Gets a value that represents the final rendered <see cref="Geometry"/> of the shape.
/// </summary>
public Geometry? RenderedGeometry
{
get
{
if (_renderedGeometry == null && DefiningGeometry != null)
{
if (_transform == Matrix.Identity)
{
_renderedGeometry = DefiningGeometry;
}
else
{
_renderedGeometry = DefiningGeometry.Clone();
if (_renderedGeometry.Transform == null ||
_renderedGeometry.Transform.Value == Matrix.Identity)
{
_renderedGeometry.Transform = new MatrixTransform(_transform);
}
else
{
_renderedGeometry.Transform = new MatrixTransform(
_renderedGeometry.Transform.Value * _transform);
}
}
}
return _renderedGeometry;
}
}
/// <summary>
/// Gets or sets the <see cref="IBrush"/> that specifies how the shape's interior is painted.
/// </summary>
public IBrush? Fill
{
get => GetValue(FillProperty);
set => SetValue(FillProperty, value);
}
/// <summary>
/// Gets or sets a <see cref="Stretch"/> enumeration value that describes how the shape fills its allocated space.
/// </summary>
public Stretch Stretch
{
get => GetValue(StretchProperty);
set => SetValue(StretchProperty, value);
}
/// <summary>
/// Gets or sets the <see cref="IBrush"/> that specifies how the shape's outline is painted.
/// </summary>
public IBrush? Stroke
{
get => GetValue(StrokeProperty);
set => SetValue(StrokeProperty, value);
}
/// <summary>
/// Gets or sets a collection of <see cref="double"/> values that indicate the pattern of dashes and gaps that is used to outline shapes.
/// </summary>
public AvaloniaList<double>? StrokeDashArray
{
get => GetValue(StrokeDashArrayProperty);
set => SetValue(StrokeDashArrayProperty, value);
}
/// <summary>
/// Gets or sets a value that specifies the distance within the dash pattern where a dash begins.
/// </summary>
public double StrokeDashOffset
{
get => GetValue(StrokeDashOffsetProperty);
set => SetValue(StrokeDashOffsetProperty, value);
}
/// <summary>
/// Gets or sets the width of the shape outline.
/// </summary>
public double StrokeThickness
{
get => GetValue(StrokeThicknessProperty);
set => SetValue(StrokeThicknessProperty, value);
}
/// <summary>
/// Gets or sets a <see cref="PenLineCap"/> enumeration value that describes the shape at the ends of a line.
/// </summary>
public PenLineCap StrokeLineCap
{
get => GetValue(StrokeLineCapProperty);
set => SetValue(StrokeLineCapProperty, value);
}
/// <summary>
/// Gets or sets a <see cref="PenLineJoin"/> enumeration value that specifies the type of join that is used at the vertices of a Shape.
/// </summary>
public PenLineJoin StrokeJoin
{
get => GetValue(StrokeJoinProperty);
set => SetValue(StrokeJoinProperty, value);
}
/// <summary>
/// Gets or sets the limit on the ratio of the miter length to half the <see cref="StrokeThickness"/> of the pen.
/// </summary>
public double StrokeMiterLimit
{
get => GetValue(StrokeMiterLimitProperty);
set => SetValue(StrokeMiterLimitProperty, value);
}
private EventHandler GeometryChangedHandler => _geometryChangedHandler ??= OnGeometryChanged;
public sealed override void Render(DrawingContext context)
{
var geometry = RenderedGeometry;
if (geometry != null)
{
context.DrawGeometry(Fill, _strokePen, geometry);
}
}
/// <summary>
/// Marks a property as affecting the shape's geometry.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// After a call to this method in a control's static constructor, any change to the
/// property will cause <see cref="InvalidateGeometry"/> to be called on the element.
/// </remarks>
protected static void AffectsGeometry<TShape>(params AvaloniaProperty[] properties)
where TShape : Shape
{
foreach (var property in properties)
{
property.Changed.Subscribe(e =>
{
if (e.Sender is TShape shape)
{
AffectsGeometryInvalidate(shape, e);
}
});
}
}
/// <summary>
/// Creates the shape's defining geometry.
/// </summary>
/// <returns>Defining <see cref="Geometry"/> of the shape.</returns>
protected abstract Geometry? CreateDefiningGeometry();
/// <summary>
/// Called when the underlying <see cref="Geometry"/> changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnGeometryChanged(object? sender, EventArgs e)
{
_renderedGeometry = null;
InvalidateMeasure();
}
/// <summary>
/// Invalidates the geometry of this shape.
/// </summary>
protected void InvalidateGeometry()
{
if (_definingGeometry is not null)
{
_definingGeometry.Changed -= GeometryChangedHandler;
}
_renderedGeometry = null;
_definingGeometry = null;
InvalidateMeasure();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == StrokeProperty
|| change.Property == StrokeThicknessProperty
|| change.Property == StrokeDashArrayProperty
|| change.Property == StrokeDashOffsetProperty
|| change.Property == StrokeLineCapProperty
|| change.Property == StrokeJoinProperty
|| change.Property == StrokeMiterLimitProperty)
{
if (change.Property == StrokeProperty
|| change.Property == StrokeThicknessProperty)
{
InvalidateMeasure();
}
if (Pen.TryModifyOrCreate(ref _strokePen, Stroke, StrokeThickness, StrokeDashArray, StrokeDashOffset, StrokeLineCap, StrokeJoin, StrokeMiterLimit))
{
InvalidateVisual();
}
}
else if (change.Property == FillProperty)
{
InvalidateVisual();
}
}
protected override Size MeasureOverride(Size availableSize)
{
if (DefiningGeometry is null)
{
return default;
}
return CalculateSizeAndTransform(availableSize, DefiningGeometry.Bounds, Stretch).size;
}
protected override Size ArrangeOverride(Size finalSize)
{
if (DefiningGeometry != null)
{
// This should probably use GetRenderBounds(strokeThickness) but then the calculations
// will multiply the stroke thickness as well, which isn't correct.
var (_, transform) = CalculateSizeAndTransform(finalSize, DefiningGeometry.Bounds, Stretch);
if (_transform != transform)
{
_transform = transform;
_renderedGeometry = null;
}
return finalSize;
}
return default;
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
if (_definingGeometry is not null)
{
_definingGeometry.Changed += GeometryChangedHandler;
}
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (_definingGeometry is not null)
{
_definingGeometry.Changed -= GeometryChangedHandler;
}
}
internal static (Size size, Matrix transform) CalculateSizeAndTransform(Size availableSize, Rect shapeBounds, Stretch Stretch)
{
Size shapeSize = new Size(shapeBounds.Right, shapeBounds.Bottom);
Matrix translate = Matrix.Identity;
double desiredX = availableSize.Width;
double desiredY = availableSize.Height;
double sx = 0.0;
double sy = 0.0;
if (Stretch != Stretch.None)
{
shapeSize = shapeBounds.Size;
translate = Matrix.CreateTranslation(-(Vector)shapeBounds.Position);
}
if (double.IsInfinity(availableSize.Width))
{
desiredX = shapeSize.Width;
}
if (double.IsInfinity(availableSize.Height))
{
desiredY = shapeSize.Height;
}
if (shapeBounds.Width > 0)
{
sx = desiredX / shapeSize.Width;
}
if (shapeBounds.Height > 0)
{
sy = desiredY / shapeSize.Height;
}
if (double.IsInfinity(availableSize.Width))
{
sx = sy;
}
if (double.IsInfinity(availableSize.Height))
{
sy = sx;
}
switch (Stretch)
{
case Stretch.Uniform:
sx = sy = Math.Min(sx, sy);
break;
case Stretch.UniformToFill:
sx = sy = Math.Max(sx, sy);
break;
case Stretch.Fill:
if (double.IsInfinity(availableSize.Width))
{
sx = 1.0;
}
if (double.IsInfinity(availableSize.Height))
{
sy = 1.0;
}
break;
default:
sx = sy = 1;
break;
}
var transform = translate * Matrix.CreateScale(sx, sy);
var size = new Size(shapeSize.Width * sx, shapeSize.Height * sy);
return (size, transform);
}
private static void AffectsGeometryInvalidate(Shape control, AvaloniaPropertyChangedEventArgs e)
{
// If the geometry is invalidated when Bounds changes, only invalidate when the Size
// portion changes.
if (e.Property == BoundsProperty)
{
var oldBounds = (Rect)e.OldValue!;
var newBounds = (Rect)e.NewValue!;
if (oldBounds.Size == newBounds.Size)
{
return;
}
}
control.InvalidateGeometry();
}
}
}
| Shape |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Bson/Serialization/Serializers/Decimal128Serializer.cs | {
"start": 807,
"end": 7998
} | public sealed class ____ : StructSerializerBase<Decimal128>, IRepresentationConfigurable<Decimal128Serializer>, IRepresentationConverterConfigurable<Decimal128Serializer>
{
#region static
private static readonly Decimal128Serializer __instance = new Decimal128Serializer();
/// <summary>
/// Gets a cached instance of a Decimal128Serializer with Decimal128 representation.
/// </summary>
public static Decimal128Serializer Instance => __instance;
#endregion
// private fields
private readonly BsonType _representation;
private readonly RepresentationConverter _converter;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="Decimal128Serializer"/> class.
/// </summary>
public Decimal128Serializer()
: this(BsonType.Decimal128)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Decimal128Serializer"/> class.
/// </summary>
/// <param name="representation">The representation.</param>
public Decimal128Serializer(BsonType representation)
: this(representation, new RepresentationConverter(false, false))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Decimal128Serializer"/> class.
/// </summary>
/// <param name="representation">The representation.</param>
/// <param name="converter">The converter.</param>
public Decimal128Serializer(BsonType representation, RepresentationConverter converter)
{
switch (representation)
{
case BsonType.Decimal128:
case BsonType.Double:
case BsonType.Int32:
case BsonType.Int64:
case BsonType.String:
break;
default:
var message = string.Format("{0} is not a valid representation for a Decimal128Serializer.", representation);
throw new ArgumentException(message);
}
_representation = representation;
_converter = converter;
}
// public properties
/// <summary>
/// Gets the converter.
/// </summary>
/// <value>
/// The converter.
/// </value>
public RepresentationConverter Converter
{
get { return _converter; }
}
/// <summary>
/// Gets the representation.
/// </summary>
/// <value>
/// The representation.
/// </value>
public BsonType Representation
{
get { return _representation; }
}
// public methods
/// <summary>
/// Deserializes a value.
/// </summary>
/// <param name="context">The deserialization context.</param>
/// <param name="args">The deserialization args.</param>
/// <returns>A deserialized value.</returns>
public override Decimal128 Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var bsonReader = context.Reader;
var bsonType = bsonReader.GetCurrentBsonType();
switch (bsonType)
{
case BsonType.Decimal128:
return bsonReader.ReadDecimal128();
case BsonType.Double:
return _converter.ToDecimal128(bsonReader.ReadDouble());
case BsonType.Int32:
return _converter.ToDecimal128(bsonReader.ReadInt32());
case BsonType.Int64:
return _converter.ToDecimal128(bsonReader.ReadInt64());
case BsonType.String:
return JsonConvert.ToDecimal128(bsonReader.ReadString());
default:
throw CreateCannotDeserializeFromBsonTypeException(bsonType);
}
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null)) { return false; }
if (object.ReferenceEquals(this, obj)) { return true; }
return
base.Equals(obj) &&
obj is Decimal128Serializer other &&
object.Equals(_converter, other._converter) &&
_representation.Equals(other._representation);
}
/// <inheritdoc/>
public override int GetHashCode() => 0;
/// <summary>
/// Serializes a value.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="args">The serialization args.</param>
/// <param name="value">The object.</param>
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Decimal128 value)
{
var bsonWriter = context.Writer;
switch (_representation)
{
case BsonType.Decimal128:
bsonWriter.WriteDecimal128(value);
break;
case BsonType.Double:
bsonWriter.WriteDouble(_converter.ToDouble(value));
break;
case BsonType.Int32:
bsonWriter.WriteInt32(_converter.ToInt32(value));
break;
case BsonType.Int64:
bsonWriter.WriteInt64(_converter.ToInt64(value));
break;
case BsonType.String:
bsonWriter.WriteString(JsonConvert.ToString(value));
break;
default:
var message = string.Format("'{0}' is not a valid Decimal128 representation.", _representation);
throw new BsonSerializationException(message);
}
}
/// <summary>
/// Returns a serializer that has been reconfigured with the specified item serializer.
/// </summary>
/// <param name="converter">The converter.</param>
/// <returns>The reconfigured serializer.</returns>
public Decimal128Serializer WithConverter(RepresentationConverter converter)
{
if (converter == _converter)
{
return this;
}
else
{
return new Decimal128Serializer(_representation, converter);
}
}
/// <summary>
/// Returns a serializer that has been reconfigured with the specified representation.
/// </summary>
/// <param name="representation">The representation.</param>
/// <returns>The reconfigured serializer.</returns>
public Decimal128Serializer WithRepresentation(BsonType representation)
{
if (representation == _representation)
{
return this;
}
else
{
return new Decimal128Serializer(representation, _converter);
}
}
// explicit | Decimal128Serializer |
csharp | open-telemetry__opentelemetry-dotnet | test/OpenTelemetry.Tests/Logs/BatchExportLogRecordProcessorOptionsTests.cs | {
"start": 172,
"end": 4096
} | public sealed class ____ : IDisposable
{
public BatchExportLogRecordProcessorOptionsTests()
{
ClearEnvVars();
}
public void Dispose()
{
ClearEnvVars();
GC.SuppressFinalize(this);
}
[Fact]
public void BatchExportLogRecordProcessorOptions_Defaults()
{
var options = new BatchExportLogRecordProcessorOptions();
Assert.Equal(30000, options.ExporterTimeoutMilliseconds);
Assert.Equal(512, options.MaxExportBatchSize);
Assert.Equal(2048, options.MaxQueueSize);
Assert.Equal(5000, options.ScheduledDelayMilliseconds);
}
[Fact]
public void BatchExportLogRecordProcessorOptions_EnvironmentVariableOverride()
{
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.ExporterTimeoutEnvVarKey, "1");
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.MaxExportBatchSizeEnvVarKey, "2");
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.MaxQueueSizeEnvVarKey, "3");
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.ScheduledDelayEnvVarKey, "4");
var options = new BatchExportLogRecordProcessorOptions();
Assert.Equal(1, options.ExporterTimeoutMilliseconds);
Assert.Equal(2, options.MaxExportBatchSize);
Assert.Equal(3, options.MaxQueueSize);
Assert.Equal(4, options.ScheduledDelayMilliseconds);
}
[Fact]
public void ExportLogRecordProcessorOptions_UsingIConfiguration()
{
var values = new Dictionary<string, string?>()
{
[BatchExportLogRecordProcessorOptions.MaxQueueSizeEnvVarKey] = "1",
[BatchExportLogRecordProcessorOptions.MaxExportBatchSizeEnvVarKey] = "2",
[BatchExportLogRecordProcessorOptions.ExporterTimeoutEnvVarKey] = "3",
[BatchExportLogRecordProcessorOptions.ScheduledDelayEnvVarKey] = "4",
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(values)
.Build();
var options = new BatchExportLogRecordProcessorOptions(configuration);
Assert.Equal(1, options.MaxQueueSize);
Assert.Equal(2, options.MaxExportBatchSize);
Assert.Equal(3, options.ExporterTimeoutMilliseconds);
Assert.Equal(4, options.ScheduledDelayMilliseconds);
}
[Fact]
public void BatchExportLogRecordProcessorOptions_SetterOverridesEnvironmentVariable()
{
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.ExporterTimeoutEnvVarKey, "123");
var options = new BatchExportLogRecordProcessorOptions
{
ExporterTimeoutMilliseconds = 89000,
};
Assert.Equal(89000, options.ExporterTimeoutMilliseconds);
}
[Fact]
public void BatchExportLogRecordProcessorOptions_EnvironmentVariableNames()
{
Assert.Equal("OTEL_BLRP_EXPORT_TIMEOUT", BatchExportLogRecordProcessorOptions.ExporterTimeoutEnvVarKey);
Assert.Equal("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE", BatchExportLogRecordProcessorOptions.MaxExportBatchSizeEnvVarKey);
Assert.Equal("OTEL_BLRP_MAX_QUEUE_SIZE", BatchExportLogRecordProcessorOptions.MaxQueueSizeEnvVarKey);
Assert.Equal("OTEL_BLRP_SCHEDULE_DELAY", BatchExportLogRecordProcessorOptions.ScheduledDelayEnvVarKey);
}
private static void ClearEnvVars()
{
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.ExporterTimeoutEnvVarKey, null);
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.MaxExportBatchSizeEnvVarKey, null);
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.MaxQueueSizeEnvVarKey, null);
Environment.SetEnvironmentVariable(BatchExportLogRecordProcessorOptions.ScheduledDelayEnvVarKey, null);
}
}
| BatchExportLogRecordProcessorOptionsTests |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/FeatureMatrix/Shapes/ShapeConverters.cs | {
"start": 1868,
"end": 2620
} | public class ____ : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string dashArray && !string.IsNullOrWhiteSpace(dashArray))
{
var collection = new DoubleCollection();
var values = dashArray.Split(',');
foreach (var val in values)
{
if (double.TryParse(val.Trim(), out double dashValue))
{
collection.Add(dashValue);
}
}
return collection;
}
return new DoubleCollection();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is DoubleCollection collection)
{
return string.Join(",", collection);
}
return string.Empty;
}
}
| StringToDoubleCollectionConverter |
csharp | ShareX__ShareX | ShareX.HelpersLib/Native/NativeEnums.cs | {
"start": 113710,
"end": 130492
} | public enum ____ : ushort
{
///<summary>
///Left mouse button
///</summary>
LBUTTON = 0x01,
///<summary>
///Right mouse button
///</summary>
RBUTTON = 0x02,
///<summary>
///Control-break processing
///</summary>
CANCEL = 0x03,
///<summary>
///Middle mouse button (three-button mouse)
///</summary>
MBUTTON = 0x04,
///<summary>
///Windows 2000/XP: X1 mouse button
///</summary>
XBUTTON1 = 0x05,
///<summary>
///Windows 2000/XP: X2 mouse button
///</summary>
XBUTTON2 = 0x06,
///<summary>
///BACKSPACE key
///</summary>
BACK = 0x08,
///<summary>
///TAB key
///</summary>
TAB = 0x09,
///<summary>
///CLEAR key
///</summary>
CLEAR = 0x0C,
///<summary>
///ENTER key
///</summary>
RETURN = 0x0D,
///<summary>
///SHIFT key
///</summary>
SHIFT = 0x10,
///<summary>
///CTRL key
///</summary>
CONTROL = 0x11,
///<summary>
///ALT key
///</summary>
MENU = 0x12,
///<summary>
///PAUSE key
///</summary>
PAUSE = 0x13,
///<summary>
///CAPS LOCK key
///</summary>
CAPITAL = 0x14,
///<summary>
///Input Method Editor (IME) Kana mode
///</summary>
KANA = 0x15,
///<summary>
///IME Hangul mode
///</summary>
HANGUL = 0x15,
///<summary>
///IME Junja mode
///</summary>
JUNJA = 0x17,
///<summary>
///IME final mode
///</summary>
FINAL = 0x18,
///<summary>
///IME Hanja mode
///</summary>
HANJA = 0x19,
///<summary>
///IME Kanji mode
///</summary>
KANJI = 0x19,
///<summary>
///ESC key
///</summary>
ESCAPE = 0x1B,
///<summary>
///IME convert
///</summary>
CONVERT = 0x1C,
///<summary>
///IME nonconvert
///</summary>
NONCONVERT = 0x1D,
///<summary>
///IME accept
///</summary>
ACCEPT = 0x1E,
///<summary>
///IME mode change request
///</summary>
MODECHANGE = 0x1F,
///<summary>
///SPACEBAR
///</summary>
SPACE = 0x20,
///<summary>
///PAGE UP key
///</summary>
PRIOR = 0x21,
///<summary>
///PAGE DOWN key
///</summary>
NEXT = 0x22,
///<summary>
///END key
///</summary>
END = 0x23,
///<summary>
///HOME key
///</summary>
HOME = 0x24,
///<summary>
///LEFT ARROW key
///</summary>
LEFT = 0x25,
///<summary>
///UP ARROW key
///</summary>
UP = 0x26,
///<summary>
///RIGHT ARROW key
///</summary>
RIGHT = 0x27,
///<summary>
///DOWN ARROW key
///</summary>
DOWN = 0x28,
///<summary>
///SELECT key
///</summary>
SELECT = 0x29,
///<summary>
///PRINT key
///</summary>
PRINT = 0x2A,
///<summary>
///EXECUTE key
///</summary>
EXECUTE = 0x2B,
///<summary>
///PRINT SCREEN key
///</summary>
SNAPSHOT = 0x2C,
///<summary>
///INS key
///</summary>
INSERT = 0x2D,
///<summary>
///DEL key
///</summary>
DELETE = 0x2E,
///<summary>
///HELP key
///</summary>
HELP = 0x2F,
///<summary>
///0 key
///</summary>
KEY_0 = 0x30,
///<summary>
///1 key
///</summary>
KEY_1 = 0x31,
///<summary>
///2 key
///</summary>
KEY_2 = 0x32,
///<summary>
///3 key
///</summary>
KEY_3 = 0x33,
///<summary>
///4 key
///</summary>
KEY_4 = 0x34,
///<summary>
///5 key
///</summary>
KEY_5 = 0x35,
///<summary>
///6 key
///</summary>
KEY_6 = 0x36,
///<summary>
///7 key
///</summary>
KEY_7 = 0x37,
///<summary>
///8 key
///</summary>
KEY_8 = 0x38,
///<summary>
///9 key
///</summary>
KEY_9 = 0x39,
///<summary>
///A key
///</summary>
KEY_A = 0x41,
///<summary>
///B key
///</summary>
KEY_B = 0x42,
///<summary>
///C key
///</summary>
KEY_C = 0x43,
///<summary>
///D key
///</summary>
KEY_D = 0x44,
///<summary>
///E key
///</summary>
KEY_E = 0x45,
///<summary>
///F key
///</summary>
KEY_F = 0x46,
///<summary>
///G key
///</summary>
KEY_G = 0x47,
///<summary>
///H key
///</summary>
KEY_H = 0x48,
///<summary>
///I key
///</summary>
KEY_I = 0x49,
///<summary>
///J key
///</summary>
KEY_J = 0x4A,
///<summary>
///K key
///</summary>
KEY_K = 0x4B,
///<summary>
///L key
///</summary>
KEY_L = 0x4C,
///<summary>
///M key
///</summary>
KEY_M = 0x4D,
///<summary>
///N key
///</summary>
KEY_N = 0x4E,
///<summary>
///O key
///</summary>
KEY_O = 0x4F,
///<summary>
///P key
///</summary>
KEY_P = 0x50,
///<summary>
///Q key
///</summary>
KEY_Q = 0x51,
///<summary>
///R key
///</summary>
KEY_R = 0x52,
///<summary>
///S key
///</summary>
KEY_S = 0x53,
///<summary>
///T key
///</summary>
KEY_T = 0x54,
///<summary>
///U key
///</summary>
KEY_U = 0x55,
///<summary>
///V key
///</summary>
KEY_V = 0x56,
///<summary>
///W key
///</summary>
KEY_W = 0x57,
///<summary>
///X key
///</summary>
KEY_X = 0x58,
///<summary>
///Y key
///</summary>
KEY_Y = 0x59,
///<summary>
///Z key
///</summary>
KEY_Z = 0x5A,
///<summary>
///Left Windows key (Microsoft Natural keyboard)
///</summary>
LWIN = 0x5B,
///<summary>
///Right Windows key (Natural keyboard)
///</summary>
RWIN = 0x5C,
///<summary>
///Applications key (Natural keyboard)
///</summary>
APPS = 0x5D,
///<summary>
///Computer Sleep key
///</summary>
SLEEP = 0x5F,
///<summary>
///Numeric keypad 0 key
///</summary>
NUMPAD0 = 0x60,
///<summary>
///Numeric keypad 1 key
///</summary>
NUMPAD1 = 0x61,
///<summary>
///Numeric keypad 2 key
///</summary>
NUMPAD2 = 0x62,
///<summary>
///Numeric keypad 3 key
///</summary>
NUMPAD3 = 0x63,
///<summary>
///Numeric keypad 4 key
///</summary>
NUMPAD4 = 0x64,
///<summary>
///Numeric keypad 5 key
///</summary>
NUMPAD5 = 0x65,
///<summary>
///Numeric keypad 6 key
///</summary>
NUMPAD6 = 0x66,
///<summary>
///Numeric keypad 7 key
///</summary>
NUMPAD7 = 0x67,
///<summary>
///Numeric keypad 8 key
///</summary>
NUMPAD8 = 0x68,
///<summary>
///Numeric keypad 9 key
///</summary>
NUMPAD9 = 0x69,
///<summary>
///Multiply key
///</summary>
MULTIPLY = 0x6A,
///<summary>
///Add key
///</summary>
ADD = 0x6B,
///<summary>
///Separator key
///</summary>
SEPARATOR = 0x6C,
///<summary>
///Subtract key
///</summary>
SUBTRACT = 0x6D,
///<summary>
///Decimal key
///</summary>
DECIMAL = 0x6E,
///<summary>
///Divide key
///</summary>
DIVIDE = 0x6F,
///<summary>
///F1 key
///</summary>
F1 = 0x70,
///<summary>
///F2 key
///</summary>
F2 = 0x71,
///<summary>
///F3 key
///</summary>
F3 = 0x72,
///<summary>
///F4 key
///</summary>
F4 = 0x73,
///<summary>
///F5 key
///</summary>
F5 = 0x74,
///<summary>
///F6 key
///</summary>
F6 = 0x75,
///<summary>
///F7 key
///</summary>
F7 = 0x76,
///<summary>
///F8 key
///</summary>
F8 = 0x77,
///<summary>
///F9 key
///</summary>
F9 = 0x78,
///<summary>
///F10 key
///</summary>
F10 = 0x79,
///<summary>
///F11 key
///</summary>
F11 = 0x7A,
///<summary>
///F12 key
///</summary>
F12 = 0x7B,
///<summary>
///F13 key
///</summary>
F13 = 0x7C,
///<summary>
///F14 key
///</summary>
F14 = 0x7D,
///<summary>
///F15 key
///</summary>
F15 = 0x7E,
///<summary>
///F16 key
///</summary>
F16 = 0x7F,
///<summary>
///F17 key
///</summary>
F17 = 0x80,
///<summary>
///F18 key
///</summary>
F18 = 0x81,
///<summary>
///F19 key
///</summary>
F19 = 0x82,
///<summary>
///F20 key
///</summary>
F20 = 0x83,
///<summary>
///F21 key
///</summary>
F21 = 0x84,
///<summary>
///F22 key, (PPC only) Key used to lock device.
///</summary>
F22 = 0x85,
///<summary>
///F23 key
///</summary>
F23 = 0x86,
///<summary>
///F24 key
///</summary>
F24 = 0x87,
///<summary>
///NUM LOCK key
///</summary>
NUMLOCK = 0x90,
///<summary>
///SCROLL LOCK key
///</summary>
SCROLL = 0x91,
///<summary>
///Left SHIFT key
///</summary>
LSHIFT = 0xA0,
///<summary>
///Right SHIFT key
///</summary>
RSHIFT = 0xA1,
///<summary>
///Left CONTROL key
///</summary>
LCONTROL = 0xA2,
///<summary>
///Right CONTROL key
///</summary>
RCONTROL = 0xA3,
///<summary>
///Left MENU key
///</summary>
LMENU = 0xA4,
///<summary>
///Right MENU key
///</summary>
RMENU = 0xA5,
///<summary>
///Windows 2000/XP: Browser Back key
///</summary>
BROWSER_BACK = 0xA6,
///<summary>
///Windows 2000/XP: Browser Forward key
///</summary>
BROWSER_FORWARD = 0xA7,
///<summary>
///Windows 2000/XP: Browser Refresh key
///</summary>
BROWSER_REFRESH = 0xA8,
///<summary>
///Windows 2000/XP: Browser Stop key
///</summary>
BROWSER_STOP = 0xA9,
///<summary>
///Windows 2000/XP: Browser Search key
///</summary>
BROWSER_SEARCH = 0xAA,
///<summary>
///Windows 2000/XP: Browser Favorites key
///</summary>
BROWSER_FAVORITES = 0xAB,
///<summary>
///Windows 2000/XP: Browser Start and Home key
///</summary>
BROWSER_HOME = 0xAC,
///<summary>
///Windows 2000/XP: Volume Mute key
///</summary>
VOLUME_MUTE = 0xAD,
///<summary>
///Windows 2000/XP: Volume Down key
///</summary>
VOLUME_DOWN = 0xAE,
///<summary>
///Windows 2000/XP: Volume Up key
///</summary>
VOLUME_UP = 0xAF,
///<summary>
///Windows 2000/XP: Next Track key
///</summary>
MEDIA_NEXT_TRACK = 0xB0,
///<summary>
///Windows 2000/XP: Previous Track key
///</summary>
MEDIA_PREV_TRACK = 0xB1,
///<summary>
///Windows 2000/XP: Stop Media key
///</summary>
MEDIA_STOP = 0xB2,
///<summary>
///Windows 2000/XP: Play/Pause Media key
///</summary>
MEDIA_PLAY_PAUSE = 0xB3,
///<summary>
///Windows 2000/XP: Start Mail key
///</summary>
LAUNCH_MAIL = 0xB4,
///<summary>
///Windows 2000/XP: Select Media key
///</summary>
LAUNCH_MEDIA_SELECT = 0xB5,
///<summary>
///Windows 2000/XP: Start Application 1 key
///</summary>
LAUNCH_APP1 = 0xB6,
///<summary>
///Windows 2000/XP: Start Application 2 key
///</summary>
LAUNCH_APP2 = 0xB7,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_1 = 0xBA,
///<summary>
///Windows 2000/XP: For any country/region, the '+' key
///</summary>
OEM_PLUS = 0xBB,
///<summary>
///Windows 2000/XP: For any country/region, the ',' key
///</summary>
OEM_COMMA = 0xBC,
///<summary>
///Windows 2000/XP: For any country/region, the '-' key
///</summary>
OEM_MINUS = 0xBD,
///<summary>
///Windows 2000/XP: For any country/region, the '.' key
///</summary>
OEM_PERIOD = 0xBE,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_2 = 0xBF,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_3 = 0xC0,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_4 = 0xDB,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_5 = 0xDC,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_6 = 0xDD,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_7 = 0xDE,
///<summary>
///Used for miscellaneous characters; it can vary by keyboard.
///</summary>
OEM_8 = 0xDF,
///<summary>
///Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
///</summary>
OEM_102 = 0xE2,
///<summary>
///Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
///</summary>
PROCESSKEY = 0xE5,
///<summary>
///Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes.
///The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information,
///see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
///</summary>
PACKET = 0xE7,
///<summary>
///Attn key
///</summary>
ATTN = 0xF6,
///<summary>
///CrSel key
///</summary>
CRSEL = 0xF7,
///<summary>
///ExSel key
///</summary>
EXSEL = 0xF8,
///<summary>
///Erase EOF key
///</summary>
EREOF = 0xF9,
///<summary>
///Play key
///</summary>
PLAY = 0xFA,
///<summary>
///Zoom key
///</summary>
ZOOM = 0xFB,
///<summary>
///Reserved
///</summary>
NONAME = 0xFC,
///<summary>
///PA1 key
///</summary>
PA1 = 0xFD,
///<summary>
///Clear key
///</summary>
OEM_CLEAR = 0xFE
}
| VirtualKeyCode |
csharp | ServiceStack__ServiceStack | ServiceStack.Blazor/tests/UI.Gallery/Gallery.Server/Pages/AutoQueryGrids/ContactsMeta.razor.cs | {
"start": 3584,
"end": 3696
} | public class ____ : IDeleteDb<Contact>, IReturnVoid
{
public int Id { get; set; }
}
// Data Model
| DeleteContact |
csharp | dotnet__machinelearning | src/Microsoft.ML.StandardTrainers/Standard/MulticlassClassification/OneVersusAllTrainer.cs | {
"start": 5669,
"end": 6010
} | class ____ all other classes. Prediction is then performed by running these binary classifiers, "
+ "and choosing the prediction with the highest confidence score.";
private readonly Options _options;
/// <summary>
/// Options passed to <see cref="OneVersusAllTrainer"/>
/// </summary>
| from |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_Frame.cs | {
"start": 19407,
"end": 19684
} | public partial class ____ : Page
{
public ExceptionInOnNavigatedToPage()
{
}
protected
#if HAS_UNO
internal
#endif
override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
throw new NotSupportedException("Crashed");
}
}
| ExceptionInOnNavigatedToPage |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding101OneToManyTestBase.cs | {
"start": 7610,
"end": 7934
} | public class ____
{
public int Id { get; set; }
[Required]
public Blog Blog { get; set; }
}
public DbSet<Blog> Blogs
=> Set<Blog>();
public DbSet<Post> Posts
=> Set<Post>();
}
| Post |
csharp | NSubstitute__NSubstitute | src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs | {
"start": 103,
"end": 1423
} | public class ____(ICallFactory callFactory, IArgumentSpecificationDequeue argSpecificationDequeue)
{
public virtual ICall Map(IInvocation castleInvocation)
{
Func<object>? baseMethod = null;
if (castleInvocation.InvocationTarget != null &&
castleInvocation.MethodInvocationTarget.IsVirtual &&
!castleInvocation.MethodInvocationTarget.IsAbstract)
{
baseMethod = CreateBaseResultInvocation(castleInvocation);
}
var queuedArgSpecifications = argSpecificationDequeue.DequeueAllArgumentSpecificationsForMethod(castleInvocation.Arguments.Length);
return callFactory.Create(castleInvocation.Method, castleInvocation.Arguments, castleInvocation.Proxy, queuedArgSpecifications, baseMethod);
}
private static Func<object> CreateBaseResultInvocation(IInvocation invocation)
{
// Notice, it's important to keep this as a separate method, as methods with lambda closures
// always allocate, even if delegate is not actually constructed.
// This way we make allocation only if indeed required.
Func<object> baseResult = () => { invocation.Proceed(); return invocation.ReturnValue; };
var result = new Lazy<object>(baseResult);
return () => result.Value;
}
}
| CastleInvocationMapper |
csharp | dotnet__aspnetcore | src/Identity/test/Identity.FunctionalTests/Pages/Account/ExternalLogin.cs | {
"start": 255,
"end": 2038
} | public class ____ : DefaultUIPage
{
private readonly IHtmlFormElement _emailForm;
public ExternalLogin(
HttpClient client,
IHtmlDocument externalLogin,
DefaultUIContext context)
: base(client, externalLogin, context)
{
_emailForm = HtmlAssert.HasForm(Document);
Title = HtmlAssert.HasElement("#external-login-title", Document);
Description = HtmlAssert.HasElement("#external-login-description", Document);
}
public IHtmlElement Title { get; }
public IHtmlElement Description { get; }
public async Task<Index> SendEmailAsync(string email)
{
var response = await Client.SendAsync(_emailForm, new Dictionary<string, string>
{
["Input_Email"] = email
});
var redirect = ResponseAssert.IsRedirect(response);
var indexResponse = await Client.GetAsync(redirect);
var index = await ResponseAssert.IsHtmlDocumentAsync(indexResponse);
return new Index(Client, index, Context.WithAuthenticatedUser());
}
public async Task<RegisterConfirmation> SendEmailWithConfirmationAsync(string email, bool hasRealEmail)
{
var response = await Client.SendAsync(_emailForm, new Dictionary<string, string>
{
["Input_Email"] = email
});
var redirect = ResponseAssert.IsRedirect(response);
Assert.Equal(RegisterConfirmation.Path + "?email=" + email, redirect.ToString(), StringComparer.OrdinalIgnoreCase);
var registerResponse = await Client.GetAsync(redirect);
var register = await ResponseAssert.IsHtmlDocumentAsync(registerResponse);
return new RegisterConfirmation(Client, register, hasRealEmail ? Context.WithRealEmailSender() : Context);
}
}
| ExternalLogin |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/ModelBuilding/InMemoryModelBuilderGenericRelationshipStringTest.cs | {
"start": 7151,
"end": 8025
} | class
____ TRelatedEntity : class
{
public override TestReferenceCollectionBuilder<TRelatedEntity, TEntity> WithMany(
Expression<Func<TRelatedEntity, IEnumerable<TEntity>?>>? navigationExpression = null)
=> new GenericStringTestReferenceCollectionBuilder<TRelatedEntity, TEntity>(
ReferenceNavigationBuilder.WithMany(
navigationExpression?.GetMemberAccess().GetSimpleMemberName()));
public override TestReferenceReferenceBuilder<TEntity, TRelatedEntity> WithOne(
Expression<Func<TRelatedEntity, TEntity?>>? navigationExpression = null)
=> new GenericStringTestReferenceReferenceBuilder<TEntity, TRelatedEntity>(
ReferenceNavigationBuilder.WithOne(
navigationExpression?.GetMemberAccess().GetSimpleMemberName()));
}
| where |
csharp | dotnet__orleans | src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs | {
"start": 7372,
"end": 7947
} | public partial class ____ : Grain, IFaultInjectionTransactionCoordinatorGrain, IGrainWithGuidKey, IGrain, Runtime.IAddressable
{
public System.Threading.Tasks.Task MultiGrainAddAndFaultInjection(System.Collections.Generic.List<IFaultInjectionTransactionTestGrain> grains, int numberToAdd, FaultInjectionControl faultInjection = null) { throw null; }
public System.Threading.Tasks.Task MultiGrainSet(System.Collections.Generic.List<IFaultInjectionTransactionTestGrain> grains, int newValue) { throw null; }
}
| FaultInjectionTransactionCoordinatorGrain |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp/Runtime/Serialization/BinarySerializationHelper.cs | {
"start": 4153,
"end": 4330
} | class ____ used in deserializing to allow deserializing objects that are defined
/// in assemlies that are load in runtime (like PlugIns).
/// </summary>
| is |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 5136353,
"end": 5142485
} | public partial class ____ : global::StrawberryShake.IOperationResultDataFactory<global::ChilliCream.Nitro.CommandLine.Cloud.Client.ValidateFusionConfigurationPublishResult>
{
public ValidateFusionConfigurationPublishResultFactory()
{
}
global::System.Type global::StrawberryShake.IOperationResultDataFactory.ResultType => typeof(global::ChilliCream.Nitro.CommandLine.Cloud.Client.IValidateFusionConfigurationPublishResult);
public ValidateFusionConfigurationPublishResult Create(global::StrawberryShake.IOperationResultDataInfo dataInfo, global::StrawberryShake.IEntityStoreSnapshot? snapshot = null)
{
if (dataInfo is ValidateFusionConfigurationPublishResultInfo info)
{
return new ValidateFusionConfigurationPublishResult(MapNonNullableIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition(info.ValidateFusionConfigurationComposition));
}
throw new global::System.ArgumentException("ValidateFusionConfigurationPublishResultInfo expected.");
}
private global::ChilliCream.Nitro.CommandLine.Cloud.Client.IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition MapNonNullableIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition(global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ValidateFusionConfigurationCompositionPayloadData data)
{
IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition returnValue = default !;
if (data.__typename.Equals("ValidateFusionConfigurationCompositionPayload", global::System.StringComparison.Ordinal))
{
returnValue = new ValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_ValidateFusionConfigurationCompositionPayload(MapIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_ErrorsNonNullableArray(data.Errors));
}
else
{
throw new global::System.NotSupportedException();
}
return returnValue;
}
private global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors>? MapIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_ErrorsNonNullableArray(global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.IValidateFusionConfigurationCompositionErrorData>? list)
{
if (list is null)
{
return null;
}
var validateFusionConfigurationCompositionErrors = new global::System.Collections.Generic.List<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors>();
foreach (global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.IValidateFusionConfigurationCompositionErrorData child in list)
{
validateFusionConfigurationCompositionErrors.Add(MapNonNullableIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors(child));
}
return validateFusionConfigurationCompositionErrors;
}
private global::ChilliCream.Nitro.CommandLine.Cloud.Client.IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors MapNonNullableIValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors(global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.IValidateFusionConfigurationCompositionErrorData data)
{
IValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors? returnValue;
if (data is global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.UnauthorizedOperationData unauthorizedOperation)
{
returnValue = new global::ChilliCream.Nitro.CommandLine.Cloud.Client.ValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors_UnauthorizedOperation(unauthorizedOperation.__typename ?? throw new global::System.ArgumentNullException(), unauthorizedOperation.Message ?? throw new global::System.ArgumentNullException());
}
else if (data is global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.FusionConfigurationRequestNotFoundErrorData fusionConfigurationRequestNotFoundError)
{
returnValue = new global::ChilliCream.Nitro.CommandLine.Cloud.Client.ValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors_FusionConfigurationRequestNotFoundError(fusionConfigurationRequestNotFoundError.__typename ?? throw new global::System.ArgumentNullException(), fusionConfigurationRequestNotFoundError.Message ?? throw new global::System.ArgumentNullException());
}
else if (data is global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.InvalidProcessingStateTransitionErrorData invalidProcessingStateTransitionError)
{
returnValue = new global::ChilliCream.Nitro.CommandLine.Cloud.Client.ValidateFusionConfigurationPublish_ValidateFusionConfigurationComposition_Errors_InvalidProcessingStateTransitionError(invalidProcessingStateTransitionError.__typename ?? throw new global::System.ArgumentNullException(), invalidProcessingStateTransitionError.Message ?? throw new global::System.ArgumentNullException());
}
else
{
throw new global::System.NotSupportedException();
}
return returnValue;
}
global::System.Object global::StrawberryShake.IOperationResultDataFactory.Create(global::StrawberryShake.IOperationResultDataInfo dataInfo, global::StrawberryShake.IEntityStoreSnapshot? snapshot)
{
return Create(dataInfo, snapshot);
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| ValidateFusionConfigurationPublishResultFactory |
csharp | neuecc__MessagePack-CSharp | src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Extension/UnityBlitResolver.cs | {
"start": 2257,
"end": 3238
} | internal static class ____
{
private static readonly Dictionary<Type, Type> FormatterMap = new Dictionary<Type, Type>()
{
{ typeof(Vector2[]), typeof(Vector2ArrayBlitFormatter) },
{ typeof(Vector3[]), typeof(Vector3ArrayBlitFormatter) },
{ typeof(Vector4[]), typeof(Vector4ArrayBlitFormatter) },
{ typeof(Quaternion[]), typeof(QuaternionArrayBlitFormatter) },
{ typeof(Color[]), typeof(ColorArrayBlitFormatter) },
{ typeof(Bounds[]), typeof(BoundsArrayBlitFormatter) },
{ typeof(Rect[]), typeof(RectArrayBlitFormatter) },
};
internal static object? GetFormatter(Type t)
{
Type formatterType;
if (FormatterMap.TryGetValue(t, out formatterType))
{
return Activator.CreateInstance(formatterType);
}
return null;
}
}
| UnityBlitResolverGetFormatterHelper |
csharp | dotnet__reactive | Ix.NET/Source/System.Interactive.Async.Tests/System/Linq/Operators/Throw.cs | {
"start": 305,
"end": 689
} | public class ____ : AsyncEnumerableExTests
{
[Fact]
public async Task Throw1()
{
var ex = new Exception("Bang!");
var xs = AsyncEnumerableEx.Throw<int>(ex);
var e = xs.GetAsyncEnumerator();
await AssertThrowsAsync(e.MoveNextAsync(), ex);
Assert.False(await e.MoveNextAsync());
}
}
}
| Throw |
csharp | unoplatform__uno | src/Uno.UI.Tests.ViewLibrary/TestInitializer.cs | {
"start": 239,
"end": 394
} | public class ____
{
public static bool IsInitialized { get; private set; }
public TestInitializer()
{
IsInitialized = true;
}
}
}
| TestInitializer |
csharp | open-telemetry__opentelemetry-dotnet | src/OpenTelemetry.Exporter.OpenTelemetryProtocol/PersistentStorage/FileBlob.cs | {
"start": 455,
"end": 3430
} | public class ____ : PersistentBlob
#endif
{
private readonly DirectorySizeTracker? directorySizeTracker;
/// <summary>
/// Initializes a new instance of the <see cref="FileBlob"/>
/// class.
/// </summary>
/// <param name="fullPath">Absolute file path of the blob.</param>
public FileBlob(string fullPath)
: this(fullPath, null)
{
}
internal FileBlob(string fullPath, DirectorySizeTracker? directorySizeTracker)
{
this.FullPath = fullPath;
this.directorySizeTracker = directorySizeTracker;
}
public string FullPath { get; private set; }
protected override bool OnTryRead([NotNullWhen(true)] out byte[]? buffer)
{
try
{
buffer = File.ReadAllBytes(this.FullPath);
}
catch (Exception ex)
{
PersistentStorageEventSource.Log.CouldNotReadFileBlob(this.FullPath, ex);
buffer = null;
return false;
}
return true;
}
protected override bool OnTryWrite(byte[] buffer, int leasePeriodMilliseconds = 0)
{
Guard.ThrowIfNull(buffer);
var path = this.FullPath + ".tmp";
try
{
PersistentStorageHelper.WriteAllBytes(path, buffer);
if (leasePeriodMilliseconds > 0)
{
var timestamp = DateTime.UtcNow + TimeSpan.FromMilliseconds(leasePeriodMilliseconds);
this.FullPath += $"@{timestamp:yyyy-MM-ddTHHmmss.fffffffZ}.lock";
}
File.Move(path, this.FullPath);
}
catch (Exception ex)
{
PersistentStorageEventSource.Log.CouldNotWriteFileBlob(path, ex);
return false;
}
this.directorySizeTracker?.FileAdded(buffer.LongLength);
return true;
}
protected override bool OnTryLease(int leasePeriodMilliseconds)
{
var path = this.FullPath;
var leaseTimestamp = DateTime.UtcNow + TimeSpan.FromMilliseconds(leasePeriodMilliseconds);
if (path.EndsWith(".lock", StringComparison.OrdinalIgnoreCase))
{
path = path.Substring(0, path.LastIndexOf('@'));
}
path += $"@{leaseTimestamp:yyyy-MM-ddTHHmmss.fffffffZ}.lock";
try
{
File.Move(this.FullPath, path);
}
catch (Exception ex)
{
PersistentStorageEventSource.Log.CouldNotLeaseFileBlob(this.FullPath, ex);
return false;
}
this.FullPath = path;
return true;
}
protected override bool OnTryDelete()
{
try
{
PersistentStorageHelper.RemoveFile(this.FullPath, out var fileSize);
this.directorySizeTracker?.FileRemoved(fileSize);
}
catch (Exception ex)
{
PersistentStorageEventSource.Log.CouldNotDeleteFileBlob(this.FullPath, ex);
return false;
}
return true;
}
}
| FileBlob |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/RazorWebSite/Controllers/ViewEngineController.cs | {
"start": 208,
"end": 1913
} | public class ____ : Controller
{
public IActionResult ViewWithoutLayout()
{
return View();
}
public IActionResult ViewWithFullPath()
{
return View("/Views/ViewEngine/ViewWithFullPath.cshtml");
}
public IActionResult ViewWithRelativePath()
{
return View("Views/ViewEngine/ViewWithRelativePath.cshtml");
}
public IActionResult ViewWithLayout()
{
return View();
}
public IActionResult ViewWithNestedLayout()
{
return View();
}
public IActionResult ViewWithPartial()
{
ViewData["TestKey"] = "test-value";
var model = new Person
{
Address = new Address { ZipCode = "98052" }
};
return View(model);
}
public IActionResult ViewWithPartialTakingModelFromIEnumerable()
{
var model = new List<Person>()
{
new Person() { Name = "Hello" },
new Person() { Name = "World" }
};
return View(model);
}
public IActionResult ViewPassesViewDataToLayout()
{
ViewData["Title"] = "Controller title";
return View("ViewWithTitle");
}
public IActionResult ViewWithDataFromController()
{
ViewData["data-from-controller"] = "hello from controller";
return View("ViewWithDataFromController");
}
public IActionResult ViewWithComponentThatHasLayout()
{
ViewData["Title"] = "View With Component With Layout";
return View();
}
public IActionResult ViewWithComponentThatHasViewStart()
{
return View();
}
public IActionResult SearchInPages() => View();
}
| ViewEngineController |
csharp | getsentry__sentry-dotnet | test/Sentry.DiagnosticSource.IntegrationTests/SqlListenerTests.verify.cs | {
"start": 53,
"end": 7703
} | public class ____ : IClassFixture<LocalDbFixture>
{
private readonly LocalDbFixture _fixture;
private readonly TestOutputDiagnosticLogger _logger;
public SqlListenerTests(LocalDbFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_logger = new TestOutputDiagnosticLogger(output);
}
#if !NETFRAMEWORK
[SkippableFact]
public async Task RecordsSqlAsync()
{
Skip.If(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var transport = new RecordingTransport();
var options = new SentryOptions
{
AttachStacktrace = false,
TracesSampleRate = 1,
Transport = transport,
Dsn = ValidDsn,
DiagnosticLogger = _logger,
Debug = true
};
#if NET6_0_OR_GREATER
await using var database = await _fixture.SqlInstance.Build();
#else
using var database = await _fixture.SqlInstance.Build();
#endif
using (var hub = new Hub(options))
{
var transaction = hub.StartTransaction("my transaction", "my operation");
hub.ConfigureScope(scope => scope.Transaction = transaction);
hub.CaptureException(new("my exception"));
await using (var connection = await database.OpenNewConnection())
{
await TestDbBuilder.AddDataAsync(connection);
await TestDbBuilder.GetDataAsync(connection);
}
transaction.Finish();
}
var result = await Verify(transport.Payloads)
.IgnoreMember<IEventLike>(_ => _.Environment)
.ScrubLinesWithReplace(line => line.Replace(LocalDbFixture.InstanceName, "SqlListenerTests"))
.IgnoreStandardSentryMembers();
Assert.DoesNotContain("SHOULD NOT APPEAR IN PAYLOAD", result.Text);
}
#endif
#if NET6_0_OR_GREATER
[SkippableFact]
public async Task LoggingAsync()
{
Skip.If(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var transport = new RecordingTransport();
void ApplyOptions(SentryLoggingOptions sentryOptions)
{
sentryOptions.AttachStacktrace = false;
sentryOptions.TracesSampleRate = 1;
sentryOptions.Transport = transport;
sentryOptions.Dsn = ValidDsn;
sentryOptions.DiagnosticLogger = _logger;
sentryOptions.Debug = true;
}
var options = new SentryLoggingOptions();
ApplyOptions(options);
await using var database = await _fixture.SqlInstance.Build();
await using (var dbContext = TestDbBuilder.GetDbContext(database.Connection))
{
dbContext.Add(new TestEntity
{
Property = "Value"
});
await dbContext.SaveChangesAsync();
}
var loggerFactory = LoggerFactory.Create(_ => _.AddSentry(ApplyOptions));
using (var hub = new Hub(options))
{
var transaction = hub.StartTransaction("my transaction", "my operation");
hub.ConfigureScope(scope => scope.Transaction = transaction);
await using (var connection = await database.OpenNewConnection())
await using (var dbContext = TestDbBuilder.GetDbContext(connection, loggerFactory))
{
dbContext.Add(new TestEntity
{
Property = "Value"
});
try
{
await dbContext.SaveChangesAsync();
}
catch
{
// Suppress the exception so we can test that we received the error through logging.
// Note, this uses the Sentry.Extensions.Logging integration.
}
}
transaction.Finish();
}
var result = await Verify(transport.Payloads)
.ScrubInlineGuids()
.IgnoreMember<IEventLike>(_ => _.Environment)
.ScrubLinesWithReplace(line => line.Replace(LocalDbFixture.InstanceName, "SqlListenerTests"))
// Really not sure why, but bytes received for this test varies randomly when run in CI
// TODO: remove this and investigate
.IgnoreMember("bytes_received")
.ScrubLinesWithReplace(line =>
{
if (line.StartsWith("Executed DbCommand ("))
{
return "Executed DbCommand";
}
if (line.StartsWith("Failed executing DbCommand ("))
{
return "Failed executing DbCommand";
}
var efVersion = typeof(DbContext).Assembly.GetName().Version!.ToString(3);
return line.Replace(efVersion, "");
})
.IgnoreStandardSentryMembers()
.UniqueForRuntimeAndVersion();
Assert.DoesNotContain("An error occurred while saving the entity changes", result.Text);
}
#endif
[Fact]
public void ShouldIgnoreAllErrorAndExceptionIds()
{
var eventIds = typeof(CoreEventId).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(x => x.FieldType == typeof(EventId))
.ToList();
Assert.NotEmpty(eventIds);
foreach (var field in eventIds)
{
var eventId = (EventId)field.GetValue(null)!;
var isEfExceptionMessage = SentryLogger.IsEfExceptionMessage(eventId);
var name = field.Name;
if (name.EndsWith("Exception") ||
name.EndsWith("Error") ||
name.EndsWith("Failed"))
{
Assert.True(isEfExceptionMessage, eventId.Name);
}
else
{
Assert.False(isEfExceptionMessage, eventId.Name);
}
}
}
[SkippableFact]
public async Task RecordsEfAsync()
{
Skip.If(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var transport = new RecordingTransport();
var options = new SentryOptions
{
AttachStacktrace = false,
TracesSampleRate = 1,
Transport = transport,
Dsn = ValidDsn,
DiagnosticLogger = _logger,
Debug = true
};
#if NETFRAMEWORK
options.AddDiagnosticSourceIntegration();
#endif
#if NET6_0_OR_GREATER
await using var database = await _fixture.SqlInstance.Build();
#else
using var database = await _fixture.SqlInstance.Build();
#endif
using (var hub = new Hub(options))
{
var transaction = hub.StartTransaction("my transaction", "my operation");
hub.ConfigureScope(scope => scope.Transaction = transaction);
hub.CaptureException(new("my exception"));
#if NETCOREAPP
await using (var connection = await database.OpenNewConnection())
#else
using (var connection = await database.OpenNewConnection())
#endif
{
await TestDbBuilder.AddEfDataAsync(connection);
await TestDbBuilder.GetEfDataAsync(connection);
}
transaction.Finish();
}
var result = await Verify(transport.Payloads)
.IgnoreMember<IEventLike>(_ => _.Environment)
.ScrubLinesWithReplace(line => line.Replace(LocalDbFixture.InstanceName, "SqlListenerTests"))
.IgnoreStandardSentryMembers()
.UniqueForRuntimeAndVersion();
Assert.DoesNotContain("SHOULD NOT APPEAR IN PAYLOAD", result.Text);
}
}
| SqlListenerTests |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Users/Services/MembershipService.cs | {
"start": 139,
"end": 1182
} | public class ____ : IMembershipService
{
private readonly UserManager<IUser> _userManager;
private readonly IUserClaimsPrincipalFactory<IUser> _claimsPrincipalFactory;
public MembershipService(
IUserClaimsPrincipalFactory<IUser> claimsPrincipalFactory,
UserManager<IUser> userManager)
{
_claimsPrincipalFactory = claimsPrincipalFactory;
_userManager = userManager;
}
public async Task<bool> CheckPasswordAsync(string userName, string password)
{
var user = await _userManager.FindByNameAsync(userName);
if (user == null)
{
return false;
}
return await _userManager.CheckPasswordAsync(user, password);
}
public async Task<IUser> GetUserAsync(string userName)
{
var user = await _userManager.FindByNameAsync(userName);
return user;
}
public Task<ClaimsPrincipal> CreateClaimsPrincipal(IUser user)
{
return _claimsPrincipalFactory.CreateAsync(user as User);
}
}
| MembershipService |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/AttributeTests.cs | {
"start": 9563,
"end": 9731
} | public class ____ { }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
| DefaultWithMultipleRouteAttributes |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Shipping.UPS/API/Track/TrackClient.cs | {
"start": 17446,
"end": 18289
} | public partial class ____
{
[Newtonsoft.Json.JsonProperty("pickupByDate", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string PickupByDate { get; set; }
private System.Collections.Generic.IDictionary<string, object> _additionalProperties;
[Newtonsoft.Json.JsonExtensionData]
public System.Collections.Generic.IDictionary<string, object> AdditionalProperties
{
get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary<string, object>()); }
set { _additionalProperties = value; }
}
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.0.0))")]
| AccessPointInformation |
csharp | cake-build__cake | src/Cake.DotNetTool.Module/DotNetToolPackage.cs | {
"start": 322,
"end": 947
} | public sealed class ____
{
/// <summary>
/// Gets or sets the tool package ID.
/// </summary>
/// <value>The tool package ID.</value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the tool package version.
/// </summary>
/// <value>The tool package version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the tool package short code.
/// </summary>
/// <value>The tool package short code.</value>
public string ShortCode { get; set; }
}
} | DotNetToolPackage |
csharp | dotnet__orleans | test/Grains/TestFSharpGrainInterfaces/IFSharpParametersGrain.cs | {
"start": 186,
"end": 287
} | public interface ____<T,U> : IGrainWithGuidKey, IFSharpParameters<T>
{
}
}
| IFSharpParametersGrain |
csharp | nunit__nunit | src/NUnitFramework/nunit.framework.legacy.tests/FileAssertTests.cs | {
"start": 316,
"end": 2073
} | public class ____
{
private static readonly string BadFile = Path.Combine(Path.GetTempPath(), "garbage.txt");
#region AreEqual
#region Success Tests
[Test]
public void AreEqualPassesWhenBothAreNull()
{
FileStream? expected = null;
FileStream? actual = null;
FileAssert.AreEqual(expected, actual);
}
[Test]
public void AreEqualPassesWithSameStream()
{
Stream exampleStream = new MemoryStream(new byte[] { 1, 2, 3 });
#pragma warning disable NUnit2009 // The same value has been provided as both the actual and the expected argument
Assert.That(exampleStream, Is.EqualTo(exampleStream));
#pragma warning restore NUnit2009 // The same value has been provided as both the actual and the expected argument
}
[Test]
public void AreEqualPassesWithEqualStreams()
{
using var tf1 = new TestFile("TestImage1.jpg");
using var tf2 = new TestFile("TestImage1.jpg");
using FileStream expected = tf1.File.OpenRead();
using FileStream actual = tf2.File.OpenRead();
FileAssert.AreEqual(expected, actual);
}
[Test]
public void NonReadableStreamGivesException()
{
using var tf1 = new TestFile("TestImage1.jpg");
using var tf2 = new TestFile("TestImage1.jpg");
using FileStream expected = tf1.File.OpenRead();
using FileStream actual = tf2.File.OpenWrite();
var ex = Assert.Throws<ArgumentException>(() => FileAssert.AreEqual(expected, actual));
Assert.That(ex?.Message, Does.Contain("not readable"));
}
| FileAssertTests |
csharp | dotnet__efcore | src/EFCore.Relational/Migrations/Operations/CreateTableOperation.cs | {
"start": 494,
"end": 1665
} | public class ____ : TableOperation
{
/// <summary>
/// The <see cref="AddPrimaryKeyOperation" /> representing the creation of the primary key for the table.
/// </summary>
public virtual AddPrimaryKeyOperation? PrimaryKey { get; set; }
/// <summary>
/// An ordered list of <see cref="AddColumnOperation" /> for adding columns to the table.
/// </summary>
public virtual List<AddColumnOperation> Columns { get; } = [];
/// <summary>
/// A list of <see cref="AddForeignKeyOperation" /> for creating foreign key constraints in the table.
/// </summary>
public virtual List<AddForeignKeyOperation> ForeignKeys { get; } = [];
/// <summary>
/// A list of <see cref="AddUniqueConstraintOperation" /> for creating unique constraints in the table.
/// </summary>
public virtual List<AddUniqueConstraintOperation> UniqueConstraints { get; } = [];
/// <summary>
/// A list of <see cref="AddCheckConstraintOperation" /> for creating check constraints in the table.
/// </summary>
public virtual List<AddCheckConstraintOperation> CheckConstraints { get; } = [];
}
| CreateTableOperation |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Interfaces/IOneWayClient.cs | {
"start": 78,
"end": 278
} | public interface ____
{
void SendOneWay(object requestDto);
void SendOneWay(string relativeOrAbsoluteUri, object requestDto);
void SendAllOneWay(IEnumerable<object> requests);
} | IOneWayClient |
csharp | fals__cqrs-clean-eventual-consistency | src/Ametista.Core/Shared/IBuilder.cs | {
"start": 38,
"end": 99
} | public interface ____<T>
{
T Build();
}
} | IBuilder |
csharp | unoplatform__uno | src/SourceGenerators/System.Xaml.Tests/Test/System.Xaml.Schema/XamlTypeInvokerTest.cs | {
"start": 4163,
"end": 4598
} | public class ____
{
// delegate type mismatch
void HandleTypeConverter ()
{
}
}
[Test]
public void SetHandleTypeConverterInvalid2 ()
{
Assert.Throws(typeof(ArgumentException), () =>
{
var i = new XamlTypeInvoker(new XamlType(typeof(TestClassTypeConverter2), sctx));
Assert.IsNull(i.SetTypeConverterHandler, "#1");
});
}
[XamlSetTypeConverter ("HandleTypeConverter")]
| TestClassTypeConverter2 |
csharp | scriban__scriban | src/Scriban/Parsing/Parser.Statements.Scriban.cs | {
"start": 477,
"end": 18776
} |
partial class ____
{
private void ParseScribanStatement(string identifier, ScriptNode parent, bool parseEndOfStatementAfterEnd, ref ScriptStatement statement, ref bool hasEnd, ref bool nextStatement)
{
var startToken = Current;
switch (identifier)
{
case "end":
hasEnd = true;
statement = ParseEndStatement(parseEndOfStatementAfterEnd);
break;
case "wrap":
CheckNotInCase(parent, startToken);
statement = ParseWrapStatement();
break;
case "if":
CheckNotInCase(parent, startToken);
statement = ParseIfStatement(false, null);
break;
case "case":
CheckNotInCase(parent, startToken);
statement = ParseCaseStatement();
break;
case "when":
var whenStatement = ParseWhenStatement();
var whenParent = parent as ScriptConditionStatement;
if (parent is ScriptWhenStatement)
{
((ScriptWhenStatement)whenParent).Next = whenStatement;
}
else if (parent is ScriptCaseStatement)
{
statement = whenStatement;
}
else
{
nextStatement = false;
// unit test: TODO
LogError(startToken, "A `when` condition must be preceded by another `when`/`else`/`case` condition");
}
hasEnd = true;
break;
case "else":
var nextCondition = ParseElseStatement(false);
var parentCondition = parent as ScriptConditionStatement;
if (parent is ScriptIfStatement || parent is ScriptWhenStatement)
{
if (parent is ScriptIfStatement)
{
((ScriptIfStatement)parentCondition).Else = nextCondition;
}
else
{
((ScriptWhenStatement)parentCondition).Next = nextCondition;
}
}
else if (parent is ScriptForStatement forStatement)
{
if (nextCondition is ScriptElseStatement nextElse)
{
forStatement.Else = nextElse;
}
else
{
LogError(nextCondition.Span, "Invalid if/else combination within a for statement.");
}
}
else
{
nextStatement = false;
// unit test: 201-if-else-error3.txt
LogError(startToken, "A else condition must be preceded by another if/else/when condition or a for loop.");
}
hasEnd = true;
break;
case "for":
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseForStatement<ScriptForStatement>();
}
break;
case "tablerow":
if (_isScientific) goto default;
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseForStatement<ScriptTableRowStatement>();
}
break;
case "with":
CheckNotInCase(parent, startToken);
statement = ParseWithStatement();
break;
case "import":
CheckNotInCase(parent, startToken);
statement = ParseImportStatement();
break;
case "readonly":
CheckNotInCase(parent, startToken);
statement = ParseReadOnlyStatement();
break;
case "while":
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseWhileStatement();
}
break;
case "break":
CheckNotInCase(parent, startToken);
var breakStatement = Open<ScriptBreakStatement>();
statement = breakStatement;
ExpectAndParseKeywordTo(breakStatement.BreakKeyword); // Parse break
ExpectEndOfStatement();
Close(statement);
// This has to be done at execution time, because of the wrap statement
//if (!IsInLoop())
//{
// LogError(statement, "Unexpected statement outside of a loop");
//}
break;
case "continue":
CheckNotInCase(parent, startToken);
var continueStatement = Open<ScriptContinueStatement>();
statement = continueStatement;
ExpectAndParseKeywordTo(continueStatement.ContinueKeyword); // Parse continue keyword
ExpectEndOfStatement();
Close(statement);
// This has to be done at execution time, because of the wrap statement
//if (!IsInLoop())
//{
// LogError(statement, "Unexpected statement outside of a loop");
//}
break;
case "func":
CheckNotInCase(parent, startToken);
statement = ParseFunctionStatement(false);
break;
case "ret":
CheckNotInCase(parent, startToken);
statement = ParseReturnStatement();
break;
case "capture":
CheckNotInCase(parent, startToken);
statement = ParseCaptureStatement();
break;
default:
CheckNotInCase(parent, startToken);
// Otherwise it is an expression statement
statement = ParseExpressionStatement();
break;
}
}
private ScriptEndStatement ParseEndStatement(bool parseEndOfStatementAfterEnd)
{
var endStatement = Open<ScriptEndStatement>();
ExpectAndParseKeywordTo(endStatement.EndKeyword);
if (parseEndOfStatementAfterEnd)
{
ExpectEndOfStatement();
}
return Close(endStatement);
}
private ScriptFunction ParseFunctionStatement(bool isAnonymous)
{
var scriptFunction = Open<ScriptFunction>();
var previousExpressionLevel = _expressionLevel;
try
{
// Reset expression level when parsing
_expressionLevel = 0;
if (isAnonymous)
{
scriptFunction.NameOrDoToken = ExpectAndParseKeywordTo(ScriptKeyword.Do());
}
else
{
scriptFunction.FuncToken = ExpectAndParseKeywordTo(ScriptKeyword.Func());
scriptFunction.NameOrDoToken = ExpectAndParseVariable(scriptFunction);
}
// If we have parenthesis, this is a function with explicit parameters
if (Current.Type == TokenType.OpenParen)
{
scriptFunction.OpenParen = ParseToken(TokenType.OpenParen);
var parameters = new ScriptList<ScriptParameter>();
bool hasTripleDot = false;
bool hasOptionals = false;
bool isFirst = true;
while (true)
{
// Parse any required comma (before each new non-first argument)
// Or closing parent (and we exit the loop)
if (Current.Type == TokenType.CloseParen)
{
scriptFunction.CloseParen = ParseToken(TokenType.CloseParen);
scriptFunction.Span.End = scriptFunction.CloseParen.Span.End;
break;
}
if (!isFirst)
{
if (Current.Type == TokenType.Comma)
{
PushTokenToTrivia();
NextToken();
FlushTriviasToLastTerminal();
}
else
{
LogError(Current, "Expecting a comma to separate arguments in a function call.");
}
}
isFirst = false;
// Else we expect an expression
if (IsStartOfExpression())
{
var parameter = Open<ScriptParameter>();
var arg = ExpectAndParseVariable(scriptFunction);
if (!(arg is ScriptVariableGlobal))
{
if (arg == null)
break;
LogError(arg.Span, "Expecting only a simple name parameter for a function");
}
parameter.Name = arg;
if (Current.Type == TokenType.Equal)
{
if (hasTripleDot)
{
LogError(arg.Span, "Cannot declare an optional parameter after a variable parameter (`...`).");
}
hasOptionals = true;
parameter.EqualOrTripleDotToken = ScriptToken.Equal();
ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.Equal);
parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End;
var defaultValue = ExpectAndParseExpression(parameter);
if (defaultValue is ScriptLiteral literal)
{
parameter.DefaultValue = literal;
parameter.Span.End = literal.Span.End;
}
else
{
LogError(arg.Span, "Expecting only a literal for an optional parameter value.");
}
}
else if (Current.Type == TokenType.TripleDot)
{
if (hasTripleDot)
{
LogError(arg.Span, "Cannot declare multiple variable parameters.");
}
hasTripleDot = true;
hasOptionals = true;
parameter.EqualOrTripleDotToken = ScriptToken.TripleDot();
ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.TripleDot);
parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End;
}
else if (hasOptionals)
{
LogError(arg.Span, "Cannot declare a normal parameter after an optional parameter.");
}
parameters.Add(parameter);
scriptFunction.Span.End = parameter.Span.End;
}
else
{
LogError(Current, "Expecting an expression for argument function calls instead of this token.");
break;
}
}
if (scriptFunction.CloseParen == null)
{
LogError(Current, "Expecting a closing parenthesis for a function call.");
}
// Setup parameters once they have been all parsed
scriptFunction.Parameters = parameters;
}
ExpectEndOfStatement();
// If the function is anonymous we don't expect an EOS after the `end`
scriptFunction.Body = ParseBlockStatement(scriptFunction, !isAnonymous);
}
finally
{
_expressionLevel = previousExpressionLevel;
}
return Close(scriptFunction);
}
private ScriptImportStatement ParseImportStatement()
{
var importStatement = Open<ScriptImportStatement>();
ExpectAndParseKeywordTo(importStatement.ImportKeyword); // Parse import keyword
importStatement.Expression = ExpectAndParseExpression(importStatement);
ExpectEndOfStatement();
return Close(importStatement);
}
private ScriptReadOnlyStatement ParseReadOnlyStatement()
{
var readOnlyStatement = Open<ScriptReadOnlyStatement>();
ExpectAndParseKeywordTo(readOnlyStatement.ReadOnlyKeyword); // Parse readonly keyword
readOnlyStatement.Variable = ExpectAndParseVariable(readOnlyStatement);
ExpectEndOfStatement();
return Close(readOnlyStatement);
}
private ScriptReturnStatement ParseReturnStatement()
{
var ret = Open<ScriptReturnStatement>();
ExpectAndParseKeywordTo(ret.RetKeyword); // Parse ret keyword
if (IsStartOfExpression())
{
ret.Expression = ParseExpression(ret);
}
ExpectEndOfStatement();
return Close(ret);
}
private ScriptWhileStatement ParseWhileStatement()
{
var whileStatement = Open<ScriptWhileStatement>();
ExpectAndParseKeywordTo(whileStatement.WhileKeyword); // Parse while keyword
// Parse the condition
// unit test: 220-while-error1.txt
whileStatement.Condition = ExpectAndParseExpression(whileStatement, allowAssignment: false);
if (ExpectEndOfStatement())
{
whileStatement.Body = ParseBlockStatement(whileStatement);
}
return Close(whileStatement);
}
private ScriptWithStatement ParseWithStatement()
{
var withStatement = Open<ScriptWithStatement>();
ExpectAndParseKeywordTo(withStatement.WithKeyword); // // Parse with keyword
withStatement.Name = ExpectAndParseExpression(withStatement);
if (ExpectEndOfStatement())
{
withStatement.Body = ParseBlockStatement(withStatement);
}
return Close(withStatement);
}
private ScriptWrapStatement ParseWrapStatement()
{
var wrapStatement = Open<ScriptWrapStatement>();
ExpectAndParseKeywordTo(wrapStatement.WrapKeyword); // Parse wrap keyword
wrapStatement.Target = ExpectAndParseExpression(wrapStatement);
if (ExpectEndOfStatement())
{
wrapStatement.Body = ParseBlockStatement(wrapStatement);
}
return Close(wrapStatement);
}
private void FixRawStatementAfterFrontMatter(ScriptPage page)
{
// In case of parsing a front matter, we don't want to include any \r\n after the end of the front-matter
// So we manipulate back the syntax tree for the expected raw statement (if any), otherwise we can early
// exit.
var rawStatement = page.Body.Statements.FirstOrDefault() as ScriptRawStatement;
if (rawStatement == null)
{
return;
}
rawStatement.Text = rawStatement.Text.TrimStart();
}
private static bool IsScribanKeyword(string text)
{
switch (text)
{
case "if":
case "else":
case "end":
case "for":
case "case":
case "when":
case "while":
case "break":
case "continue":
case "func":
case "import":
case "readonly":
case "with":
case "capture":
case "ret":
case "wrap":
case "do":
return true;
}
return false;
}
}
} | Parser |
csharp | AutoMapper__AutoMapper | src/UnitTests/NullBehavior.cs | {
"start": 28377,
"end": 29910
} | public class ____
{
public IEnumerable<int> Values1 { get; set; }
public List<int> Values2 { get; set; }
public Dictionary<string, int> Values3 { get; set; }
public int[] Values4 { get; set; }
public ReadOnlyCollection<int> Values5 { get; set; }
public Collection<int> Values6 { get; set; }
public int[,] Values7 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateProfile("MyProfile", p =>
{
p.CreateMap<Source, Dest>();
p.AllowNullCollections = true;
});
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Dest>(new Source());
}
[Fact]
public void Should_allow_null_ienumerables()
{
_dest.Values1.ShouldBeNull();
}
[Fact]
public void Should_allow_null_lists()
{
_dest.Values2.ShouldBeNull();
}
[Fact]
public void Should_allow_null_dictionaries()
{
_dest.Values3.ShouldBeNull();
}
[Fact]
public void Should_allow_null_arrays()
{
_dest.Values4.ShouldBeNull();
}
[Fact]
public void Should_allow_null_read_only_collections()
{
_dest.Values5.ShouldBeNull();
}
[Fact]
public void Should_allow_null_collections()
{
_dest.Values6.ShouldBeNull();
}
[Fact]
public void Should_allow_null_multidimensional_arrays()
{
_dest.Values7.ShouldBeNull();
}
}
| Dest |
csharp | dotnet__orleans | src/Orleans.Serialization.TestKit/BufferTestHelper.cs | {
"start": 3012,
"end": 3451
} | public class ____
{
public int MaxAllocationSize { get; set; }
}
protected override TestMultiSegmentBufferWriter CreateBufferWriter() => new(_options.MaxAllocationSize);
public override string ToString() => $"{nameof(TestMultiSegmentBufferWriter)} {nameof(_options.MaxAllocationSize)}: {_options.MaxAllocationSize}";
}
[ExcludeFromCodeCoverage]
| Options |
csharp | CommunityToolkit__Maui | src/CommunityToolkit.Maui.SourceGenerators.Benchmarks/BindablePropertyAttributeSourceGeneratorBenchmarks.cs | {
"start": 227,
"end": 1745
} | public class ____
{
static readonly CommonUsageTests commonUsageTests = new();
static readonly EdgeCaseTests edgeCaseTests = new();
static readonly IntegrationTests integrationTests = new();
[Benchmark]
public Task GenerateBindableProperty_SimpleExample_GeneratesCorrectCode()
=> commonUsageTests.GenerateBindableProperty_SimpleExample_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_MultipleProperties_GeneratesCorrectCode()
=> commonUsageTests.GenerateBindableProperty_MultipleProperties_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_WithAllParameters_GeneratesCorrectCode()
=> commonUsageTests.GenerateBindableProperty_WithAllParameters_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_InternalClass_GeneratesCorrectCode()
=> commonUsageTests.GenerateBindableProperty_InternalClass_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_ComplexInheritanceScenario_GeneratesCorrectCode()
=> integrationTests.GenerateBindableProperty_ComplexInheritanceScenario_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_NestedClass_GeneratesCorrectCode()
=> integrationTests.GenerateBindableProperty_NestedClass_GeneratesCorrectCode();
[Benchmark]
public Task GenerateBindableProperty_WithComplexDefaultValues_GeneratesCorrectCode()
=> edgeCaseTests.GenerateBindableProperty_WithComplexDefaultValues_GeneratesCorrectCode();
} | BindablePropertyAttributeSourceGeneratorBenchmarks |
csharp | bitwarden__server | util/PostgresMigrations/Migrations/20221209020447_EventsDomainName.cs | {
"start": 115,
"end": 585
} | public partial class ____ : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DomainName",
table: "Event",
type: "text",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DomainName",
table: "Event");
}
}
| EventsDomainName |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.