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
AutoMapper__AutoMapper
src/UnitTests/MappingInheritance/PropertyOnMappingShouldResolveMostSpecificType.cs
{ "start": 1068, "end": 8063 }
public class ____ { public ContainerDto() { Items = new List<ItemDto>(); } public List<ItemDto> Items { get; private set; } } [Fact] public void container_class_is_caching_too_specific_mapper_for_collection() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<ItemBase, ItemDto>() .ForMember(d => d.Description, m => m.MapFrom(s => s)) .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)) .Include<SpecificItem, SpecificItemDto>(); cfg.CreateMap<SpecificItem, SpecificItemDto>() .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)); cfg.CreateMap<ItemBase, DescriptionBaseDto>() .Include<GenericItem, GenericDescriptionDto>() .Include<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<GenericItem, GenericDescriptionDto>() .Include<DifferentItem, DifferentDescriptionDto>() .Include<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<DifferentItem, DifferentDescriptionDto>(); cfg.CreateMap<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<Container, ContainerDto>(); }); var dto = config.CreateMapper().Map<Container, ContainerDto>(new Container { Items = { new DifferentItem(), new SpecificItem() } }); dto.Items[0].Description.ShouldBeOfType<DifferentDescriptionDto>(); dto.Items[1].ShouldBeOfType<SpecificItemDto>(); dto.Items[1].Description.ShouldBeOfType<SpecificDescriptionDto>(); } [Fact] public void container_class_is_caching_too_specific_mapper_for_collection_with_one_parameter() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<ItemBase, ItemDto>() .ForMember(d => d.Description, m => m.MapFrom(s => s)) .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)) .Include<SpecificItem, SpecificItemDto>(); cfg.CreateMap<SpecificItem, SpecificItemDto>() .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)); cfg.CreateMap<ItemBase, DescriptionBaseDto>() .Include<GenericItem, GenericDescriptionDto>() .Include<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<GenericItem, GenericDescriptionDto>() .Include<DifferentItem, DifferentDescriptionDto>() .Include<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<DifferentItem, DifferentDescriptionDto>(); cfg.CreateMap<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<Container, ContainerDto>(); }); var dto = config.CreateMapper().Map<ContainerDto>(new Container { Items = { new DifferentItem(), new SpecificItem() } }); dto.Items[0].Description.ShouldBeOfType<DifferentDescriptionDto>(); dto.Items[1].ShouldBeOfType<SpecificItemDto>(); dto.Items[1].Description.ShouldBeOfType<SpecificDescriptionDto>(); } [Fact] public void property_on_dto_mapped_from_self_should_be_specific_match() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<ItemBase, ItemDto>() .ForMember(d => d.Description, m => m.MapFrom(s => s)) .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)) .Include<SpecificItem, SpecificItemDto>(); cfg.CreateMap<SpecificItem, SpecificItemDto>() .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)); cfg.CreateMap<ItemBase, DescriptionBaseDto>() .Include<GenericItem, GenericDescriptionDto>() .Include<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<GenericItem, GenericDescriptionDto>() .Include<DifferentItem, DifferentDescriptionDto>() .Include<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<DifferentItem, DifferentDescriptionDto>(); cfg.CreateMap<DifferentItem2, DifferentDescriptionDto2>(); }); config.AssertConfigurationIsValid(); var dto = config.CreateMapper().Map<ItemBase, ItemDto>(new DifferentItem()); dto.ShouldBeOfType<ItemDto>(); dto.Description.ShouldBeOfType<DifferentDescriptionDto>(); } [Fact] public void property_on_dto_mapped_from_self_should_be_specific_match_with_one_parameter() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<ItemBase, ItemDto>() .ForMember(d => d.Description, m => m.MapFrom(s => s)) .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)) .Include<SpecificItem, SpecificItemDto>(); cfg.CreateMap<SpecificItem, SpecificItemDto>() .ForMember(d => d.SomeProperty, m => m.MapFrom(s => s.SomeBaseProperty)); cfg.CreateMap<ItemBase, DescriptionBaseDto>() .Include<GenericItem, GenericDescriptionDto>() .Include<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<SpecificItem, SpecificDescriptionDto>(); cfg.CreateMap<GenericItem, GenericDescriptionDto>() .Include<DifferentItem, DifferentDescriptionDto>() .Include<DifferentItem2, DifferentDescriptionDto2>(); cfg.CreateMap<DifferentItem, DifferentDescriptionDto>(); cfg.CreateMap<DifferentItem2, DifferentDescriptionDto2>(); }); config.AssertConfigurationIsValid(); var dto = config.CreateMapper().Map<ItemDto>(new DifferentItem()); dto.ShouldBeOfType<ItemDto>(); dto.Description.ShouldBeOfType<DifferentDescriptionDto>(); } }
ContainerDto
csharp
dotnet__machinelearning
src/Microsoft.ML.Transforms/Dracula/CountTargetEncodingTransformer.cs
{ "start": 29452, "end": 30608 }
class ____ the back-off indicator. /// </summary> /// <param name="catalog">The transforms catalog.</param> /// <param name="outputColumnName">Name of the column resulting from the transformation of <paramref name="inputColumnName"/>.</param> /// <param name="initialCounts">A previously trained count table containing initial counts.</param> /// <param name="inputColumnName">Name of the column to transform. If set to <see langword="null"/>, the value of the <paramref name="outputColumnName"/> will be used as source.</param> /// <param name="labelColumn">The name of the label column.</param> /// <returns></returns> public static CountTargetEncodingEstimator CountTargetEncode(this TransformsCatalog catalog, string outputColumnName, CountTargetEncodingTransformer initialCounts, string inputColumnName = null, string labelColumn = "Label") { return new CountTargetEncodingEstimator(CatalogUtils.GetEnvironment(catalog), labelColumn, initialCounts, new[] { new InputOutputColumnPair(outputColumnName, inputColumnName) }); } }
and
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Sms.Abstractions/SmsMessage.cs
{ "start": 28, "end": 499 }
public class ____ { /// <summary> /// The phone number to send the message from. /// If not specified, the provider's default phone number will be used. /// </summary> public string From { get; set; } /// <summary> /// The phone number to send the message to. /// </summary> public string To { get; set; } /// <summary> /// The body of the message to send. /// </summary> public string Body { get; set; } }
SmsMessage
csharp
EventStore__EventStore
src/KurrentDB.Plugins.Tests/PluginBaseTests.cs
{ "start": 8322, "end": 8725 }
class ____ : NightCityPlugin { private readonly Action<Exception> _onLicenseException; public CustomCityPlugin(Action<Exception> onLicenseException) : base(new() { RequiredEntitlements = ["starlight"] }) { _onLicenseException = onLicenseException; } protected override void OnLicenseException(Exception ex, Action<Exception> shutdown) { _onLicenseException(ex); } }
CustomCityPlugin
csharp
dotnet__machinelearning
src/Microsoft.ML.FastTree/FastTreeArguments.cs
{ "start": 2135, "end": 4172 }
public sealed class ____ : BoostedTreeOptions, IFastTreeTrainerFactory { /// <summary> /// Whether to use derivatives optimized for unbalanced training data. /// </summary> [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Option for using derivatives optimized for unbalanced sets", ShortName = "us")] [TGUI(Label = "Optimize for unbalanced")] public bool UnbalancedSets = false; /// <summary> /// internal state of <see cref="EarlyStoppingMetric"/>. It should be always synced with /// <see cref="BoostedTreeOptions.EarlyStoppingMetrics"/>. /// </summary> // Disable 649 because Visual Studio can't detect its assignment via property. #pragma warning disable 649 private EarlyStoppingMetric _earlyStoppingMetric; #pragma warning restore 649 /// <summary> /// Early stopping metrics. /// </summary> public EarlyStoppingMetric EarlyStoppingMetric { get { return _earlyStoppingMetric; } set { // Update the state of the user-facing stopping metric. _earlyStoppingMetric = value; // Set up internal property according to its public value. EarlyStoppingMetrics = (int)_earlyStoppingMetric; } } /// <summary> /// Create a new <see cref="Options"/> object with default values. /// </summary> public Options() { // Use L1 by default. EarlyStoppingMetric = EarlyStoppingMetric.L1Norm; } ITrainer IComponentFactory<ITrainer>.CreateComponent(IHostEnvironment env) => new FastTreeBinaryTrainer(env, this); } } // XML docs are provided in the other part of this partial class. No need to duplicate the content here. public sealed
Options
csharp
dotnet__aspire
src/Aspire.Hosting.Python/PythonAppResourceBuilderExtensions.cs
{ "start": 1290, "end": 73768 }
public static class ____ { private const string DefaultVirtualEnvFolder = ".venv"; private const string DefaultPythonVersion = "3.13"; /// <summary> /// Adds a Python application to the application model. /// </summary> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param> /// <param name="name">The name of the resource.</param> /// <param name="appDirectory">The path to the directory containing the python application.</param> /// <param name="scriptPath">The path to the script relative to the app directory to run.</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> /// <remarks> /// <para> /// This method executes a Python script directly using <c>python script.py</c>. /// By default, the virtual environment is resolved using the following priority: /// <list type="number"> /// <item>If <c>.venv</c> exists in the app directory, use it.</item> /// <item>If <c>.venv</c> exists in the AppHost directory, use it.</item> /// <item>Otherwise, default to <c>.venv</c> in the app directory.</item> /// </list> /// Use <see cref="WithVirtualEnvironment{T}(IResourceBuilder{T}, string, bool)"/> to specify a different virtual environment path. /// Use <c>WithArgs</c> to pass arguments to the script. /// </para> /// <para> /// Python applications automatically have debugging support enabled. /// </para> /// </remarks> /// <example> /// Add a FastAPI Python application to the application model: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// builder.AddPythonApp("fastapi-app", "../api", "main.py") /// .WithArgs("arg1", "arg2"); /// /// builder.Build().Run(); /// </code> /// </example> [OverloadResolutionPriority(1)] public static IResourceBuilder<PythonAppResource> AddPythonApp( this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string scriptPath) => AddPythonAppCore(builder, name, appDirectory, EntrypointType.Script, scriptPath, DefaultVirtualEnvFolder) .WithDebugging(); /// <summary> /// Adds a Python module to the application model. /// </summary> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param> /// <param name="name">The name of the resource.</param> /// <param name="appDirectory">The path to the directory containing the python application.</param> /// <param name="moduleName">The name of the Python module to run (e.g., "flask", "uvicorn").</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> /// <remarks> /// <para> /// This method runs a Python module using <c>python -m &lt;module&gt;</c>. /// By default, the virtual environment folder is expected to be named <c>.venv</c> and located in the app directory. /// Use <see cref="WithVirtualEnvironment{T}(IResourceBuilder{T}, string, bool)"/> to specify a different virtual environment path. /// Use <c>WithArgs</c> to pass arguments to the module. /// </para> /// <para> /// Python modules automatically have debugging support enabled. /// </para> /// </remarks> /// <example> /// Add a Flask module to the application model: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// builder.AddPythonModule("flask-dev", "../flaskapp", "flask") /// .WithArgs("run", "--debug", "--host=0.0.0.0"); /// /// builder.Build().Run(); /// </code> /// </example> public static IResourceBuilder<PythonAppResource> AddPythonModule( this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string moduleName) => AddPythonAppCore(builder, name, appDirectory, EntrypointType.Module, moduleName, DefaultVirtualEnvFolder) .WithDebugging(); /// <summary> /// Adds a Python executable to the application model. /// </summary> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param> /// <param name="name">The name of the resource.</param> /// <param name="appDirectory">The path to the directory containing the python application.</param> /// <param name="executableName">The name of the executable in the virtual environment (e.g., "pytest", "uvicorn", "flask").</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> /// <remarks> /// <para> /// This method runs an executable from the virtual environment's bin directory. /// By default, the virtual environment folder is expected to be named <c>.venv</c> and located in the app directory. /// Use <see cref="WithVirtualEnvironment{T}(IResourceBuilder{T}, string, bool)"/> to specify a different virtual environment path. /// Use <c>WithArgs</c> to pass arguments to the executable. /// </para> /// <para> /// Unlike scripts and modules, Python executables do not have debugging support enabled by default. /// Use <see cref="WithDebugging"/> to explicitly enable debugging support if the executable is a Python-based /// tool that can be debugged. /// </para> /// </remarks> /// <example> /// Add a pytest executable to the application model: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// builder.AddPythonExecutable("pytest", "../api", "pytest") /// .WithArgs("-q") /// .WithDebugging(); /// /// builder.Build().Run(); /// </code> /// </example> public static IResourceBuilder<PythonAppResource> AddPythonExecutable( this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string executableName) => AddPythonAppCore(builder, name, appDirectory, EntrypointType.Executable, executableName, DefaultVirtualEnvFolder); /// <summary> /// Adds a python application with a virtual environment to the application model. /// </summary> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param> /// <param name="name">The name of the resource.</param> /// <param name="appDirectory">The path to the directory containing the python app files.</param> /// <param name="scriptPath">The path to the script relative to the app directory to run.</param> /// <param name="scriptArgs">The arguments for the script.</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> /// <remarks> /// <para> /// This overload is obsolete. Use one of the more specific methods instead: /// </para> /// <list type="bullet"> /// <item><description><see cref="AddPythonApp(IDistributedApplicationBuilder, string, string, string)"/> - To run a Python script file</description></item> /// <item><description><see cref="AddPythonModule"/> - To run a Python module via <c>python -m</c></description></item> /// <item><description><see cref="AddPythonExecutable"/> - To run an executable from the virtual environment</description></item> /// </list> /// <para> /// Chain with <c>WithArgs</c> to pass arguments: /// </para> /// <example> /// <code lang="csharp"> /// builder.AddPythonScript("name", "dir", "script.py") /// .WithArgs("arg1", "arg2"); /// </code> /// </example> /// </remarks> [Obsolete("Use AddPythonScript, AddPythonModule, or AddPythonExecutable and chain with .WithArgs(...) instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static IResourceBuilder<PythonAppResource> AddPythonApp( this IDistributedApplicationBuilder builder, string name, string appDirectory, string scriptPath, params string[] scriptArgs) { ArgumentException.ThrowIfNullOrEmpty(scriptPath); ThrowIfNullOrContainsIsNullOrEmpty(scriptArgs); return AddPythonAppCore(builder, name, appDirectory, EntrypointType.Script, scriptPath, DefaultVirtualEnvFolder) .WithDebugging() .WithArgs(scriptArgs); } /// <summary> /// Adds a python application with a virtual environment to the application model. /// </summary> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param> /// <param name="name">The name of the resource.</param> /// <param name="appDirectory">The path to the directory containing the python app files.</param> /// <param name="scriptPath">The path to the script to run, relative to the app directory.</param> /// <param name="virtualEnvironmentPath">Path to the virtual environment.</param> /// <param name="scriptArgs">The arguments for the script.</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> /// <remarks> /// <para> /// This overload is obsolete. Use one of the more specific methods instead: /// </para> /// <list type="bullet"> /// <item><description><see cref="AddPythonApp(IDistributedApplicationBuilder, string, string, string)"/> - To run a Python script file</description></item> /// <item><description><see cref="AddPythonModule"/> - To run a Python module via <c>python -m</c></description></item> /// <item><description><see cref="AddPythonExecutable"/> - To run an executable from the virtual environment</description></item> /// </list> /// <para> /// Chain with <see cref="WithVirtualEnvironment"/> and <c>WithArgs</c>: /// </para> /// <example> /// <code lang="csharp"> /// builder.AddPythonScript("name", "dir", "script.py") /// .WithVirtualEnvironment("myenv") /// .WithArgs("arg1", "arg2"); /// </code> /// </example> /// </remarks> [Obsolete("Use AddPythonScript, AddPythonModule, or AddPythonExecutable and chain with .WithVirtualEnvironment(...).WithArgs(...) instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static IResourceBuilder<PythonAppResource> AddPythonApp( this IDistributedApplicationBuilder builder, string name, string appDirectory, string scriptPath, string virtualEnvironmentPath, params string[] scriptArgs) { ThrowIfNullOrContainsIsNullOrEmpty(scriptArgs); ArgumentException.ThrowIfNullOrEmpty(scriptPath); return AddPythonAppCore(builder, name, appDirectory, EntrypointType.Script, scriptPath, virtualEnvironmentPath) .WithDebugging() .WithArgs(scriptArgs); } /// <summary> /// Adds a Uvicorn-based Python application to the distributed application builder with HTTP endpoint configuration. /// </summary> /// <param name="builder">The distributed application builder to which the Uvicorn application resource will be added.</param> /// <param name="name">The unique name of the Uvicorn application resource.</param> /// <param name="appDirectory">The directory containing the Python application files.</param> /// <param name="app">The ASGI app import path which informs Uvicorn which module and variable to load as your web application. /// For example, "main:app" means "main.py" file and variable named "app".</param> /// <returns>A resource builder for further configuration of the Uvicorn Python application resource.</returns> /// <remarks> /// <para> /// This method configures the application to use Uvicorn as the ASGI server and exposes an HTTP /// endpoint. When publishing, it sets the entry point to use the Uvicorn executable with appropriate arguments for /// host and port. /// </para> /// <para> /// By default, the virtual environment folder is expected to be named <c>.venv</c> and located in the app directory. /// Use <see cref="WithVirtualEnvironment"/> to specify a different virtual environment path. /// </para> /// <para> /// In non-publish mode, the <c>--reload</c> flag is automatically added to enable hot reload during development. /// </para> /// </remarks> /// <example> /// Add a FastAPI application using Uvicorn: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// var api = builder.AddUvicornApp("api", "../fastapi-app", "main:app") /// .WithUv() /// .WithExternalHttpEndpoints(); /// /// builder.Build().Run(); /// </code> /// </example> public static IResourceBuilder<UvicornAppResource> AddUvicornApp( this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string app) { var resourceBuilder = AddPythonAppCore( builder, name, appDirectory, EntrypointType.Executable, "uvicorn", DefaultVirtualEnvFolder, (n, e, d) => new UvicornAppResource(n, e, d)) .WithDebugging() .WithHttpEndpoint(env: "PORT") .WithArgs(c => { c.Args.Add(app); c.Args.Add("--host"); var endpoint = ((IResourceWithEndpoints)c.Resource).GetEndpoint("http"); if (builder.ExecutionContext.IsPublishMode) { c.Args.Add("0.0.0.0"); } else { c.Args.Add(endpoint.EndpointAnnotation.TargetHost); } c.Args.Add("--port"); c.Args.Add(endpoint.Property(EndpointProperty.TargetPort)); // Add hot reload in non-publish mode if (!builder.ExecutionContext.IsPublishMode) { c.Args.Add("--reload"); } }) .WithServerAuthenticationCertificateConfiguration(ctx => { ctx.Arguments.Add("--ssl-keyfile"); ctx.Arguments.Add(ctx.KeyPath); ctx.Arguments.Add("--ssl-certfile"); ctx.Arguments.Add(ctx.CertificatePath); if (ctx.Password is not null) { ctx.Arguments.Add("--ssl-keyfile-password"); ctx.Arguments.Add(ctx.Password); } return Task.CompletedTask; }); if (builder.ExecutionContext.IsRunMode) { builder.Eventing.Subscribe<BeforeStartEvent>((@event, cancellationToken) => { var developerCertificateService = @event.Services.GetRequiredService<IDeveloperCertificateService>(); bool addHttps = false; if (!resourceBuilder.Resource.TryGetLastAnnotation<ServerAuthenticationCertificateAnnotation>(out var annotation)) { if (developerCertificateService.UseForServerAuthentication) { // If no certificate is configured, and the developer certificate service supports container trust, // configure the resource to use the developer certificate for its key pair. addHttps = true; } } else if (annotation.UseDeveloperCertificate.GetValueOrDefault(developerCertificateService.UseForServerAuthentication) || annotation.Certificate is not null) { addHttps = true; } if (addHttps) { // If a TLS certificate is configured, override the endpoint to use HTTPS instead of HTTP // Uvicorn only supports binding to a single port resourceBuilder .WithEndpoint("http", ep => ep.UriScheme = "https"); } return Task.CompletedTask; }); } return resourceBuilder; } private static IResourceBuilder<PythonAppResource> AddPythonAppCore( IDistributedApplicationBuilder builder, string name, string appDirectory, EntrypointType entrypointType, string entrypoint, string virtualEnvironmentPath) { return AddPythonAppCore(builder, name, appDirectory, entrypointType, entrypoint, virtualEnvironmentPath, (n, e, d) => new PythonAppResource(n, e, d)); } private static IResourceBuilder<T> AddPythonAppCore<T>( IDistributedApplicationBuilder builder, string name, string appDirectory, EntrypointType entrypointType, string entrypoint, string virtualEnvironmentPath, Func<string, string, string, T> createResource) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); ArgumentException.ThrowIfNullOrEmpty(name); ArgumentNullException.ThrowIfNull(appDirectory); ArgumentException.ThrowIfNullOrEmpty(entrypoint); ArgumentNullException.ThrowIfNull(virtualEnvironmentPath); // Register Python environment validation services (once per builder) builder.Services.TryAddSingleton<PythonInstallationManager>(); // When using the default virtual environment path, look for existing virtual environments // in multiple locations: app directory first, then AppHost directory as fallback var resolvedVenvPath = virtualEnvironmentPath; if (virtualEnvironmentPath == DefaultVirtualEnvFolder) { resolvedVenvPath = ResolveDefaultVirtualEnvironmentPath(builder, appDirectory, virtualEnvironmentPath); } // python will be replaced with the resolved entrypoint based on the virtualEnvironmentPath var resource = createResource(name, "python", Path.GetFullPath(appDirectory, builder.AppHostDirectory)); var resourceBuilder = builder .AddResource(resource) // Order matters, we need to bootstrap the entrypoint before setting the entrypoint .WithAnnotation(new PythonEntrypointAnnotation { Type = entrypointType, Entrypoint = entrypoint }) // This will resolve the correct python executable based on the virtual environment .WithVirtualEnvironment(resolvedVenvPath) // This will set up the the entrypoint based on the PythonEntrypointAnnotation .WithEntrypoint(entrypointType, entrypoint); resourceBuilder.WithIconName("CodePyRectangle"); resourceBuilder.WithOtlpExporter(); // Configure OpenTelemetry exporters using environment variables // https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#exporter-selection resourceBuilder.WithEnvironment(context => { context.EnvironmentVariables["OTEL_TRACES_EXPORTER"] = "otlp"; context.EnvironmentVariables["OTEL_LOGS_EXPORTER"] = "otlp"; context.EnvironmentVariables["OTEL_METRICS_EXPORTER"] = "otlp"; // Make sure to attach the logging instrumentation setting, so we can capture logs. // Without this you'll need to configure logging yourself. Which is kind of a pain. context.EnvironmentVariables["OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED"] = "true"; // Set PYTHONUTF8=1 on Windows in run mode to enable UTF-8 mode // See: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONUTF8 if (OperatingSystem.IsWindows() && context.ExecutionContext.IsRunMode) { context.EnvironmentVariables["PYTHONUTF8"] = "1"; } }); // Configure required environment variables for custom certificate trust when running as an executable. resourceBuilder .WithCertificateTrustScope(CertificateTrustScope.System) .WithCertificateTrustConfiguration(ctx => { if (ctx.Scope == CertificateTrustScope.Append) { var resourceLogger = ctx.ExecutionContext.ServiceProvider.GetRequiredService<ResourceLoggerService>(); var logger = resourceLogger.GetLogger(ctx.Resource); logger.LogInformation("Certificate trust scope is set to 'Append', but Python resources do not support appending to the default certificate authorities; only OTLP certificate trust will be applied."); } else { // Override default certificates path for the requests module. // See: https://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification ctx.EnvironmentVariables["REQUESTS_CA_BUNDLE"] = ctx.CertificateBundlePath; // Requests also supports CURL_CA_BUNDLE as an alternative config (lower priority than REQUESTS_CA_BUNDLE). // Setting it to be as complete as possible and avoid potential issues with conflicting configurations. ctx.EnvironmentVariables["CURL_CA_BUNDLE"] = ctx.CertificateBundlePath; } // Override default opentelemetry-python certificate bundle path // See: https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html#module-opentelemetry.exporter.otlp ctx.EnvironmentVariables["OTEL_EXPORTER_OTLP_CERTIFICATE"] = ctx.CertificateBundlePath; return Task.CompletedTask; }); resourceBuilder.PublishAsDockerFile(c => { // Only generate a Dockerfile if one doesn't already exist in the app directory if (File.Exists(Path.Combine(resource.WorkingDirectory, "Dockerfile"))) { return; } c.WithDockerfileBuilder(resource.WorkingDirectory, context => { if (!context.Resource.TryGetLastAnnotation<PythonEntrypointAnnotation>(out var entrypointAnnotation)) { // No entrypoint annotation found, cannot generate Dockerfile return; } // Try to get Python environment annotation context.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var pythonEnvironmentAnnotation); // Detect Python version var pythonVersion = pythonEnvironmentAnnotation?.Version; if (pythonVersion is null) { var virtualEnvironment = pythonEnvironmentAnnotation?.VirtualEnvironment; pythonVersion = PythonVersionDetector.DetectVersion(appDirectory, virtualEnvironment); } // if we could not detect Python version, use the default pythonVersion ??= DefaultPythonVersion; var entrypointType = entrypointAnnotation.Type; var entrypoint = entrypointAnnotation.Entrypoint; // Check if using UV by looking at the package manager annotation var isUsingUv = context.Resource.TryGetLastAnnotation<PythonPackageManagerAnnotation>(out var pkgMgr) && pkgMgr.ExecutableName == "uv"; if (isUsingUv) { GenerateUvDockerfile(context, resource, pythonVersion, entrypointType, entrypoint); } else { GenerateFallbackDockerfile(context, resource, pythonVersion, entrypointType, entrypoint); } }); }); resourceBuilder.WithPipelineConfiguration(context => { if (resourceBuilder.Resource.TryGetAnnotationsOfType<ContainerFilesDestinationAnnotation>(out var containerFilesAnnotations)) { var buildSteps = context.GetSteps(resourceBuilder.Resource, WellKnownPipelineTags.BuildCompute); foreach (var containerFile in containerFilesAnnotations) { buildSteps.DependsOn(context.GetSteps(containerFile.Source, WellKnownPipelineTags.BuildCompute)); } } }); if (builder.ExecutionContext.IsRunMode) { // Subscribe to BeforeStartEvent for this specific resource to wire up dependencies dynamically // This allows methods like WithPip, WithUv, and WithVirtualEnvironment to add/remove resources // and the dependencies will be established based on which resources actually exist // Only do this in run mode since the installer and venv creator only run in run mode var resourceToSetup = resourceBuilder.Resource; builder.Eventing.Subscribe<BeforeStartEvent>((evt, ct) => { // Wire up wait dependencies for this resource based on which child resources exist SetupDependencies(builder, resourceToSetup); return Task.CompletedTask; }); // Automatically add pip as the package manager if pyproject.toml or requirements.txt exists // Only do this in run mode since the installer resource only runs in run mode // Note: pip supports both pyproject.toml and requirements.txt var appDirectoryFullPath = Path.GetFullPath(appDirectory, builder.AppHostDirectory); if (File.Exists(Path.Combine(appDirectoryFullPath, "pyproject.toml")) || File.Exists(Path.Combine(appDirectoryFullPath, "requirements.txt"))) { resourceBuilder.WithPip(); } else { // No package files found, but we should still create venv if it doesn't exist // and createIfNotExists is true (which is the default) CreateVenvCreatorIfNeeded(resourceBuilder); } } return resourceBuilder; } private static void GenerateUvDockerfile(DockerfileBuilderCallbackContext context, PythonAppResource resource, string pythonVersion, EntrypointType entrypointType, string entrypoint) { // Check if uv.lock exists in the working directory var uvLockPath = Path.Combine(resource.WorkingDirectory, "uv.lock"); var hasUvLock = File.Exists(uvLockPath); // Get custom base images from annotation, if present context.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation); var buildImage = baseImageAnnotation?.BuildImage ?? $"ghcr.io/astral-sh/uv:python{pythonVersion}-bookworm-slim"; var runtimeImage = baseImageAnnotation?.RuntimeImage ?? $"python:{pythonVersion}-slim-bookworm"; var builderStage = context.Builder .From(buildImage, "builder") .EmptyLine() .Comment("Enable bytecode compilation and copy mode for the virtual environment") .Env("UV_COMPILE_BYTECODE", "1") .Env("UV_LINK_MODE", "copy") .EmptyLine() .WorkDir("/app") .EmptyLine(); if (hasUvLock) { // If uv.lock exists, use locked mode for reproducible builds builderStage .Comment("Install dependencies first for better layer caching") .Comment("Uses BuildKit cache mounts to speed up repeated builds") .RunWithMounts( "uv sync --locked --no-install-project --no-dev", "type=cache,target=/root/.cache/uv", "type=bind,source=uv.lock,target=uv.lock", "type=bind,source=pyproject.toml,target=pyproject.toml") .EmptyLine() .Comment("Copy the rest of the application source and install the project") .Copy(".", "/app") .RunWithMounts( "uv sync --locked --no-dev", "type=cache,target=/root/.cache/uv"); } else { // If uv.lock doesn't exist, copy pyproject.toml and generate lock file builderStage .Comment("Copy pyproject.toml to install dependencies") .Copy("pyproject.toml", "/app/") .EmptyLine() .Comment("Install dependencies and generate lock file") .Comment("Uses BuildKit cache mount to speed up repeated builds") .RunWithMounts( "uv sync --no-install-project --no-dev", "type=cache,target=/root/.cache/uv") .EmptyLine() .Comment("Copy the rest of the application source and install the project") .Copy(".", "/app") .RunWithMounts( "uv sync --no-dev", "type=cache,target=/root/.cache/uv"); } var logger = context.Services.GetService<ILogger<PythonAppResource>>(); context.Builder.AddContainerFilesStages(context.Resource, logger); var runtimeBuilder = context.Builder .From(runtimeImage, "app") .EmptyLine() .AddContainerFiles(context.Resource, "/app", logger) .Comment("------------------------------") .Comment("🚀 Runtime stage") .Comment("------------------------------") .Comment("Create non-root user for security") .Run("groupadd --system --gid 999 appuser && useradd --system --gid 999 --uid 999 --create-home appuser") .EmptyLine() .Comment("Copy the application and virtual environment from builder") .CopyFrom(builderStage.StageName!, "/app", "/app", "appuser:appuser") .EmptyLine() .Comment("Add virtual environment to PATH and set VIRTUAL_ENV") .Env("PATH", "/app/.venv/bin:${PATH}") .Env("VIRTUAL_ENV", "/app/.venv") .Env("PYTHONDONTWRITEBYTECODE", "1") .Env("PYTHONUNBUFFERED", "1") .EmptyLine() .Comment("Use the non-root user to run the application") .User("appuser") .EmptyLine() .Comment("Set working directory") .WorkDir("/app") .EmptyLine() .Comment("Run the application"); // Set the appropriate entrypoint and command based on entrypoint type switch (entrypointType) { case EntrypointType.Script: runtimeBuilder.Entrypoint(["python", entrypoint]); break; case EntrypointType.Module: runtimeBuilder.Entrypoint(["python", "-m", entrypoint]); break; case EntrypointType.Executable: runtimeBuilder.Entrypoint([entrypoint]); break; } } private static void GenerateFallbackDockerfile(DockerfileBuilderCallbackContext context, PythonAppResource resource, string pythonVersion, EntrypointType entrypointType, string entrypoint) { // Use the same runtime image as UV workflow for consistency context.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation); var runtimeImage = baseImageAnnotation?.RuntimeImage ?? $"python:{pythonVersion}-slim-bookworm"; // Check if requirements.txt or pyproject.toml exists var requirementsTxtPath = Path.Combine(resource.WorkingDirectory, "requirements.txt"); var hasRequirementsTxt = File.Exists(requirementsTxtPath); var logger = context.Services.GetService<ILogger<PythonAppResource>>(); context.Builder.AddContainerFilesStages(context.Resource, logger); var stage = context.Builder .From(runtimeImage) .EmptyLine() .AddContainerFiles(context.Resource, "/app", logger) .Comment("------------------------------") .Comment("🚀 Python Application") .Comment("------------------------------") .Comment("Create non-root user for security") .Run("groupadd --system --gid 999 appuser && useradd --system --gid 999 --uid 999 --create-home appuser") .EmptyLine() .Comment("Set working directory") .WorkDir("/app") .EmptyLine(); if (hasRequirementsTxt) { // Copy requirements.txt first for better layer caching stage .Comment("Copy requirements.txt for dependency installation") .Copy("requirements.txt", "/app/requirements.txt") .EmptyLine() .Comment("Install dependencies using pip") .Run( """ apt-get update \ && apt-get install -y --no-install-recommends build-essential \ && pip install --no-cache-dir -r requirements.txt \ && apt-get purge -y --auto-remove build-essential \ && rm -rf /var/lib/apt/lists/* """) .EmptyLine(); } else { var pyprojectTomlPath = Path.Combine(resource.WorkingDirectory, "pyproject.toml"); var hasPyprojectToml = File.Exists(pyprojectTomlPath); if (hasPyprojectToml) { // Copy pyproject.toml first for better layer caching stage .Comment("Copy pyproject.toml for dependency installation") .Copy("pyproject.toml", "/app/pyproject.toml") .EmptyLine() .Comment("Install dependencies using pip") .Run( """ apt-get update \ && apt-get install -y --no-install-recommends build-essential \ && pip install --no-cache-dir . \ && apt-get purge -y --auto-remove build-essential \ && rm -rf /var/lib/apt/lists/* """) .EmptyLine(); } } // Copy the rest of the application stage .Comment("Copy application files") .Copy(".", "/app", "appuser:appuser") .EmptyLine() .Comment("Set environment variables") .Env("PYTHONDONTWRITEBYTECODE", "1") .Env("PYTHONUNBUFFERED", "1") .EmptyLine() .Comment("Use the non-root user to run the application") .User("appuser") .EmptyLine() .Comment("Run the application"); // Set the appropriate entrypoint based on entrypoint type switch (entrypointType) { case EntrypointType.Script: stage.Entrypoint(["python", entrypoint]); break; case EntrypointType.Module: stage.Entrypoint(["python", "-m", entrypoint]); break; case EntrypointType.Executable: stage.Entrypoint([entrypoint]); break; } } private static void ThrowIfNullOrContainsIsNullOrEmpty(string[] scriptArgs) { ArgumentNullException.ThrowIfNull(scriptArgs); foreach (var scriptArg in scriptArgs) { if (string.IsNullOrEmpty(scriptArg)) { var values = string.Join(", ", scriptArgs); if (scriptArg is null) { throw new ArgumentNullException(nameof(scriptArgs), $"Array params contains null item: [{values}]"); } throw new ArgumentException($"Array params contains empty item: [{values}]", nameof(scriptArgs)); } } } /// <summary> /// Resolves the default virtual environment path by checking multiple candidate locations. /// </summary> /// <param name="builder">The distributed application builder.</param> /// <param name="appDirectory">The Python app directory (relative to AppHost).</param> /// <param name="virtualEnvironmentPath">The relative virtual environment path (e.g., ".venv").</param> /// <returns>The resolved virtual environment path.</returns> private static string ResolveDefaultVirtualEnvironmentPath(IDistributedApplicationBuilder builder, string appDirectory, string virtualEnvironmentPath) { var appDirectoryFullPath = Path.GetFullPath(appDirectory, builder.AppHostDirectory); // Walk up from the Python app directory looking for the virtual environment // Stop at the AppHost's parent directory to avoid picking up unrelated venvs var appHostParentDirectory = Path.GetDirectoryName(builder.AppHostDirectory); // Check if the app directory is under the AppHost's parent directory // If not, only look in the app directory itself if (appHostParentDirectory != null) { var relativePath = Path.GetRelativePath(appHostParentDirectory, appDirectoryFullPath); var isUnderAppHostParent = !relativePath.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relativePath); if (!isUnderAppHostParent) { // App is not under AppHost's parent, only use the app directory return Path.Combine(appDirectoryFullPath, virtualEnvironmentPath); } } var currentDirectory = appDirectoryFullPath; while (currentDirectory != null) { var venvPath = Path.Combine(currentDirectory, virtualEnvironmentPath); if (Directory.Exists(venvPath)) { return venvPath; } // Stop if we've reached the AppHost's parent directory // Use case-insensitive comparison on Windows, case-sensitive on Unix var reachedBoundary = OperatingSystem.IsWindows() ? string.Equals(currentDirectory, appHostParentDirectory, StringComparison.OrdinalIgnoreCase) : string.Equals(currentDirectory, appHostParentDirectory, StringComparison.Ordinal); if (reachedBoundary) { break; } // Move up to the parent directory var parentDirectory = Path.GetDirectoryName(currentDirectory); // Stop if we can't go up anymore or if we've gone beyond the AppHost's parent if (parentDirectory == null || parentDirectory == currentDirectory) { break; } currentDirectory = parentDirectory; } // Default: Return app directory path (for cases where the venv will be created later) return Path.Combine(appDirectoryFullPath, virtualEnvironmentPath); } /// <summary> /// Configures a custom virtual environment path for the Python application. /// </summary> /// <param name="builder">The resource builder.</param> /// <param name="virtualEnvironmentPath"> /// The path to the virtual environment. Can be absolute or relative to the app directory. /// When relative, it is resolved from the working directory of the Python application. /// Common values include ".venv", "venv", or "myenv". /// </param> /// <param name="createIfNotExists"> /// Whether to automatically create the virtual environment if it doesn't exist. Defaults to <c>true</c>. /// Set to <c>false</c> to disable automatic venv creation (the venv must already exist). /// </param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for method chaining.</returns> /// <remarks> /// <para> /// This method updates the Python executable path to use the specified virtual environment. /// </para> /// <para> /// By default (<paramref name="createIfNotExists"/> = <c>true</c>), if the virtual environment doesn't exist, /// it will be automatically created before running the application (when using pip package manager, not uv). /// Set <paramref name="createIfNotExists"/> to <c>false</c> to disable this behavior and require the venv to already exist. /// </para> /// <para> /// Virtual environments allow Python applications to have isolated dependencies separate from /// the system Python installation. This is the recommended approach for Python applications. /// </para> /// <para> /// When you explicitly specify a virtual environment path using this method, the path is used verbatim. /// The automatic multi-location lookup (checking both app and AppHost directories) only applies when /// using the default ".venv" path during initial app creation via AddPythonScript, AddPythonModule, or AddPythonExecutable. /// </para> /// </remarks> /// <example> /// Configure a Python app to use a custom virtual environment: /// <code lang="csharp"> /// var python = builder.AddPythonApp("api", "../python-api", "main.py") /// .WithVirtualEnvironment("myenv"); /// /// // Disable automatic venv creation (require venv to exist) /// var python2 = builder.AddPythonApp("api2", "../python-api2", "main.py") /// .WithVirtualEnvironment("myenv", createIfNotExists: false); /// </code> /// </example> public static IResourceBuilder<T> WithVirtualEnvironment<T>( this IResourceBuilder<T> builder, string virtualEnvironmentPath, bool createIfNotExists = true) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); ArgumentException.ThrowIfNullOrEmpty(virtualEnvironmentPath); // Use the provided path verbatim - resolve relative paths against the app working directory var resolvedPath = Path.IsPathRooted(virtualEnvironmentPath) ? virtualEnvironmentPath : Path.GetFullPath(virtualEnvironmentPath, builder.Resource.WorkingDirectory); var virtualEnvironment = new VirtualEnvironment(resolvedPath); // Get the entrypoint annotation to determine how to update the command if (!builder.Resource.TryGetLastAnnotation<PythonEntrypointAnnotation>(out var entrypointAnnotation)) { throw new InvalidOperationException("Cannot update virtual environment: Python entrypoint annotation not found."); } // Update the command based on entrypoint type string command = entrypointAnnotation.Type switch { EntrypointType.Executable => virtualEnvironment.GetExecutable(entrypointAnnotation.Entrypoint), EntrypointType.Script or EntrypointType.Module => virtualEnvironment.GetExecutable("python"), _ => throw new InvalidOperationException($"Unsupported entrypoint type: {entrypointAnnotation.Type}") }; builder.WithCommand(command); builder.WithPythonEnvironment(env => { env.VirtualEnvironment = virtualEnvironment; env.CreateVenvIfNotExists = createIfNotExists; }); // If createIfNotExists is false, remove venv creator if (!createIfNotExists) { RemoveVenvCreator(builder); } return builder; } /// <summary> /// Enables debugging support for the Python application. /// </summary> /// <param name="builder">The resource builder.</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for method chaining.</returns> /// <remarks> /// <para> /// This method adds the <see cref="PythonExecutableDebuggableAnnotation"/> to the resource, which enables /// debugging support. The debugging configuration is automatically set up based on the /// entrypoint type (Script, Module, or Executable). /// </para> /// <para> /// The debug configuration includes the Python interpreter path from the virtual environment, /// the program or module to debug, and appropriate launch settings. /// </para> /// </remarks> public static IResourceBuilder<T> WithDebugging<T>( this IResourceBuilder<T> builder) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); // Add the annotation that marks this resource as debuggable builder.WithAnnotation(new PythonExecutableDebuggableAnnotation()); // Get the entrypoint annotation to determine how to configure debugging if (!builder.Resource.TryGetLastAnnotation<PythonEntrypointAnnotation>(out var entrypointAnnotation)) { throw new InvalidOperationException("Cannot configure debugging: Python entrypoint annotation not found."); } var entrypointType = entrypointAnnotation.Type; var entrypoint = entrypointAnnotation.Entrypoint; string programPath; string module; if (entrypointType == EntrypointType.Script) { programPath = Path.GetFullPath(entrypoint, builder.Resource.WorkingDirectory); module = string.Empty; } else { programPath = builder.Resource.WorkingDirectory; module = entrypoint; } builder.WithDebugSupport( mode => { string interpreterPath; if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var annotation) || annotation.VirtualEnvironment is null) { interpreterPath = string.Empty; } else { var venvPath = Path.IsPathRooted(annotation.VirtualEnvironment.VirtualEnvironmentPath) ? annotation.VirtualEnvironment.VirtualEnvironmentPath : Path.GetFullPath(annotation.VirtualEnvironment.VirtualEnvironmentPath, builder.Resource.WorkingDirectory); if (OperatingSystem.IsWindows()) { interpreterPath = Path.Join(venvPath, "Scripts", "python.exe"); } else { interpreterPath = Path.Join(venvPath, "bin", "python"); } } return new PythonLaunchConfiguration { ProgramPath = programPath, Module = module, Mode = mode, InterpreterPath = interpreterPath }; }, "python", static ctx => { // Remove entrypoint-specific arguments that VS Code will handle. // We need to verify the annotation to ensure we remove the correct args. if (!ctx.Resource.TryGetLastAnnotation<PythonEntrypointAnnotation>(out var annotation)) { return; } // For Module type: remove "-m" and module name (2 args) if (annotation.Type == EntrypointType.Module) { if (ctx.Args is [string arg0, string arg1, ..] && arg0 == "-m" && arg1 == annotation.Entrypoint) { ctx.Args.RemoveAt(0); // Remove "-m" ctx.Args.RemoveAt(0); // Remove module name } } // For Script type: remove script path (1 arg) else if (annotation.Type == EntrypointType.Script) { if (ctx.Args is [string arg0, ..] && arg0 == annotation.Entrypoint) { ctx.Args.RemoveAt(0); // Remove script path } } }); return builder; } /// <summary> /// Configures the entrypoint for the Python application. /// </summary> /// <param name="builder">The resource builder.</param> /// <param name="entrypointType">The type of entrypoint (Script, Module, or Executable).</param> /// <param name="entrypoint">The entrypoint value (script path, module name, or executable name).</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for method chaining.</returns> /// <remarks> /// <para> /// This method allows you to change the entrypoint configuration of a Python application after it has been created. /// The command and arguments will be updated based on the specified entrypoint type: /// </para> /// <list type="bullet"> /// <item><description><b>Script</b>: Runs as <c>python &lt;scriptPath&gt;</c></description></item> /// <item><description><b>Module</b>: Runs as <c>python -m &lt;moduleName&gt;</c></description></item> /// <item><description><b>Executable</b>: Runs the executable directly from the virtual environment</description></item> /// </list> /// <para> /// <b>Important:</b> This method resets all command-line arguments. If you need to add arguments after changing /// the entrypoint, call <c>WithArgs</c> after this method. /// </para> /// </remarks> /// <example> /// Change a Python app from running a script to running a module: /// <code lang="csharp"> /// var python = builder.AddPythonScript("api", "../python-api", "main.py") /// .WithEntrypoint(EntrypointType.Module, "uvicorn") /// .WithArgs("main:app", "--reload"); /// </code> /// </example> public static IResourceBuilder<T> WithEntrypoint<T>( this IResourceBuilder<T> builder, EntrypointType entrypointType, string entrypoint) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); ArgumentException.ThrowIfNullOrEmpty(entrypoint); // Get or create the virtual environment from the annotation if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var pythonEnv) || pythonEnv.VirtualEnvironment is null) { throw new InvalidOperationException("Cannot set entrypoint: Python environment annotation with virtual environment not found."); } var virtualEnvironment = pythonEnv.VirtualEnvironment; // Determine the new command based on entrypoint type var command = entrypointType switch { EntrypointType.Executable => virtualEnvironment.GetExecutable(entrypoint), EntrypointType.Script or EntrypointType.Module => virtualEnvironment.GetExecutable("python"), _ => throw new ArgumentOutOfRangeException(nameof(entrypointType), entrypointType, "Invalid entrypoint type.") }; // Update the command inline builder.WithCommand(command); builder.WithAnnotation(new PythonEntrypointAnnotation { Type = entrypointType, Entrypoint = entrypoint }, ResourceAnnotationMutationBehavior.Replace); builder.WithArgs(static context => { if (!context.Resource.TryGetLastAnnotation<PythonEntrypointAnnotation>(out var existingAnnotation)) { return; } // Clear existing args since we're replacing the entrypoint context.Args.Clear(); var entrypointType = existingAnnotation.Type; var entrypoint = existingAnnotation.Entrypoint; // Add entrypoint-specific arguments switch (entrypointType) { case EntrypointType.Module: context.Args.Add("-m"); context.Args.Add(entrypoint); break; case EntrypointType.Script: context.Args.Add(entrypoint); break; case EntrypointType.Executable: // Executable runs directly, no additional args needed for entrypoint break; } }); return builder; } /// <summary> /// Configures the Python resource to use pip as the package manager and optionally installs packages before the application starts. /// </summary> /// <typeparam name="T">The type of the Python application resource, must derive from <see cref="PythonAppResource"/>.</typeparam> /// <param name="builder">The resource builder.</param> /// <param name="install">When true (default), automatically installs packages before the application starts. When false, only sets the package manager annotation without creating an installer resource.</param> /// <param name="installArgs">The command-line arguments passed to pip install command.</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for method chaining.</returns> /// <remarks> /// <para> /// This method creates a child resource that runs <c>pip install</c> in the working directory of the Python application. /// The Python application will wait for this resource to complete successfully before starting. /// </para> /// <para> /// Pip will automatically detect and use either pyproject.toml or requirements.txt based on which file exists in the application directory. /// If pyproject.toml exists, pip will use it. Otherwise, if requirements.txt exists, pip will use that. /// Calling this method will replace any previously configured package manager (such as uv). /// </para> /// </remarks> /// <example> /// Add a Python app with automatic pip package installation: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// var python = builder.AddPythonScript("api", "../python-api", "main.py") /// .WithPip() // Automatically installs from pyproject.toml or requirements.txt /// .WithHttpEndpoint(port: 5000); /// /// builder.Build().Run(); /// </code> /// </example> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> is null.</exception> public static IResourceBuilder<T> WithPip<T>(this IResourceBuilder<T> builder, bool install = true, string[]? installArgs = null) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); // Ensure virtual environment exists - create default .venv if not configured if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var pythonEnv) || pythonEnv.VirtualEnvironment is null) { // Create default virtual environment if none exists builder.WithVirtualEnvironment(".venv"); pythonEnv = builder.Resource.Annotations.OfType<PythonEnvironmentAnnotation>().Last(); } var virtualEnvironment = pythonEnv.VirtualEnvironment!; // Determine install command based on which file exists // Pip supports both pyproject.toml and requirements.txt var workingDirectory = builder.Resource.WorkingDirectory; string[] baseInstallArgs; if (File.Exists(Path.Combine(workingDirectory, "pyproject.toml"))) { // Use pip install with pyproject.toml (pip will read from pyproject.toml automatically) baseInstallArgs = ["install", "."]; } else if (File.Exists(Path.Combine(workingDirectory, "requirements.txt"))) { // Use pip install with requirements.txt baseInstallArgs = ["install", "-r", "requirements.txt"]; } else { // Default to requirements.txt even if it doesn't exist (will fail at runtime if no file is present) baseInstallArgs = ["install", "-r", "requirements.txt"]; } builder .WithAnnotation(new PythonPackageManagerAnnotation(virtualEnvironment.GetExecutable("pip")), ResourceAnnotationMutationBehavior.Replace) .WithAnnotation(new PythonInstallCommandAnnotation([.. baseInstallArgs, .. installArgs ?? []]), ResourceAnnotationMutationBehavior.Replace); AddInstaller(builder, install); // Create venv creator if needed (will check if venv exists) CreateVenvCreatorIfNeeded(builder); return builder; } /// <summary> /// Adds a UV environment setup task to ensure the virtual environment exists before running the Python application. /// </summary> /// <typeparam name="T">The type of the Python application resource, must derive from <see cref="PythonAppResource"/>.</typeparam> /// <param name="builder">The resource builder.</param> /// <param name="install">When true (default), automatically runs uv sync before the application starts. When false, only sets the package manager annotation without creating an installer resource.</param> /// <param name="args">Optional custom arguments to pass to the uv command. If not provided, defaults to ["sync"].</param> /// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for method chaining.</returns> /// <remarks> /// <para> /// This method creates a child resource that runs <c>uv sync</c> in the working directory of the Python application. /// The Python application will wait for this resource to complete successfully before starting. /// </para> /// <para> /// UV (https://github.com/astral-sh/uv) is a modern Python package manager written in Rust that can manage virtual environments /// and dependencies with significantly faster performance than traditional tools. The <c>uv sync</c> command ensures that the virtual /// environment exists, Python is installed if needed, and all dependencies specified in pyproject.toml are installed and synchronized. /// </para> /// <para> /// Calling this method will replace any previously configured package manager (such as pip). /// </para> /// </remarks> /// <example> /// Add a Python app with automatic UV environment setup: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// var python = builder.AddPythonScript("api", "../python-api", "main.py") /// .WithUv() // Automatically runs 'uv sync' before starting the app /// .WithHttpEndpoint(port: 5000); /// /// builder.Build().Run(); /// </code> /// </example> /// <example> /// Add a Python app with custom UV arguments: /// <code lang="csharp"> /// var builder = DistributedApplication.CreateBuilder(args); /// /// var python = builder.AddPythonScript("api", "../python-api", "main.py") /// .WithUv(args: ["sync", "--python", "3.12", "--no-dev"]) // Custom uv sync args /// .WithHttpEndpoint(port: 5000); /// /// builder.Build().Run(); /// </code> /// </example> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> is null.</exception> public static IResourceBuilder<T> WithUv<T>(this IResourceBuilder<T> builder, bool install = true, string[]? args = null) where T : PythonAppResource { ArgumentNullException.ThrowIfNull(builder); // Register UV validation service builder.ApplicationBuilder.Services.TryAddSingleton<UvInstallationManager>(); // Default args: sync only (uv will auto-detect Python and dependencies from pyproject.toml) args ??= ["sync"]; builder .WithAnnotation(new PythonPackageManagerAnnotation("uv"), ResourceAnnotationMutationBehavior.Replace) .WithAnnotation(new PythonInstallCommandAnnotation(args), ResourceAnnotationMutationBehavior.Replace); AddInstaller(builder, install); // UV handles venv creation, so remove any existing venv creator RemoveVenvCreator(builder); return builder; } private static bool IsPythonCommandAvailable(string command) { var pathVariable = Environment.GetEnvironmentVariable("PATH"); if (string.IsNullOrWhiteSpace(pathVariable)) { return false; } if (OperatingSystem.IsWindows()) { // On Windows, try both .exe and .cmd extensions foreach (var ext in new[] { ".exe", ".cmd" }) { var commandWithExt = command + ext; foreach (var directory in pathVariable.Split(Path.PathSeparator)) { var fullPath = Path.Combine(directory, commandWithExt); if (File.Exists(fullPath)) { return true; } } } } else { // On Unix-like systems, no extension needed foreach (var directory in pathVariable.Split(Path.PathSeparator)) { var fullPath = Path.Combine(directory, command); if (File.Exists(fullPath)) { return true; } } } return false; } private static void AddInstaller<T>(IResourceBuilder<T> builder, bool install) where T : PythonAppResource { // Only install packages if in run mode if (builder.ApplicationBuilder.ExecutionContext.IsRunMode) { // Check if the installer resource already exists var installerName = $"{builder.Resource.Name}-installer"; builder.ApplicationBuilder.TryCreateResourceBuilder<PythonInstallerResource>(installerName, out var existingResource); if (!install) { if (existingResource != null) { // Remove existing installer resource if install is false builder.ApplicationBuilder.Resources.Remove(existingResource.Resource); builder.Resource.Annotations.OfType<PythonPackageInstallerAnnotation>() .ToList() .ForEach(a => builder.Resource.Annotations.Remove(a)); } return; } if (existingResource is not null) { // Installer already exists, it will be reconfigured via BeforeStartEvent return; } var installer = new PythonInstallerResource(installerName, builder.Resource); var installerBuilder = builder.ApplicationBuilder.AddResource(installer) .WithParentRelationship(builder.Resource) .ExcludeFromManifest(); // Add validation for the installer command (uv or python) installerBuilder.OnBeforeResourceStarted(static async (installerResource, e, ct) => { // Check which command this installer is using (set by BeforeStartEvent) if (installerResource.TryGetLastAnnotation<ExecutableAnnotation>(out var executable) && executable.Command == "uv") { // Validate that uv is installed - don't throw so the app fails as it normally would var uvInstallationManager = e.Services.GetRequiredService<UvInstallationManager>(); await uvInstallationManager.EnsureInstalledAsync(throwOnFailure: false, ct).ConfigureAwait(false); } // For other package managers (pip, etc.), Python validation happens via PythonVenvCreatorResource }); builder.ApplicationBuilder.Eventing.Subscribe<BeforeStartEvent>((_, _) => { // Set the installer's working directory to match the resource's working directory // and set the install command and args based on the resource's annotations if (!builder.Resource.TryGetLastAnnotation<PythonPackageManagerAnnotation>(out var packageManager) || !builder.Resource.TryGetLastAnnotation<PythonInstallCommandAnnotation>(out var installCommand)) { // No package manager configured - don't fail, just don't run the installer // This allows venv to be created without requiring a package manager return Task.CompletedTask; } installerBuilder .WithCommand(packageManager.ExecutableName) .WithWorkingDirectory(builder.Resource.WorkingDirectory) .WithArgs(installCommand.Args); return Task.CompletedTask; }); builder.WithAnnotation(new PythonPackageInstallerAnnotation(installer)); } } private static void CreateVenvCreatorIfNeeded<T>(IResourceBuilder<T> builder) where T : PythonAppResource { // Check if we should create a venv if (!ShouldCreateVenv(builder)) { return; } if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var pythonEnv) || pythonEnv.VirtualEnvironment == null) { return; } var venvPath = Path.IsPathRooted(pythonEnv.VirtualEnvironment.VirtualEnvironmentPath) ? pythonEnv.VirtualEnvironment.VirtualEnvironmentPath : Path.GetFullPath(pythonEnv.VirtualEnvironment.VirtualEnvironmentPath, builder.Resource.WorkingDirectory); // Create venv creator as a child resource var venvCreatorName = $"{builder.Resource.Name}-venv-creator"; // Use TryCreateResourceBuilder to check if it already exists if (builder.ApplicationBuilder.TryCreateResourceBuilder<PythonVenvCreatorResource>(venvCreatorName, out _)) { // Venv creator already exists, no need to create again return; } // Create new venv creator resource var venvCreator = new PythonVenvCreatorResource(venvCreatorName, builder.Resource, venvPath); // Determine which Python command to use string pythonCommand; if (OperatingSystem.IsWindows()) { // On Windows, try py launcher first, then python pythonCommand = IsPythonCommandAvailable("py") ? "py" : "python"; } else { // On Unix-like systems, try python3 first (more explicit), then python pythonCommand = IsPythonCommandAvailable("python3") ? "python3" : "python"; } builder.ApplicationBuilder.AddResource(venvCreator) .WithCommand(pythonCommand) .WithArgs(["-m", "venv", venvPath]) .WithWorkingDirectory(builder.Resource.WorkingDirectory) .WithParentRelationship(builder.Resource) .ExcludeFromManifest() .OnBeforeResourceStarted(static async (venvCreatorResource, e, ct) => { // Validate that Python is installed before creating venv - don't throw so the app fails as it normally would var pythonInstallationManager = e.Services.GetRequiredService<PythonInstallationManager>(); await pythonInstallationManager.EnsureInstalledAsync(throwOnFailure: false, ct).ConfigureAwait(false); }); // Wait relationships will be set up dynamically in SetupDependencies } private static void RemoveVenvCreator<T>(IResourceBuilder<T> builder) where T : PythonAppResource { var venvCreatorName = $"{builder.Resource.Name}-venv-creator"; // Use TryCreateResourceBuilder to check if venv creator exists if (builder.ApplicationBuilder.TryCreateResourceBuilder<PythonVenvCreatorResource>(venvCreatorName, out var venvCreatorBuilder)) { builder.ApplicationBuilder.Resources.Remove(venvCreatorBuilder.Resource); // Wait relationships are managed dynamically in SetupDependencies, so no need to clean them up here } } private static void SetupDependencies(IDistributedApplicationBuilder builder, PythonAppResource resource) { // This method is called in BeforeStartEvent to dynamically set up dependencies // based on which child resources actually exist after all method calls have been made var venvCreatorName = $"{resource.Name}-venv-creator"; var installerName = $"{resource.Name}-installer"; // Try to get the venv creator and installer resources builder.TryCreateResourceBuilder<PythonVenvCreatorResource>(venvCreatorName, out var venvCreatorBuilder); builder.TryCreateResourceBuilder<PythonInstallerResource>(installerName, out var installerBuilder); // Get the Python app resource builder builder.TryCreateResourceBuilder<PythonAppResource>(resource.Name, out var appBuilder); if (appBuilder == null) { return; // Resource doesn't exist, nothing to set up } // Set up wait dependencies based on what exists: // 1. If both venv creator and installer exist: installer waits for venv creator, app waits for installer // 2. If only installer exists: app waits for installer // 3. If only venv creator exists: app waits for venv creator (no installer needed) // 4. If neither exists: app runs directly (no waits needed) if (venvCreatorBuilder != null && installerBuilder != null) { // Both exist: installer waits for venv, app waits for installer installerBuilder.WaitForCompletion(venvCreatorBuilder); appBuilder.WaitForCompletion(installerBuilder); } else if (installerBuilder != null) { // Only installer exists: app waits for installer appBuilder.WaitForCompletion(installerBuilder); } else if (venvCreatorBuilder != null) { // Only venv creator exists: app waits for venv creator appBuilder.WaitForCompletion(venvCreatorBuilder); } // If neither exists, no wait relationships needed } private static bool ShouldCreateVenv<T>(IResourceBuilder<T> builder) where T : PythonAppResource { // Check if we're using uv (which handles venv creation itself) var isUsingUv = builder.Resource.TryGetLastAnnotation<PythonPackageManagerAnnotation>(out var pkgMgr) && pkgMgr.ExecutableName == "uv"; if (isUsingUv) { // UV handles venv creation, we don't need to create it return false; } // Get the virtual environment path if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var pythonEnv) || pythonEnv.VirtualEnvironment == null) { return false; } // Check if automatic venv creation is disabled if (!pythonEnv.CreateVenvIfNotExists) { return false; } var venvPath = Path.IsPathRooted(pythonEnv.VirtualEnvironment.VirtualEnvironmentPath) ? pythonEnv.VirtualEnvironment.VirtualEnvironmentPath : Path.GetFullPath(pythonEnv.VirtualEnvironment.VirtualEnvironmentPath, builder.Resource.WorkingDirectory); // Check if venv directory exists (simple check, don't verify validity) if (Directory.Exists(venvPath)) { return false; } return true; } internal static IResourceBuilder<PythonAppResource> WithPythonEnvironment(this IResourceBuilder<PythonAppResource> builder, Action<PythonEnvironmentAnnotation> configure) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configure); if (!builder.Resource.TryGetLastAnnotation<PythonEnvironmentAnnotation>(out var existing)) { existing = new PythonEnvironmentAnnotation(); builder.WithAnnotation(existing); } configure(existing); return builder; } }
PythonAppResourceBuilderExtensions
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Conventions/IgnoreIfNullConventionsTests.cs
{ "start": 761, "end": 1227 }
public class ____ { [Theory] [InlineData(true)] [InlineData(false)] public void TestApply(bool value) { var subject = new IgnoreIfNullConvention(value); var classMap = new BsonClassMap<TestClass>(); var memberMap = classMap.MapMember(x => x.Id); subject.Apply(memberMap); Assert.Equal(value, memberMap.IgnoreIfNull); }
IgnoreIfNullConventionsTests
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs
{ "start": 116, "end": 9208 }
public class ____ { [Fact] public async Task Node_Resolve_Separated_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo>() .AddObjectType<Bar>(d => d .ImplementsNode() .IdField(t => t.Id) .ResolveNodeWith<BarResolver>(t => t.GetBarAsync(null!))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Nodes_Get_Single() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo>() .AddObjectType<Bar>(d => d .ImplementsNode() .IdField(t => t.Id) .ResolveNodeWith<BarResolver>(t => t.GetBarAsync(null!))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ nodes(ids: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Tow_Many_Nodes() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification(o => o.MaxAllowedNodeBatchSize = 1) .AddQueryType<Foo>() .AddObjectType<Bar>(d => d .ImplementsNode() .IdField(t => t.Id) .ResolveNodeWith<BarResolver>(t => t.GetBarAsync(null!))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ nodes(ids: [\"QmFyOjEyMw==\", \"QmFyOjEyMw==\"]) { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Nodes_Get_Many() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo>() .AddObjectType<Bar>(d => d .ImplementsNode() .IdField(t => t.Id) .ResolveNodeWith<BarResolver>(t => t.GetBarAsync(null!))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ nodes(ids: [\"QmFyOjEyMw==\", \"QmFyOjEyMw==\"]) { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Parent_Id() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType( x => x.Name("Query") .Field("childs") .Resolve(new Child { Id = "123" })) .AddObjectType<Child>(d => d .ImplementsNode() .IdField(t => t.Id) .ResolveNode((_, id) => Task.FromResult<Child?>(new Child { Id = id }))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync("{ childs { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Separated_Resolver_ImplicitId() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo>() .AddObjectType<Bar>(d => d .ImplementsNode() .ResolveNodeWith<BarResolver>(t => t.GetBarAsync(null!))) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo1>() .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Bar5>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_Named_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo2>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_Inherited_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo6>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_External_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo3>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_ExternalInheritedStatic_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo7>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_ExternalInheritedInstance_Resolver() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo8>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_ExternalDefinedOnInterface_Resolver() { // arrange var executor = await new ServiceCollection() .AddSingleton<IBar9Resolver, Bar9Resolver>() .AddGraphQL() .AddGlobalObjectIdentification() .AddQueryType<Foo9>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); } [Fact] public async Task Node_Resolve_Implicit_Custom_IdField() { // arrange var executor = await new ServiceCollection() .AddGraphQLServer() .AddGlobalObjectIdentification() .AddQueryType<Foo4>() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync( "{ node(id: \"QmFyOjEyMw==\") { id } }"); // assert result.MatchSnapshot(); }
NodeFieldSupportTests
csharp
louthy__language-ext
LanguageExt.Core/Immutable Collections/TrieSet/TrieSet.cs
{ "start": 17691, "end": 28351 }
internal class ____ : Node { public readonly uint EntryMap; public readonly uint NodeMap; public readonly K[] Items; public readonly Node[] Nodes; public Tag Type => Tag.Entries; public Entries(uint entryMap, uint nodeMap, K[] items, Node[] nodes) { EntryMap = entryMap; NodeMap = nodeMap; Items = items; Nodes = nodes; } public void Deconstruct(out uint entryMap, out uint nodeMap, out K[] items, out Node[] nodes) { entryMap = EntryMap; nodeMap = NodeMap; items = Items; nodes = Nodes; } public (int CountDelta, Node Node) Remove(K key, uint hash, Sec section) { var hashIndex = Bit.Get(hash, section); var mask = Mask(hashIndex); if (Bit.Get(EntryMap, mask)) { // If key belongs to an entry var ind = Index(EntryMap, mask); if (EqK.Equals(Items[ind], key)) { return (-1, new Entries( Bit.Set(EntryMap, mask, false), NodeMap, RemoveAt(Items, ind), Nodes)); } else { return (0, this); } } else if (Bit.Get(NodeMap, mask)) { //If key lies in a sub-node var ind = Index(NodeMap, mask); var (cd, subNode) = Nodes[ind].Remove(key, hash, section.Next()); if (cd == 0) return (0, this); switch (subNode.Type) { case Tag.Entries: var subEntries = (Entries)subNode; if (subEntries.Items.Length == 1 && subEntries.Nodes.Length == 0) { // If the node only has one subnode, make that subnode the new node if (Items.Length == 0 && Nodes.Length == 1) { // Build a new Entries for this level with the sublevel mask fixed return (cd, new Entries( Mask(Bit.Get((uint)EqK.GetHashCode(subEntries.Items[0]), section)), 0, Clone(subEntries.Items), System.Array.Empty<Node>() )); } else { return (cd, new Entries( Bit.Set(EntryMap, mask, true), Bit.Set(NodeMap, mask, false), Insert(Items, Index(EntryMap, mask), subEntries.Items[0]), RemoveAt(Nodes, ind))); } } else { var nodeCopy = Clone(Nodes); nodeCopy[ind] = subNode; return (cd, new Entries(EntryMap, NodeMap, Items, nodeCopy)); } case Tag.Collision: var nodeCopy2 = Clone(Nodes); nodeCopy2[ind] = subNode; return (cd, new Entries(EntryMap, NodeMap, Items, nodeCopy2)); default: return (cd, this); } } else { return (0, this); } } public (bool Found, K Key) Read(K key, uint hash, Sec section) { // var hashIndex = Bit.Get(hash, section); // Mask(hashIndex) var mask = (uint)(1 << (int)((hash & (uint)(Sec.Mask << section.Offset)) >> section.Offset)); // if(Bit.Get(EntryMap, mask)) if ((EntryMap & mask) == mask) { // var entryIndex = Index(EntryMap, mask); var entryIndex = BitCount((int)EntryMap & (((int)mask) - 1)); if (EqK.Equals(Items[entryIndex], key)) { var item = Items[entryIndex]; return (true, item); } else { return default; } } // else if (Bit.Get(NodeMap, mask)) else if ((NodeMap & mask) == mask) { // var entryIndex = Index(NodeMap, mask); var entryIndex = BitCount((int)NodeMap & (((int)mask) - 1)); return Nodes[entryIndex].Read(key, hash, section.Next()); } else { return default; } } public (int CountDelta, Node Node) Update((UpdateType Type, bool Mutate) env, K change, uint hash, Sec section) { // var hashIndex = Bit.Get(hash, section); // var mask = Mask(hashIndex); var mask = (uint)(1 << (int)((hash & (uint)(Sec.Mask << section.Offset)) >> section.Offset)); //if (Bit.Get(EntryMap, mask)) if((EntryMap & mask) == mask) { //var entryIndex = Index(EntryMap, mask); var entryIndex = BitCount((int)EntryMap & (((int)mask) - 1)); var currentEntry = Items[entryIndex]; if (EqK.Equals(currentEntry, change)) { if (env.Type == UpdateType.Add) { // Key already exists - so it's an error to add again throw new ArgumentException($"Key already exists in map: {change}"); } else if (env.Type == UpdateType.TryAdd) { // Already added, so we don't continue to try return (0, this); } var newItems = SetItem(Items, entryIndex, change, env.Mutate); return (0, new Entries(EntryMap, NodeMap, newItems, Nodes)); } else { if (env.Type == UpdateType.SetItem) { // Key must already exist to set it throw new ArgumentException($"Key already exists in map: {change}"); } else if (env.Type == UpdateType.TrySetItem) { // Key doesn't exist, so there's nothing to set return (0, this); } // Add var node = Merge(change, currentEntry, hash, (uint)EqK.GetHashCode(currentEntry), section); //var newItems = Items.Filter(elem => !EqK.Equals(elem.Key, currentEntry.Key)).ToArray(); var newItems = new K[Items.Length - 1]; var i = 0; foreach(var elem in Items) { if(!EqK.Equals(elem, currentEntry)) { newItems[i] = elem; i++; } } //var newEntryMap = Bit.Set(EntryMap, mask, false); var newEntryMap = EntryMap & (~mask); // var newNodeMap = Bit.Set(NodeMap, mask, true); var newNodeMap = NodeMap | mask; // var nodeIndex = Index(NodeMap, mask); var nodeIndex = BitCount((int)NodeMap & (((int)mask) - 1)); var newNodes = Insert(Nodes, nodeIndex, node); return (1, new Entries( newEntryMap, newNodeMap, newItems, newNodes)); } } else if (Bit.Get(NodeMap, mask)) { // var nodeIndex = Index(NodeMap, mask); var nodeIndex = BitCount((int)NodeMap & (((int)mask) - 1)); var nodeToUpdate = Nodes[nodeIndex]; var (cd, newNode) = nodeToUpdate.Update(env, change, hash, section.Next()); var newNodes = SetItem(Nodes, nodeIndex, newNode, env.Mutate); return (cd, new Entries(EntryMap, NodeMap, Items, newNodes)); } else { if (env.Type == UpdateType.SetItem) { // Key must already exist to set it throw new ArgumentException($"Key doesn't exist in map: {change}"); } else if (env.Type == UpdateType.TrySetItem) { // Key doesn't exist, so there's nothing to set return (0, this); } // var entryIndex = Index(EntryMap, mask); var entryIndex = BitCount((int)EntryMap & (((int)mask) - 1)); // var entries = Bit.Set(EntryMap, mask, true); var entries = EntryMap | mask; var newItems = Insert(Items, entryIndex, change); return (1, new Entries(entries, NodeMap, newItems, Nodes)); } } public IEnumerator<K> GetEnumerator() { foreach (var item in Items) { yield return item; } foreach (var node in Nodes) { foreach (var item in node) { yield return item; } } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// Contains items that share the same hash but have different keys /// </summary>
Entries
csharp
atata-framework__atata
src/Atata/WebDriver/Screenshots/ScreenshotKind.cs
{ "start": 86, "end": 403 }
public enum ____ { /// <summary> /// The default, which is defined in configuration. /// </summary> Default, /// <summary> /// A screenshot of the viewport. /// </summary> Viewport, /// <summary> /// A screenshot of the full page. /// </summary> FullPage }
ScreenshotKind
csharp
microsoft__semantic-kernel
dotnet/src/Agents/OpenAI/OpenAIAssistantAgentThread.cs
{ "start": 487, "end": 3072 }
public sealed class ____ : AgentThread { private readonly bool _useThreadConstructorExtension = false; private readonly AssistantClient _client; private readonly ThreadCreationOptions? _options; private readonly IEnumerable<ChatMessageContent>? _messages; private readonly IReadOnlyList<string>? _codeInterpreterFileIds; private readonly string? _vectorStoreId; private readonly IReadOnlyDictionary<string, string>? _metadata; /// <summary> /// Initializes a new instance of the <see cref="OpenAIAssistantAgentThread"/> class. /// </summary> /// <param name="client">The assistant client to use for interacting with threads.</param> public OpenAIAssistantAgentThread(AssistantClient client) { Verify.NotNull(client); this._client = client; } /// <summary> /// Initializes a new instance of the <see cref="OpenAIAssistantAgentThread"/> class. /// </summary> /// <param name="client">The assistant client to use for interacting with threads.</param> /// <param name="options">The options to use when creating the thread.</param> public OpenAIAssistantAgentThread(AssistantClient client, ThreadCreationOptions options) { Verify.NotNull(client); this._client = client; this._options = options; } /// <summary> /// Initializes a new instance of the <see cref="OpenAIAssistantAgentThread"/> class. /// </summary> /// <param name="client">The assistant client to use for interacting with threads.</param> /// <param name="messages">The initial messages for the thread.</param> /// <param name="codeInterpreterFileIds">The file IDs for the code interpreter tool.</param> /// <param name="vectorStoreId">The vector store identifier.</param> /// <param name="metadata">The metadata for the thread.</param> public OpenAIAssistantAgentThread( AssistantClient client, IEnumerable<ChatMessageContent>? messages = null, IReadOnlyList<string>? codeInterpreterFileIds = null, string? vectorStoreId = null, IReadOnlyDictionary<string, string>? metadata = null) { Verify.NotNull(client); this._useThreadConstructorExtension = true; this._client = client; this._messages = messages; this._codeInterpreterFileIds = codeInterpreterFileIds; this._vectorStoreId = vectorStoreId; this._metadata = metadata; } /// <summary> /// Initializes a new instance of the <see cref="OpenAIAssistantAgentThread"/>
OpenAIAssistantAgentThread
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridColumnHeaderAutomationPeer.cs
{ "start": 612, "end": 7012 }
public class ____ : FrameworkElementAutomationPeer, IInvokeProvider, IScrollItemProvider, ITransformProvider { /// <summary> /// Initializes a new instance of the <see cref="DataGridColumnHeaderAutomationPeer"/> class. /// </summary> /// <param name="owner">DataGridColumnHeader</param> public DataGridColumnHeaderAutomationPeer(DataGridColumnHeader owner) : base(owner) { } private DataGridColumnHeader OwningHeader { get { return Owner as DataGridColumnHeader; } } /// <summary> /// Gets the control type for the element that is associated with the UI Automation peer. /// </summary> /// <returns>The control type.</returns> protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.HeaderItem; } /// <summary> /// Called by GetClassName that gets a human readable name that, in addition to AutomationControlType, /// differentiates the control represented by this AutomationPeer. /// </summary> /// <returns>The string that contains the name.</returns> protected override string GetClassNameCore() { string classNameCore = Owner.GetType().Name; #if DEBUG_AUTOMATION System.Diagnostics.Debug.WriteLine("DataGridColumnHeaderAutomationPeer.GetClassNameCore returns " + classNameCore); #endif return classNameCore; } /// <summary> /// Gets the string that describes the functionality of the control that is associated with the automation peer. /// </summary> /// <returns>The string that contains the help text.</returns> protected override string GetHelpTextCore() { if (this.OwningHeader.OwningColumn != null && this.OwningHeader.OwningColumn.SortDirection.HasValue) { if (this.OwningHeader.OwningColumn.SortDirection.Value == DataGridSortDirection.Ascending) { return "Ascending"; } return "Descending"; } return base.GetHelpTextCore(); } /// <summary> /// Gets the name of the element. /// </summary> /// <returns>The string that contains the name.</returns> protected override string GetNameCore() { string header = this.OwningHeader.Content as string; if (header != null) { return header; } return base.GetNameCore(); } /// <summary> /// Gets the control pattern that is associated with the specified Windows.UI.Xaml.Automation.Peers.PatternInterface. /// </summary> /// <param name="patternInterface">A value from the Windows.UI.Xaml.Automation.Peers.PatternInterface enumeration.</param> /// <returns>The object that supports the specified pattern, or null if unsupported.</returns> protected override object GetPatternCore(PatternInterface patternInterface) { if (this.OwningHeader.OwningGrid != null) { switch (patternInterface) { case PatternInterface.Invoke: // this.OwningHeader.OwningGrid.DataConnection.AllowSort property is ignored because of the DataGrid.Sorting custom sorting capability. if (this.OwningHeader.OwningGrid.CanUserSortColumns && this.OwningHeader.OwningColumn.CanUserSort) { return this; } break; case PatternInterface.ScrollItem: if (this.OwningHeader.OwningGrid.HorizontalScrollBar != null && this.OwningHeader.OwningGrid.HorizontalScrollBar.Maximum > 0) { return this; } break; case PatternInterface.Transform: if (this.OwningHeader.OwningColumn != null && this.OwningHeader.OwningColumn.ActualCanUserResize) { return this; } break; } } return base.GetPatternCore(patternInterface); } /// <summary> /// Gets a value that specifies whether the element is a content element. /// </summary> /// <returns>True if the element is a content element; otherwise false</returns> protected override bool IsContentElementCore() { return false; } void IInvokeProvider.Invoke() { this.OwningHeader.InvokeProcessSort(); } void IScrollItemProvider.ScrollIntoView() { this.OwningHeader.OwningGrid.ScrollIntoView(null, this.OwningHeader.OwningColumn); } bool ITransformProvider.CanMove { get { return false; } } bool ITransformProvider.CanResize { get { return this.OwningHeader.OwningColumn != null && this.OwningHeader.OwningColumn.ActualCanUserResize; } } bool ITransformProvider.CanRotate { get { return false; } } void ITransformProvider.Move(double x, double y) { throw DataGridError.DataGridAutomationPeer.OperationCannotBePerformed(); } void ITransformProvider.Resize(double width, double height) { if (this.OwningHeader.OwningColumn != null && this.OwningHeader.OwningColumn.ActualCanUserResize) { this.OwningHeader.OwningColumn.Width = new DataGridLength(width); } } void ITransformProvider.Rotate(double degrees) { throw DataGridError.DataGridAutomationPeer.OperationCannotBePerformed(); } } }
DataGridColumnHeaderAutomationPeer
csharp
dotnet__aspire
tests/Aspire.Hosting.Tests/PublishAsDockerfileTests.cs
{ "start": 17362, "end": 17853 }
private sealed class ____ : IProjectMetadata { public string ProjectPath => "/foo/another-path"; public LaunchSettings? LaunchSettings => new() { Profiles = new() { ["https"] = new LaunchProfile { ApplicationUrl = "http://localhost:5031;https://localhost:5033", CommandName = "Project" } } }; } }
TestProjectWithHttpAndHttpsProfile
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Meetings/Application/MeetingGroups/GetMeetingGroupDetails/GetMeetingGroupDetailsQuery.cs
{ "start": 176, "end": 440 }
public class ____ : QueryBase<MeetingGroupDetailsDto> { public GetMeetingGroupDetailsQuery(Guid meetingGroupId) { MeetingGroupId = meetingGroupId; } public Guid MeetingGroupId { get; } } }
GetMeetingGroupDetailsQuery
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/General/BenchmarkClassAnalyzerTests.cs
{ "start": 6897, "end": 7986 }
public abstract class ____<{{string.Join(", ", TypeParameters.Take(typeParametersListLength))}}> { {{benchmarkAttributeUsage}} public void BenchmarkMethod() { } } """; TestCode = testCode; AddSource(benchmarkBaseClassDocument); for (var i = 0; i < genericTypeArgumentsAttributeUsageCount; i++) { AddExpectedDiagnostic(i); } await RunAsync(); } public static IEnumerable<int> TypeParametersListLengthEnumerableLocal => TypeParametersListLengthEnumerable; private static ReadOnlyCollection<string> TypeParameters => TypeParametersTheoryData; private static IReadOnlyCollection<string> GenericTypeArguments => GenericTypeArgumentsTheoryData; public static IEnumerable<string> BenchmarkAttributeUsagesEnumerableLocal => BenchmarkAttributeUsagesEnumerable; }
BenchmarkClassBase
csharp
dotnet__aspnetcore
src/Mvc/Mvc.RazorPages/test/ApplicationModels/DefaultPageApplicationModelProviderTest.cs
{ "start": 37402, "end": 37727 }
private class ____ : Page { public ModelWithoutHandler Model { get; } public override Task ExecuteAsync() => throw new NotImplementedException(); public void OnGet() { } public void OnPostAsync() { } public void OnPostDeleteCustomerAsync() { }
PageWithModelWithoutHandlers
csharp
duplicati__duplicati
Duplicati/Library/Main/Operation/Common/IndexVolumeCreator.cs
{ "start": 1414, "end": 1518 }
class ____ simply rely on the database to create the index files /// <summary> /// A collection
and
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/Conventions/AttributeConventionPack.cs
{ "start": 865, "end": 1959 }
public class ____ : IConventionPack { // private static fields private static readonly AttributeConventionPack __attributeConventionPack = new AttributeConventionPack(); // private fields private readonly AttributeConvention _attributeConvention; // constructors /// <summary> /// Initializes a new instance of the <see cref="AttributeConventionPack" /> class. /// </summary> private AttributeConventionPack() { _attributeConvention = new AttributeConvention(); } // public static properties /// <summary> /// Gets the instance. /// </summary> public static IConventionPack Instance { get { return __attributeConventionPack; } } // public properties /// <summary> /// Gets the conventions. /// </summary> public IEnumerable<IConvention> Conventions { get { yield return _attributeConvention; } } // nested classes
AttributeConventionPack
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.Tests/Generation/JsonPropertyAttributeTests.cs
{ "start": 151, "end": 2538 }
public class ____ { [Fact] public async Task When_name_of_JsonPropertyAttribute_is_set_then_it_is_used_as_json_property_name() { // Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType<MyJsonPropertyTestClass>(); // Act var property = schema.Properties["NewName"]; // Assert Assert.Equal("NewName", property.Name); } [Fact] public async Task When_name_of_JsonPropertyAttribute_is_set_then_it_is_used_as_json_property_name_even_with_contactresolver_that_has_nameing_strategy() { var settings = new NewtonsoftJsonSchemaGeneratorSettings { SerializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } } }; // Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType<MyJsonPropertyTestClass>(settings); // Act var property = schema.Properties["NewName"]; // Assert Assert.Equal("NewName", property.Name); } [Fact] public async Task Use_JsonSchemaGeneratorSettings_ContractResolver_For_JsonPropertyName() { var settings = new NewtonsoftJsonSchemaGeneratorSettings { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; // Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType<MyJsonPropertyTestClass>(settings); // Act var property = schema.Properties["newName"]; // Assert Assert.Equal("newName", property.Name); } [Fact] public async Task When_required_is_always_in_JsonPropertyAttribute_then_the_property_is_required() { // Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType<MyJsonPropertyTestClass>(); // Act var property = schema.Properties["Required"]; // Assert Assert.True(property.IsRequired); }
JsonPropertyAttributeTests
csharp
abpframework__abp
modules/openiddict/src/Volo.Abp.OpenIddict.Domain.Shared/Volo/Abp/OpenIddict/Tokens/OpenIddictTokenConsts.cs
{ "start": 40, "end": 321 }
public class ____ { public static int ReferenceIdMaxLength { get; set; } = 100; public static int StatusMaxLength { get; set; } = 50; public static int SubjectMaxLength { get; set; } = 400; public static int TypeMaxLength { get; set; } = 150; }
OpenIddictTokenConsts
csharp
graphql-dotnet__graphql-dotnet
samples/GraphQL.Harness.Tests/SuccessResultAssertion.cs
{ "start": 110, "end": 1641 }
public class ____ : GraphQLAssertion { private static readonly string extensionsKey = nameof(ExecutionResult.Extensions).ToLower(); private readonly string _result; private readonly bool _ignoreExtensions; private readonly IGraphQLTextSerializer _writer = new GraphQLSerializer(); public SuccessResultAssertion(string result, bool ignoreExtensions) { _result = result; _ignoreExtensions = ignoreExtensions; } public override void Assert(Scenario scenario, HttpContext context, ScenarioAssertionException ex) { var expectedResult = CreateQueryResult(_result); // for Alba v4 // string actualResultJson = ex.ReadBody(context); // for Alba v6 [ScenarioAssertionException.ReadBody internal] context.Request.Body.Position = 0; string actualResultJson = new StreamReader(context.Response.Body).ReadToEnd(); if (_ignoreExtensions) { expectedResult.Extensions = null; var actualResult = actualResultJson.ToDictionary(); if (actualResult.ContainsKey(extensionsKey)) { actualResult.Remove(extensionsKey); } actualResultJson = _writer.Serialize(actualResult); } string expectedResultJson = _writer.Serialize(expectedResult); if (!actualResultJson.Equals(expectedResultJson)) { ex.Add($"Expected '{expectedResultJson}' but got '{actualResultJson}'"); } } }
SuccessResultAssertion
csharp
dotnet__orleans
test/Extensions/Consul.Tests/LivenessTests.cs
{ "start": 825, "end": 1243 }
public class ____ : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder.UseConsulSiloClustering(options => { var address = new Uri(ConsulTestUtils.ConsulConnectionString); options.ConfigureConsulClient(address); }); } }
SiloBuilderConfigurator
csharp
AutoFixture__AutoFixture
Src/AutoFakeItEasyUnitTest/TestTypes/IInterfaceWithOutMethod.cs
{ "start": 63, "end": 150 }
public interface ____ { void Method(out int i); } }
IInterfaceWithOutMethod
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Build/Jenkins/Data/JenkinsRepositoryInfoTests.cs
{ "start": 378, "end": 800 }
public sealed class ____ { [Fact] public void Should_Return_Correct_Value() { // Given var info = new JenkinsInfoFixture().CreateRepositoryInfo(); // When var result = info.BranchName; // Then Assert.Equal("CAKE-BRANCH", result); } }
TheBranchNameProperty
csharp
dotnet__orleans
src/Orleans.TestingHost/UnixSocketTransport/UnixSocketConnectionOptions.cs
{ "start": 195, "end": 912 }
public partial class ____ { /// <summary> /// Get or sets to function used to get a filename given an endpoint /// </summary> public Func<EndPoint, string> ConvertEndpointToPath { get; set; } = DefaultConvertEndpointToPath; /// <summary> /// Gets or sets the memory pool factory. /// </summary> internal Func<MemoryPool<byte>> MemoryPoolFactory { get; set; } = () => KestrelMemoryPool.Create(); [GeneratedRegex("[^a-zA-Z0-9]")] private static partial Regex ConvertEndpointRegex(); private static string DefaultConvertEndpointToPath(EndPoint endPoint) => Path.Combine(Path.GetTempPath(), ConvertEndpointRegex().Replace(endPoint.ToString(), "_")); }
UnixSocketConnectionOptions
csharp
dotnet__maui
src/Controls/tests/Xaml.UnitTests/Issues/Maui25309.xaml.cs
{ "start": 394, "end": 1044 }
class ____ { [SetUp] public void Setup() { Application.SetCurrentApplication(new MockApplication()); DispatcherProvider.SetCurrent(new DispatcherProviderStub()); } [TearDown] public void TearDown() => AppInfo.SetCurrent(null); [Test] public void GenericConvertersDoesNotThrowNRE([Values] XamlInflator inflator) { var page = new Maui25309(inflator) { BindingContext = new { IsValid = true } }; var converter = page.Resources["IsValidConverter"] as Maui25309BoolToObjectConverter; Assert.IsNotNull(converter); Assert.That(page.label.BackgroundColor, Is.EqualTo(Color.Parse("#140F4B"))); } } } #nullable enable
Test
csharp
jellyfin__jellyfin
src/Jellyfin.Extensions/GuidExtensions.cs
{ "start": 145, "end": 796 }
public static class ____ { /// <summary> /// Determine whether the guid is default. /// </summary> /// <param name="guid">The guid.</param> /// <returns>Whether the guid is the default value.</returns> public static bool IsEmpty(this Guid guid) => guid.Equals(default); /// <summary> /// Determine whether the guid is null or default. /// </summary> /// <param name="guid">The guid.</param> /// <returns>Whether the guid is null or the default valueF.</returns> public static bool IsNullOrEmpty([NotNullWhen(false)] this Guid? guid) => guid is null || guid.Value.IsEmpty(); }
GuidExtensions
csharp
dotnet__efcore
test/EFCore.Tests/Metadata/Internal/PropertyTest.cs
{ "start": 13843, "end": 13919 }
private abstract class ____ : StringToBoolConverter;
AbstractValueConverter
csharp
PrismLibrary__Prism
src/Prism.Core/Navigation/Regions/ViewRegistrationException.cs
{ "start": 298, "end": 1768 }
public partial class ____ : Exception { // TODO: Find updated links as these are dead... // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // /// <summary> /// Initializes a new instance of the <see cref="ViewRegistrationException"/> class. /// </summary> public ViewRegistrationException() { } /// <summary> /// Initializes a new instance of the <see cref="ViewRegistrationException"/> class. /// </summary> /// <param name="message">The exception message.</param> public ViewRegistrationException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ViewRegistrationException"/> class. /// </summary> /// <param name="message">The exception message.</param> /// <param name="inner">The inner exception.</param> public ViewRegistrationException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="ViewRegistrationException"/>
ViewRegistrationException
csharp
JoshClose__CsvHelper
src/CsvHelper/Expressions/ObjectRecordCreator.cs
{ "start": 436, "end": 781 }
public class ____ : RecordCreator { /// <summary> /// Initializes a new instance using the given reader. /// </summary> /// <param name="reader"></param> public ObjectRecordCreator(CsvReader reader) : base(reader) { } /// <summary> /// Creates a <see cref="Delegate"/> of type <see cref="Func{T}"/> /// that will create a
ObjectRecordCreator
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs
{ "start": 84743, "end": 84847 }
private class ____ { public virtual LogbookCode Logbook { get; set; } }
LogbookRelation
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.Notifications/Toasts/Compat/Desktop/Native/SIZE.cs
{ "start": 348, "end": 543 }
internal struct ____ { internal int X; internal int Y; internal SIZE(int x, int y) { this.X = x; this.Y = y; } } } #endif
SIZE
csharp
dotnet__aspnetcore
src/Identity/EntityFrameworkCore/test/EF.Test/DbUtil.cs
{ "start": 441, "end": 3612 }
public static class ____ { public static IServiceCollection ConfigureDbServices<TContext>( DbConnection connection, IServiceCollection services = null) where TContext : DbContext { if (services == null) { services = new ServiceCollection(); } services.AddHttpContextAccessor(); services.AddDbContext<TContext>(options => { options .ConfigureWarnings(b => b.Log(CoreEventId.ManyServiceProvidersCreatedWarning)) .UseSqlite(connection); }); services.Configure<IdentityOptions>(options => { options.Stores.SchemaVersion = IdentitySchemaVersions.Version3; }); return services; } public static TContext Create<TContext>(DbConnection connection, IServiceCollection services = null) where TContext : DbContext { var serviceProvider = ConfigureDbServices<TContext>(connection, services).BuildServiceProvider(); return serviceProvider.GetRequiredService<TContext>(); } public static bool VerifyMaxLength(DbContext context, string table, int maxLength, params string[] columns) { var count = 0; foreach (var property in context.Model.GetEntityTypes().Single(e => e.GetTableName() == table).GetProperties()) { if (!columns.Contains(property.GetColumnName(StoreObjectIdentifier.Table(table, property.DeclaringType.GetSchema())))) { continue; } if (property.GetMaxLength() != maxLength) { return false; } count++; } return count == columns.Length; } public static bool VerifyColumns(SqliteConnection conn, string table, params string[] columns) { var count = 0; using (var command = new SqliteCommand("SELECT \"name\" FROM pragma_table_info(@table)", conn)) { command.Parameters.Add(new SqliteParameter("table", table)); using (var reader = command.ExecuteReader()) { while (reader.Read()) { count++; if (!columns.Contains(reader.GetString(0))) { return false; } } return count == columns.Length; } } } public static void VerifyIndex(SqliteConnection conn, string table, string index, bool isUnique = false) { using (var command = new SqliteCommand( "SELECT COUNT(*) FROM pragma_index_list(@table) WHERE \"name\" = @index AND \"unique\" = @unique", conn)) { command.Parameters.Add(new SqliteParameter("index", index)); command.Parameters.Add(new SqliteParameter("table", table)); command.Parameters.Add(new SqliteParameter("unique", isUnique)); using (var reader = command.ExecuteReader()) { Assert.True(reader.Read()); Assert.True(reader.GetInt32(0) > 0); } } } }
DbUtil
csharp
dotnet__maui
src/Controls/tests/Core.UnitTests/FlyoutPageUnitTests.cs
{ "start": 23213, "end": 24059 }
public class ____ : ContentPage { public NavigatedFromEventArgs NavigatedFromArgs { get; private set; } public NavigatingFromEventArgs NavigatingFromArgs { get; private set; } public NavigatedToEventArgs NavigatedToArgs { get; private set; } public void ClearNavigationArgs() { NavigatedFromArgs = null; NavigatingFromArgs = null; NavigatedToArgs = null; } protected override void OnNavigatedFrom(NavigatedFromEventArgs args) { base.OnNavigatedFrom(args); NavigatedFromArgs = args; } protected override void OnNavigatingFrom(NavigatingFromEventArgs args) { base.OnNavigatingFrom(args); NavigatingFromArgs = args; } protected override void OnNavigatedTo(NavigatedToEventArgs args) { base.OnNavigatedTo(args); NavigatedToArgs = args; } }
NavigationObserverPage
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Issues/Issue1834.cs
{ "start": 1760, "end": 2369 }
public class ____ : TestFixtureBase { [Test] public void Test() { string json = "{'foo':'test!'}"; ItemWithJsonConstructor c = JsonConvert.DeserializeObject<ItemWithJsonConstructor>(json); Assert.IsNull(c.ExtensionData); } [Test] public void Test_UnsetRequired() { string json = "{'foo':'test!'}"; ItemWithJsonConstructorAndDefaultValue c = JsonConvert.DeserializeObject<ItemWithJsonConstructorAndDefaultValue>(json); Assert.IsNull(c.ExtensionData); }
Issue1834
csharp
microsoft__garnet
libs/server/Resp/Objects/SharedObjectCommands.cs
{ "start": 151, "end": 3911 }
partial class ____ : ServerSessionBase { /// <summary> /// Iterates over the associated items of a key, /// using a pattern to match and count to limit how many items to return. /// </summary> /// <typeparam name="TGarnetApi"></typeparam> /// <param name="objectType">SortedSet, Hash or Set type</param> /// <param name="storageApi">The storageAPI object</param> /// <returns></returns> private unsafe bool ObjectScan<TGarnetApi>(GarnetObjectType objectType, ref TGarnetApi storageApi) where TGarnetApi : IGarnetApi { // Check number of required parameters if (parseState.Count < 2) { var cmdName = objectType switch { GarnetObjectType.Hash => nameof(HashOperation.HSCAN), GarnetObjectType.Set => nameof(SetOperation.SSCAN), GarnetObjectType.SortedSet => nameof(SortedSetOperation.ZSCAN), GarnetObjectType.All => nameof(RespCommand.COSCAN), _ => nameof(RespCommand.NONE) }; return AbortWithWrongNumberOfArguments(cmdName); } // Read key for the scan var sbKey = parseState.GetArgSliceByRef(0).SpanByte; var keyBytes = sbKey.ToByteArray(); // Get cursor value if (!parseState.TryGetLong(1, out var cursorValue) || cursorValue < 0) { return AbortWithErrorMessage(CmdStrings.RESP_ERR_GENERIC_INVALIDCURSOR); } var header = new RespInputHeader(objectType); var input = new ObjectInput(header, ref parseState, startIdx: 1, arg2: storeWrapper.serverOptions.ObjectScanCountLimit); switch (objectType) { case GarnetObjectType.Hash: input.header.HashOp = HashOperation.HSCAN; break; case GarnetObjectType.Set: input.header.SetOp = SetOperation.SSCAN; break; case GarnetObjectType.SortedSet: input.header.SortedSetOp = SortedSetOperation.ZSCAN; break; case GarnetObjectType.All: input.header.cmd = RespCommand.COSCAN; break; } // Prepare GarnetObjectStore output var output = new GarnetObjectStoreOutput(new(dcurr, (int)(dend - dcurr))); var status = storageApi.ObjectScan(keyBytes, ref input, ref output); switch (status) { case GarnetStatus.OK: // Process output ProcessOutput(output.SpanByteAndMemory); // Validation for partial input reading or error if (output.Header.result1 == int.MinValue) return false; break; case GarnetStatus.NOTFOUND: while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); while (!RespWriteUtils.TryWriteInt32AsBulkString(0, ref dcurr, dend)) SendAndReset(); while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } return true; } } }
RespServerSession
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 94763, "end": 94980 }
public class ____ { public int Id { get; set; } public RelatedEntity437 ParentEntity { get; set; } public IEnumerable<RelatedEntity439> ChildEntities { get; set; } }
RelatedEntity438
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/Contents/CitationAnnotationTests.cs
{ "start": 261, "end": 3503 }
public class ____ { [Fact] public void Constructor_PropsDefault() { CitationAnnotation a = new(); Assert.Null(a.AdditionalProperties); Assert.Null(a.AnnotatedRegions); Assert.Null(a.RawRepresentation); Assert.Null(a.Snippet); Assert.Null(a.Title); Assert.Null(a.ToolName); Assert.Null(a.Url); } [Fact] public void Constructor_PropsRoundtrip() { CitationAnnotation a = new(); Assert.Null(a.AdditionalProperties); AdditionalPropertiesDictionary props = new() { { "key", "value" } }; a.AdditionalProperties = props; Assert.Same(props, a.AdditionalProperties); Assert.Null(a.RawRepresentation); object raw = new(); a.RawRepresentation = raw; Assert.Same(raw, a.RawRepresentation); Assert.Null(a.AnnotatedRegions); List<AnnotatedRegion> regions = [new TextSpanAnnotatedRegion { StartIndex = 10, EndIndex = 42 }]; a.AnnotatedRegions = regions; Assert.Same(regions, a.AnnotatedRegions); Assert.Null(a.Snippet); a.Snippet = "snippet"; Assert.Equal("snippet", a.Snippet); Assert.Null(a.Title); a.Title = "title"; Assert.Equal("title", a.Title); Assert.Null(a.ToolName); a.ToolName = "toolName"; Assert.Equal("toolName", a.ToolName); Assert.Null(a.Url); Uri url = new("https://example.com"); a.Url = url; Assert.Same(url, a.Url); } [Fact] public void Serialization_Roundtrips() { CitationAnnotation original = new() { AdditionalProperties = new AdditionalPropertiesDictionary { { "key", "value" } }, RawRepresentation = new object(), Snippet = "snippet", Title = "title", ToolName = "toolName", Url = new("https://example.com"), AnnotatedRegions = [new TextSpanAnnotatedRegion { StartIndex = 10, EndIndex = 42 }], }; string json = JsonSerializer.Serialize(original, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(CitationAnnotation))); Assert.NotNull(json); var deserialized = (CitationAnnotation?)JsonSerializer.Deserialize(json, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(CitationAnnotation))); Assert.NotNull(deserialized); Assert.NotNull(deserialized.AdditionalProperties); Assert.Single(deserialized.AdditionalProperties); Assert.Equal(JsonElement.Parse("\"value\"").ToString(), deserialized.AdditionalProperties["key"]!.ToString()); Assert.Null(deserialized.RawRepresentation); Assert.Equal("snippet", deserialized.Snippet); Assert.Equal("title", deserialized.Title); Assert.Equal("toolName", deserialized.ToolName); Assert.NotNull(deserialized.AnnotatedRegions); TextSpanAnnotatedRegion region = Assert.IsType<TextSpanAnnotatedRegion>(Assert.Single(deserialized.AnnotatedRegions)); Assert.Equal(10, region.StartIndex); Assert.Equal(42, region.EndIndex); Assert.NotNull(deserialized.Url); Assert.Equal(original.Url, deserialized.Url); } }
CitationAnnotationTests
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.Testing/RandomSystem/RandomProviderMock.cs
{ "start": 172, "end": 1221 }
internal sealed class ____ : IRandomProvider { [ThreadStatic] private static RandomMock? _shared; private static Generator<Guid> DefaultGuidGenerator => Generator.FromCallback(Guid.NewGuid); private readonly Generator<Guid> _guidGenerator; private readonly Func<int, IRandom> _randomGenerator; public RandomProviderMock( Func<int, IRandom>? randomGenerator = null, Generator<Guid>? guidGenerator = null) { _guidGenerator = guidGenerator ?? DefaultGuidGenerator; _randomGenerator = randomGenerator ?? DefaultRandomGenerator; } #region IRandomProvider Members /// <inheritdoc cref="IRandomProvider.GetGuid()" /> public Guid GetGuid() => _guidGenerator.GetNext(); /// <inheritdoc cref="IRandomProvider.GetRandom(int)" /> public IRandom GetRandom(int seed = SharedSeed) => _randomGenerator(seed); #endregion private static RandomMock DefaultRandomGenerator(int seed) { if (seed == SharedSeed) { return _shared ??= new RandomMock(seed: SharedSeed); } return new RandomMock(seed: seed); } }
RandomProviderMock
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/ApiExplorerSettingsAttribute.cs
{ "start": 338, "end": 486 }
class ____ action method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
or
csharp
ServiceStack__ServiceStack
ServiceStack.Text/tests/ServiceStack.Text.Tests/SpecialTypesTests.cs
{ "start": 1298, "end": 3351 }
class ____ { public string Name { get; set; } public byte[] Data { get; set; } } [Test] public void Can_Serialize_Type_with_ByteArray_as_Int_Array() { var test = "{\"Name\":\"Test\",\"Data\":[1,2,3,4,5]}".FromJson<PocoWithBytes>(); Assert.That(test.Data, Is.EquivalentTo(new byte[] { 1, 2, 3, 4, 5 })); } [Test] public void Can_Serialize_ByteArray() { var test = new byte[] { 1, 2, 3, 4, 5 }; var json = JsonSerializer.SerializeToString(test); var fromJson = JsonSerializer.DeserializeFromString<byte[]>(json); Assert.That(test, Is.EquivalentTo(fromJson)); } [Test] public void Can_Serialize_HashTable() { var h = new Hashtable { { "A", 1 }, { "B", 2 } }; var fromJson = h.ToJson().FromJson<Hashtable>(); Assert.That(fromJson.Count, Is.EqualTo(h.Count)); Assert.That(fromJson["A"].ToString(), Is.EqualTo(h["A"].ToString())); Assert.That(fromJson["B"].ToString(), Is.EqualTo(h["B"].ToString())); } [Test] public void Can_serialize_delegate() { Action x = () => { }; Assert.That(x.ToJson(), Is.Null); Assert.That(x.ToJsv(), Is.Null); Assert.That(x.Dump(), Is.Not.Null); } string MethodWithArgs(int id, string name) { return null; } [Test] public void Does_dump_delegate_info() { Action d = Can_Serialize_ByteArray; Assert.That(d.Dump(), Is.EqualTo("Void Can_Serialize_ByteArray()")); Func<int, string, string> methodWithArgs = MethodWithArgs; Assert.That(methodWithArgs.Dump(), Is.EqualTo("String MethodWithArgs(Int32 arg1, String arg2)")); Action x = () => { }; Assert.That(x.Dump(), Does.StartWith("Void <Does_dump_delegate_info>")); }
PocoWithBytes
csharp
smartstore__Smartstore
src/Smartstore/Data/Caching/Extensions/CachingQueryExtensions.cs
{ "start": 135, "end": 6527 }
public static class ____ { internal static readonly MethodInfo AsCachingMethodInfo = typeof(CachingQueryExtensions) .GetTypeInfo() .GetMethods() .Where(m => m.Name == nameof(AsCaching)) .Where(m => m.GetParameters().Any(p => p.ParameterType == typeof(DbCachingPolicy))) .Single(); /// <summary> /// <para> /// The second level cache will not cache any entities that are returned from a LINQ query, /// nor will it return any previously cached result. /// </para> /// <para> /// Call this method when you want to suppress a global caching policy that has been assigned to an entity type. /// </para> /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <returns>A new query where the result set will not be cached.</returns> public static IQueryable<T> AsNoCaching<T>(this IQueryable<T> source) where T : BaseEntity { Guard.NotNull(source, nameof(source)); return source.AsCaching<T>(new DbCachingPolicy { NoCaching = true }); } /// <summary> /// Returns a new query where the result will be cached. /// Only untracked entities will be cached. /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <returns>A new query where the result set will be cached.</returns> public static IQueryable<T> AsCaching<T>(this IQueryable<T> source) where T : BaseEntity { Guard.NotNull(source, nameof(source)); return source.AsCaching<T>(new DbCachingPolicy()); } /// <summary> /// Returns a new query where the result will be cached base on the <see cref="duration"/> parameter. /// Only untracked entities will be cached. /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <param name="duration">Limits the lifetime of cached query results.</param> /// <returns>A new query where the result set will be cached.</returns> public static IQueryable<T> AsCaching<T>(this IQueryable<T> source, [NotParameterized] TimeSpan duration) where T : BaseEntity { Guard.NotNull(source, nameof(source)); if (duration < TimeSpan.Zero) { throw new ArgumentException($"Invalid caching timeout {duration}", nameof(duration)); } return source.AsCaching<T>(new DbCachingPolicy { ExpirationTimeout = duration }); } /// <summary> /// Returns a new query where the result will be cached if its item count does not exceed given <paramref name="maxRows"/>. /// Only untracked entities will be cached. /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <param name="maxRows">Query results with more items than the given number will not be cached..</param> /// <returns>A new query where the result set will be cached.</returns> public static IQueryable<T> AsCaching<T>(this IQueryable<T> source, [NotParameterized] int maxRows) where T : BaseEntity { Guard.NotNull(source, nameof(source)); Guard.IsPositive(maxRows, nameof(maxRows)); return source.AsCaching<T>(new DbCachingPolicy { MaxRows = maxRows }); } /// <summary> /// Returns a new query where the result will be cached base on the <see cref="duration"/> parameter. /// Only untracked entities will be cached. /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <param name="duration">Limits the lifetime of cached query results.</param> /// <param name="maxRows">Query results with more items than the given number will not be cached..</param> /// <returns>A new query where the result set will be cached.</returns> public static IQueryable<T> AsCaching<T>(this IQueryable<T> source, [NotParameterized] TimeSpan duration, [NotParameterized] int maxRows) where T : BaseEntity { Guard.NotNull(source, nameof(source)); Guard.IsPositive(maxRows, nameof(maxRows)); if (duration < TimeSpan.Zero) { throw new ArgumentException($"Invalid caching timeout {duration}", nameof(duration)); } return source.AsCaching<T>(new DbCachingPolicy { ExpirationTimeout = duration, MaxRows = maxRows }); } /// <summary> /// Returns a new query where the result will be cached. /// Only untracked entities will be cached. /// </summary> /// <typeparam name="T">The type of entity being queried.</typeparam> /// <param name="source">The source query.</param> /// <param name="options">Options how to handle cached query results.</param> /// <returns>A new query where the result set will be cached.</returns> public static IQueryable<T> AsCaching<T>(this IQueryable<T> source, [NotParameterized] DbCachingPolicy policy) where T : BaseEntity { Guard.NotNull(source, nameof(source)); Guard.NotNull(policy, nameof(policy)); if (source.Provider is not CachingQueryProvider) { // The AsCaching() method expression will result in a LINQ translation error // if ef caching is not active. return source; } return source.Provider.CreateQuery<T>( Expression.Call( instance: null, method: AsCachingMethodInfo.MakeGenericMethod(typeof(T)), arg0: source.Expression, arg1: Expression.Constant(policy))); } } }
CachingQueryExtensions
csharp
dotnet__aspnetcore
src/SignalR/server/StackExchangeRedis/src/Internal/RedisProtocol.cs
{ "start": 440, "end": 10109 }
internal sealed class ____ { private readonly DefaultHubMessageSerializer _messageSerializer; public RedisProtocol(DefaultHubMessageSerializer messageSerializer) { _messageSerializer = messageSerializer; } // The Redis Protocol: // * The message type is known in advance because messages are sent to different channels based on type // * Invocations are sent to the All, Group, Connection and User channels // * Group Commands are sent to the GroupManagement channel // * Acks are sent to the Acknowledgement channel. // * Completion messages (client results) are sent to the server specific Result channel // * See the Write[type] methods for a description of the protocol for each in-depth. // * The "Variable length integer" is the length-prefixing format used by BinaryReader/BinaryWriter: // * https://learn.microsoft.com/dotnet/api/system.io.binarywriter.write?view=netcore-2.2 // * The "Length prefixed string" is the string format used by BinaryReader/BinaryWriter: // * A 7-bit variable length integer encodes the length in bytes, followed by the encoded string in UTF-8. public byte[] WriteInvocation(string methodName, object?[] args, string? invocationId = null, IReadOnlyList<string>? excludedConnectionIds = null, string? returnChannel = null) { // Written as a MessagePack 'arr' containing at least these items: // * A MessagePack 'arr' of 'str's representing the excluded ids // * [The output of WriteSerializedHubMessage, which is an 'arr'] // For invocations expecting a result // * InvocationID // * Redis return channel // Any additional items are discarded. var memoryBufferWriter = MemoryBufferWriter.Get(); try { var writer = new MessagePackWriter(memoryBufferWriter); if (!string.IsNullOrEmpty(returnChannel)) { writer.WriteArrayHeader(4); } else { writer.WriteArrayHeader(2); } if (excludedConnectionIds != null && excludedConnectionIds.Count > 0) { writer.WriteArrayHeader(excludedConnectionIds.Count); foreach (var id in excludedConnectionIds) { writer.Write(id); } } else { writer.WriteArrayHeader(0); } WriteHubMessage(ref writer, new InvocationMessage(invocationId, methodName, args)); // Write last in order to preserve original order for cases where one server is updated and the other isn't. // Not really a supported scenario, but why not be nice if (!string.IsNullOrEmpty(returnChannel)) { writer.Write(invocationId); writer.Write(returnChannel); } writer.Flush(); return memoryBufferWriter.ToArray(); } finally { MemoryBufferWriter.Return(memoryBufferWriter); } } public static byte[] WriteGroupCommand(RedisGroupCommand command) { // Written as a MessagePack 'arr' containing at least these items: // * An 'int': the Id of the command // * A 'str': The server name // * An 'int': The action (likely less than 0x7F and thus a single-byte fixnum) // * A 'str': The group name // * A 'str': The connection Id // Any additional items are discarded. var memoryBufferWriter = MemoryBufferWriter.Get(); try { var writer = new MessagePackWriter(memoryBufferWriter); writer.WriteArrayHeader(5); writer.Write(command.Id); writer.Write(command.ServerName); writer.Write((byte)command.Action); writer.Write(command.GroupName); writer.Write(command.ConnectionId); writer.Flush(); return memoryBufferWriter.ToArray(); } finally { MemoryBufferWriter.Return(memoryBufferWriter); } } public static byte[] WriteAck(int messageId) { // Written as a MessagePack 'arr' containing at least these items: // * An 'int': The Id of the command being acknowledged. // Any additional items are discarded. var memoryBufferWriter = MemoryBufferWriter.Get(); try { var writer = new MessagePackWriter(memoryBufferWriter); writer.WriteArrayHeader(1); writer.Write(messageId); writer.Flush(); return memoryBufferWriter.ToArray(); } finally { MemoryBufferWriter.Return(memoryBufferWriter); } } public static byte[] WriteCompletionMessage(MemoryBufferWriter writer, string protocolName) { // Written as a MessagePack 'arr' containing at least these items: // * A 'str': The name of the HubProtocol used for the serialization of the Completion Message // * [A serialized Completion Message which is a 'bin'] // Any additional items are discarded. var completionMessage = writer.DetachAndReset(); var msgPackWriter = new MessagePackWriter(writer); msgPackWriter.WriteArrayHeader(2); msgPackWriter.Write(protocolName); msgPackWriter.WriteBinHeader(completionMessage.ByteLength); foreach (var segment in completionMessage.Segments) { msgPackWriter.WriteRaw(segment.Span); } completionMessage.Dispose(); msgPackWriter.Flush(); return writer.ToArray(); } public static RedisInvocation ReadInvocation(ReadOnlyMemory<byte> data) { // See WriteInvocation for the format var reader = new MessagePackReader(data); var length = ValidateArraySize(ref reader, 2, "Invocation"); string? returnChannel = null; string? invocationId = null; // Read excluded Ids IReadOnlyList<string>? excludedConnectionIds = null; var idCount = reader.ReadArrayHeader(); if (idCount > 0) { var ids = new string[idCount]; for (var i = 0; i < idCount; i++) { ids[i] = reader.ReadString()!; } excludedConnectionIds = ids; } // Read payload var message = ReadSerializedHubMessage(ref reader); if (length > 3) { invocationId = reader.ReadString(); returnChannel = reader.ReadString(); } return new RedisInvocation(message, excludedConnectionIds, invocationId, returnChannel); } public static RedisGroupCommand ReadGroupCommand(ReadOnlyMemory<byte> data) { var reader = new MessagePackReader(data); // See WriteGroupCommand for format. ValidateArraySize(ref reader, 5, "GroupCommand"); var id = reader.ReadInt32(); var serverName = reader.ReadString()!; var action = (GroupAction)reader.ReadByte(); var groupName = reader.ReadString()!; var connectionId = reader.ReadString()!; return new RedisGroupCommand(id, serverName, action, groupName, connectionId); } public static int ReadAck(ReadOnlyMemory<byte> data) { var reader = new MessagePackReader(data); // See WriteAck for format ValidateArraySize(ref reader, 1, "Ack"); return reader.ReadInt32(); } private void WriteHubMessage(ref MessagePackWriter writer, HubMessage message) { // Written as a MessagePack 'map' where the keys are the name of the protocol (as a MessagePack 'str') // and the values are the serialized blob (as a MessagePack 'bin'). var serializedHubMessages = _messageSerializer.SerializeMessage(message); writer.WriteMapHeader(serializedHubMessages.Count); foreach (var serializedMessage in serializedHubMessages) { writer.Write(serializedMessage.ProtocolName); var isArray = MemoryMarshal.TryGetArray(serializedMessage.Serialized, out var array); Debug.Assert(isArray); writer.Write(array); } } public static SerializedHubMessage ReadSerializedHubMessage(ref MessagePackReader reader) { var count = reader.ReadMapHeader(); var serializations = new SerializedMessage[count]; for (var i = 0; i < count; i++) { var protocol = reader.ReadString()!; var serialized = reader.ReadBytes()?.ToArray() ?? Array.Empty<byte>(); serializations[i] = new SerializedMessage(protocol, serialized); } return new SerializedHubMessage(serializations); } public static RedisCompletion ReadCompletion(ReadOnlyMemory<byte> data) { // See WriteCompletionMessage for the format var reader = new MessagePackReader(data); ValidateArraySize(ref reader, 2, "CompletionMessage"); var protocolName = reader.ReadString()!; var ros = reader.ReadBytes(); return new RedisCompletion(protocolName, ros ?? new ReadOnlySequence<byte>()); } private static int ValidateArraySize(ref MessagePackReader reader, int expectedLength, string messageType) { var length = reader.ReadArrayHeader(); if (length < expectedLength) { throw new InvalidDataException($"Insufficient items in {messageType} array."); } return length; } }
RedisProtocol
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Media/MediaContext.cs
{ "start": 899, "end": 8412 }
private record ____(Compositor Compositor, CompositingRenderer Renderer, ILayoutManager LayoutManager); private List<Action>? _invokeOnRenderCallbacks; private readonly Stack<List<Action>> _invokeOnRenderCallbackListPool = new(); private readonly DispatcherTimer _animationsTimer = new(DispatcherPriority.Render) { // Since this timer is used to drive animations that didn't contribute to the previous frame at all // We can safely use 16ms interval until we fix our animation system to actually report the next expected // frame Interval = TimeSpan.FromMilliseconds(16) }; private readonly Dictionary<object, TopLevelInfo> _topLevels = new(); private MediaContext(Dispatcher dispatcher, TimeSpan inputStarvationTimeout) { _render = Render; _inputMarkerHandler = InputMarkerHandler; _clock = new(this); _dispatcher = dispatcher; MaxSecondsWithoutInput = inputStarvationTimeout.TotalSeconds; _animationsTimer.Tick += (_, _) => { _animationsTimer.Stop(); ScheduleRender(false); }; } public static MediaContext Instance { get { // Technically it's supposed to be a thread-static singleton, but we don't have multiple threads // and need to do a full reset for unit tests var context = AvaloniaLocator.Current.GetService<MediaContext>(); if (context == null) { var opts = AvaloniaLocator.Current.GetService<DispatcherOptions>() ?? new(); context = new MediaContext(Dispatcher.UIThread, opts.InputStarvationTimeout); AvaloniaLocator.CurrentMutable.Bind<MediaContext>().ToConstant(context); } return context; } } /// <summary> /// Schedules the next render operation, handles render throttling for input processing /// </summary> private void ScheduleRender(bool now) { // Already scheduled, nothing to do if (_nextRenderOp != null) { if (now) _nextRenderOp.Priority = DispatcherPriority.Render; return; } // Sometimes our animation, layout and render passes might be taking more than a frame to complete // which can cause a "freeze"-like state when UI is being updated, but input is never being processed // So here we inject an operation with Input priority to check if Input wasn't being processed // for a long time. If that's the case the next rendering operation will be scheduled to happen after all pending input var priority = DispatcherPriority.Render; if (_inputMarkerOp == null) { _inputMarkerOp = _dispatcher.InvokeAsync(_inputMarkerHandler, DispatcherPriority.Input); _inputMarkerAddedAt = _time.Elapsed; } else if (!now && (_time.Elapsed - _inputMarkerAddedAt).TotalSeconds > MaxSecondsWithoutInput) { priority = DispatcherPriority.Input; } var renderOp = new DispatcherOperation(_dispatcher, priority, _render, throwOnUiThread: true); _nextRenderOp = renderOp; _dispatcher.InvokeAsyncImpl(renderOp, CancellationToken.None); } /// <summary> /// This handles the _inputMarkerOp message. We're using /// _inputMarkerOp to determine if input priority dispatcher ops /// have been processes. /// </summary> private void InputMarkerHandler() { //set the marker to null so we know that input priority has been processed _inputMarkerOp = null; } private void Render() { try { _isRendering = true; RenderCore(); } finally { _nextRenderOp = null; _isRendering = false; } } private void RenderCore() { var now = _time.Elapsed; if (!_animationsAreWaitingForComposition) _clock.Pulse(now); // Since new animations could be started during the layout and can affect layout/render // We are doing several iterations when it happens for (var c = 0; c < 10; c++) { FireInvokeOnRenderCallbacks(); if (_clock.HasNewSubscriptions) { _clock.PulseNewSubscriptions(); continue; } break; } if (_requestedCommits.Count > 0 || _clock.HasSubscriptions) { _animationsAreWaitingForComposition = CommitCompositorsWithThrottling(); if (!_animationsAreWaitingForComposition && _clock.HasSubscriptions) _animationsTimer.Start(); } } // Used for unit tests public bool IsTopLevelActive(object key) => _topLevels.ContainsKey(key); public void AddTopLevel(object key, ILayoutManager layoutManager, IRenderer renderer) { if(_topLevels.ContainsKey(key)) return; var render = (CompositingRenderer)renderer; _topLevels.Add(key, new TopLevelInfo(render.Compositor, render, layoutManager)); render.Start(); ScheduleRender(true); } public void RemoveTopLevel(object key) { if (_topLevels.Remove(key, out var info)) { info.Renderer.Stop(); } } /// <summary> /// Calls all _invokeOnRenderCallbacks until no more are added /// </summary> private void FireInvokeOnRenderCallbacks() { int callbackLoopCount = 0; int count = _invokeOnRenderCallbacks?.Count ?? 0; // This outer loop is to re-run layout in case the app causes a layout to get enqueued in response // to a Loaded event. In this case we would like to re-run layout before we allow render. do { while (count > 0) { callbackLoopCount++; if (callbackLoopCount > 153) throw new InvalidOperationException("Infinite layout loop detected"); var callbacks = _invokeOnRenderCallbacks!; _invokeOnRenderCallbacks = null; for (int i = 0; i < count; i++) callbacks[i].Invoke(); callbacks.Clear(); _invokeOnRenderCallbackListPool.Push(callbacks); count = _invokeOnRenderCallbacks?.Count ?? 0; } // TODO: port the rest of the Loaded logic later // Fire all the pending Loaded events before Render happens // but after the layout storm has subsided // FireLoadedPendingCallbacks(); count = _invokeOnRenderCallbacks?.Count ?? 0; } while (count > 0); } /// <summary> /// Executes the <paramref name="callback">callback</paramref> in the next iteration of the current UI-thread /// render loop / layout pass that. /// </summary> /// <param name="callback"></param> public void BeginInvokeOnRender(Action callback) { if (_invokeOnRenderCallbacks == null) _invokeOnRenderCallbacks = _invokeOnRenderCallbackListPool.Count > 0 ? _invokeOnRenderCallbackListPool.Pop() : new(); _invokeOnRenderCallbacks.Add(callback); if (!_isRendering) ScheduleRender(true); } }
TopLevelInfo
csharp
jellyfin__jellyfin
MediaBrowser.Controller/MediaEncoding/JobLogger.cs
{ "start": 250, "end": 5671 }
public class ____ { private readonly ILogger _logger; public JobLogger(ILogger logger) { _logger = logger; } public async Task StartStreamingLog(EncodingJobInfo state, StreamReader reader, Stream target) { try { using (target) using (reader) { while (!reader.EndOfStream && reader.BaseStream.CanRead) { var line = await reader.ReadLineAsync().ConfigureAwait(false); ParseLogLine(line, state); var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line); // If ffmpeg process is closed, the state is disposed, so don't write to target in that case if (!target.CanWrite) { break; } await target.WriteAsync(bytes).ConfigureAwait(false); // Check again, the stream could have been closed if (!target.CanWrite) { break; } await target.FlushAsync().ConfigureAwait(false); } } } catch (Exception ex) { _logger.LogError(ex, "Error reading ffmpeg log"); } } private void ParseLogLine(string line, EncodingJobInfo state) { float? framerate = null; double? percent = null; TimeSpan? transcodingPosition = null; long? bytesTranscoded = null; int? bitRate = null; var parts = line.Split(' '); var totalMs = state.RunTimeTicks.HasValue ? TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds : 0; var startMs = state.BaseRequest.StartTimeTicks.HasValue ? TimeSpan.FromTicks(state.BaseRequest.StartTimeTicks.Value).TotalMilliseconds : 0; for (var i = 0; i < parts.Length; i++) { var part = parts[i]; if (string.Equals(part, "fps=", StringComparison.OrdinalIgnoreCase) && (i + 1 < parts.Length)) { var rate = parts[i + 1]; if (float.TryParse(rate, CultureInfo.InvariantCulture, out var val)) { framerate = val; } } else if (part.StartsWith("fps=", StringComparison.OrdinalIgnoreCase)) { var rate = part.Split('=', 2)[^1]; if (float.TryParse(rate, CultureInfo.InvariantCulture, out var val)) { framerate = val; } } else if (state.RunTimeTicks.HasValue && part.StartsWith("time=", StringComparison.OrdinalIgnoreCase)) { var time = part.Split('=', 2)[^1]; if (TimeSpan.TryParse(time, CultureInfo.InvariantCulture, out var val)) { var currentMs = startMs + val.TotalMilliseconds; percent = 100.0 * currentMs / totalMs; transcodingPosition = TimeSpan.FromMilliseconds(currentMs); } } else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase)) { var size = part.Split('=', 2)[^1]; int? scale = null; if (size.Contains("kb", StringComparison.OrdinalIgnoreCase)) { scale = 1024; size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase); } if (scale.HasValue) { if (long.TryParse(size, CultureInfo.InvariantCulture, out var val)) { bytesTranscoded = val * scale.Value; } } } else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase)) { var rate = part.Split('=', 2)[^1]; int? scale = null; if (rate.Contains("kbits/s", StringComparison.OrdinalIgnoreCase)) { scale = 1024; rate = rate.Replace("kbits/s", string.Empty, StringComparison.OrdinalIgnoreCase); } if (scale.HasValue) { if (float.TryParse(rate, CultureInfo.InvariantCulture, out var val)) { bitRate = (int)Math.Ceiling(val * scale.Value); } } } } if (framerate.HasValue || percent.HasValue) { state.ReportTranscodingProgress(transcodingPosition, framerate, percent, bytesTranscoded, bitRate); } } } }
JobLogger
csharp
xunit__xunit
src/xunit.v3.runner.common/Reporters/Builtin/AppVeyorReporterMessageHandler.cs
{ "start": 378, "end": 7005 }
public class ____ : DefaultRunnerReporterMessageHandler { const int MaxLength = 4096; int assembliesInFlight; readonly ConcurrentDictionary<string, (string assemblyFileName, Dictionary<string, int> testMethods)> assemblyInfoByUniqueID = new(); readonly string baseUri; AppVeyorClient? client; readonly object clientLock = new(); /// <summary> /// Initializes a new instance of the <see cref="AppVeyorReporterMessageHandler" /> class. /// </summary> /// <param name="logger">The logger used to report messages</param> /// <param name="baseUri">The base AppVeyor API URI</param> public AppVeyorReporterMessageHandler( IRunnerLogger logger, string baseUri) : base(logger) { Guard.ArgumentNotNull(baseUri); this.baseUri = baseUri.TrimEnd('/'); } AppVeyorClient Client { get { lock (clientLock) client ??= new AppVeyorClient(Logger, baseUri); return client; } } /// <inheritdoc/> public override async ValueTask DisposeAsync() { await base.DisposeAsync(); GC.SuppressFinalize(this); lock (clientLock) { client?.SafeDispose(); client = null; if (assembliesInFlight != 0) Logger.LogWarning( string.Format( CultureInfo.CurrentCulture, "{0} disposed with {1} assemblies in flight", nameof(AppVeyorReporterMessageHandler), assembliesInFlight ) ); } } /// <inheritdoc/> protected override void HandleTestAssemblyFinished(MessageHandlerArgs<ITestAssemblyFinished> args) { Guard.ArgumentNotNull(args); base.HandleTestAssemblyFinished(args); lock (clientLock) { assembliesInFlight--; if (assembliesInFlight == 0) { client?.SafeDispose(); client = null; } } } /// <inheritdoc/> protected override void HandleTestAssemblyStarting(MessageHandlerArgs<ITestAssemblyStarting> args) { Guard.ArgumentNotNull(args); base.HandleTestAssemblyStarting(args); lock (clientLock) { assembliesInFlight++; // Use the TFM attrib to disambiguate var tfm = args.Message.TargetFramework; var assemblyFileName = Path.GetFileName(args.Message.AssemblyPath) ?? "<unknown filename>"; if (!string.IsNullOrWhiteSpace(tfm)) assemblyFileName = string.Format(CultureInfo.InvariantCulture, "{0} ({1})", assemblyFileName, tfm); assemblyInfoByUniqueID[args.Message.AssemblyUniqueID] = (assemblyFileName, new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)); } } /// <inheritdoc/> protected override void HandleTestStarting(MessageHandlerArgs<ITestStarting> args) { Guard.ArgumentNotNull(args); base.HandleTestStarting(args); var testName = args.Message.TestDisplayName; var testMethods = assemblyInfoByUniqueID[args.Message.AssemblyUniqueID].testMethods; lock (testMethods) if (testMethods.TryGetValue(testName, out var testIdx)) testName = string.Format(CultureInfo.InvariantCulture, "{0} {1}", testName, testIdx); Client.AddTest(GetRequestMessage( testName, "xUnit", assemblyInfoByUniqueID[args.Message.AssemblyUniqueID].assemblyFileName, "Running" )); } /// <inheritdoc/> protected override void HandleTestPassed(MessageHandlerArgs<ITestPassed> args) { Guard.ArgumentNotNull(args); var testPassed = args.Message; var metadata = MetadataCache.TryGetTestMetadata(testPassed); if (metadata is not null) { var testMethods = assemblyInfoByUniqueID[testPassed.AssemblyUniqueID].testMethods; Client.UpdateTest(GetRequestMessage( GetFinishedTestName(metadata.TestDisplayName, testMethods), "xUnit", assemblyInfoByUniqueID[testPassed.AssemblyUniqueID].assemblyFileName, "Passed", Convert.ToInt64(testPassed.ExecutionTime * 1000), stdOut: testPassed.Output )); } // TODO: What to do when metadata lookup fails? base.HandleTestPassed(args); } /// <inheritdoc/> protected override void HandleTestSkipped(MessageHandlerArgs<ITestSkipped> args) { Guard.ArgumentNotNull(args); var testSkipped = args.Message; var metadata = MetadataCache.TryGetTestMetadata(testSkipped); if (metadata is not null) { var testMethods = assemblyInfoByUniqueID[testSkipped.AssemblyUniqueID].testMethods; Client.UpdateTest(GetRequestMessage( GetFinishedTestName(metadata.TestDisplayName, testMethods), "xUnit", assemblyInfoByUniqueID[testSkipped.AssemblyUniqueID].assemblyFileName, "Skipped", Convert.ToInt64(testSkipped.ExecutionTime * 1000), stdOut: testSkipped.Output )); } // TODO: What to do when metadata lookup fails? base.HandleTestSkipped(args); } /// <inheritdoc/> protected override void HandleTestFailed(MessageHandlerArgs<ITestFailed> args) { Guard.ArgumentNotNull(args); var testFailed = args.Message; var metadata = MetadataCache.TryGetTestMetadata(testFailed); if (metadata is not null) { var testMethods = assemblyInfoByUniqueID[testFailed.AssemblyUniqueID].testMethods; Client.UpdateTest(GetRequestMessage( GetFinishedTestName(metadata.TestDisplayName, testMethods), "xUnit", assemblyInfoByUniqueID[testFailed.AssemblyUniqueID].assemblyFileName, "Failed", Convert.ToInt64(testFailed.ExecutionTime * 1000), ExceptionUtility.CombineMessages(testFailed), ExceptionUtility.CombineStackTraces(testFailed), testFailed.Output )); } // TODO: What to do when metadata lookup fails? base.HandleTestFailed(args); } // AppVeyor API helpers static string GetFinishedTestName( string methodName, Dictionary<string, int> testMethods) { lock (testMethods) { var testName = methodName; if (testMethods.TryGetValue(methodName, out var number)) testName = string.Format(CultureInfo.InvariantCulture, "{0} {1}", methodName, number); testMethods[methodName] = number + 1; return testName; } } // If this method is ever changed to support value types other than string and long, you must update // AppVeyorClient.ToJson() to ensure the types are identified and serialized correctly. static Dictionary<string, object?> GetRequestMessage( string testName, string testFramework, string fileName, string outcome, long? durationMilliseconds = null, string? errorMessage = null, string? errorStackTrace = null, string? stdOut = null) => new() { { "testName", testName }, { "testFramework", testFramework }, { "fileName", fileName }, { "outcome", outcome }, { "durationMilliseconds", durationMilliseconds }, { "ErrorMessage", errorMessage }, { "ErrorStackTrace", errorStackTrace }, { "StdOut", stdOut?.Length > MaxLength ? stdOut.Substring(0, MaxLength) : stdOut }, }; }
AppVeyorReporterMessageHandler
csharp
npgsql__npgsql
src/Npgsql.GeoJSON/CrsMap.cs
{ "start": 133, "end": 1100 }
public partial class ____ { readonly CrsMapEntry[]? _overridden; internal CrsMap(CrsMapEntry[]? overridden) => _overridden = overridden; internal string? GetAuthority(int srid) => GetAuthority(_overridden, srid) ?? GetAuthority(WellKnown, srid); static string? GetAuthority(CrsMapEntry[]? entries, int srid) { if (entries == null) return null; var left = 0; var right = entries.Length; while (left <= right) { var middle = left + (right - left) / 2; var entry = entries[middle]; if (srid < entry.MinSrid) right = middle - 1; else if (srid > entry.MaxSrid) left = middle + 1; else return entry.Authority; } return null; } } /// <summary> /// An entry which maps the authority to the inclusive range of SRID. /// </summary> readonly
CrsMap
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Benchmarks/TestBindingObservable.cs
{ "start": 90, "end": 1082 }
internal class ____<T> : IObservable<BindingValue<T?>>, IDisposable { private T? _value; private IObserver<BindingValue<T?>>? _observer; public TestBindingObservable(T? initialValue = default) => _value = initialValue; public IDisposable Subscribe(IObserver<BindingValue<T?>> observer) { if (_observer is object) throw new InvalidOperationException("The observable can only be subscribed once."); _observer = observer; observer.OnNext(_value); return this; } public void Dispose() => _observer = null; public void OnNext(T? value) => _observer?.OnNext(value); public void PublishCompleted() { _observer?.OnCompleted(); _observer = null; } protected void PublishError(Exception error) { _observer?.OnError(error); _observer = null; } } }
TestBindingObservable
csharp
microsoft__semantic-kernel
dotnet/src/IntegrationTests/Plugins/Web/WebFileDownloadPluginTests.cs
{ "start": 318, "end": 1418 }
public sealed class ____ : BaseIntegrationTest { /// <summary> /// Verify downloading to a temporary directory on the local machine. /// </summary> [Fact] public async Task VerifyDownloadToFileAsync() { var uri = new Uri("https://raw.githubusercontent.com/microsoft/semantic-kernel/refs/heads/main/docs/images/sk_logo.png"); var folderPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "sk_logo.png"); try { Directory.CreateDirectory(folderPath); var webFileDownload = new WebFileDownloadPlugin() { AllowedDomains = ["raw.githubusercontent.com"], AllowedFolders = [folderPath] }; await webFileDownload.DownloadToFileAsync(uri, filePath); Assert.True(Path.Exists(filePath)); } finally { if (Path.Exists(folderPath)) { Directory.Delete(folderPath, true); } } } }
WebFileDownloadPluginTests
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 690319, "end": 690706 }
public partial interface ____ : IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_3, IInterfaceImplementationRemoved { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_InterfaceImplementationRemoved
csharp
abpframework__abp
framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/ExceptionHandling/AbpAuthorizationExceptionTestPage_Tests.cs
{ "start": 355, "end": 2226 }
public class ____ : AspNetCoreMvcTestBase { private IExceptionSubscriber _fakeExceptionSubscriber; private FakeUserClaims _fakeRequiredService; public AbpAuthorizationExceptionTestPage_Tests() { _fakeRequiredService = GetRequiredService<FakeUserClaims>(); } protected override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); _fakeExceptionSubscriber = Substitute.For<IExceptionSubscriber>(); services.AddSingleton(_fakeExceptionSubscriber); services.Configure<AbpAuthorizationExceptionHandlerOptions>(options => { options.AuthenticationScheme = "Cookie"; }); } [Fact] public virtual async Task Should_Handle_By_Cookie_AuthenticationScheme_For_AbpAuthorizationException() { var result = await GetResponseAsync("/ExceptionHandling/ExceptionTestPage?handler=AbpAuthorizationException", HttpStatusCode.Redirect); result.Headers.Location.ToString().ShouldContain("http://localhost/Account/Login"); #pragma warning disable 4014 _fakeExceptionSubscriber .Received() .HandleAsync(Arg.Any<ExceptionNotificationContext>()); #pragma warning restore 4014 _fakeRequiredService.Claims.AddRange(new[] { new Claim(AbpClaimTypes.UserId, Guid.NewGuid().ToString()) }); result = await GetResponseAsync("/ExceptionHandling/ExceptionTestPage?handler=AbpAuthorizationException", HttpStatusCode.Redirect); result.Headers.Location.ToString().ShouldContain("http://localhost/Account/AccessDenied"); #pragma warning disable 4014 _fakeExceptionSubscriber .Received() .HandleAsync(Arg.Any<ExceptionNotificationContext>()); #pragma warning restore 4014 } }
AbpAuthorizationExceptionTestPage_Tests
csharp
unoplatform__uno
src/Uno.UI.Runtime.Skia.X11/DBus/Desktop.DBus.cs
{ "start": 72790, "end": 73994 }
interface ____<string> changed = new(), invalidated = new(); return new PropertyChanges<EmailProperties>(ReadProperties(ref reader, changed), ReadInvalidated(ref reader), changed.ToArray()); } static string[] ReadInvalidated(ref Reader reader) { List<string>? invalidated = null; ArrayEnd arrayEnd = reader.ReadArrayStart(DBusType.String); while (reader.HasNext(arrayEnd)) { invalidated ??= new(); var property = reader.ReadString(); switch (property) { case "version": invalidated.Add("Version"); break; } } return invalidated?.ToArray() ?? Array.Empty<string>(); } } private static EmailProperties ReadProperties(ref Reader reader, List<string>? changedList = null) { var props = new EmailProperties(); ArrayEnd arrayEnd = reader.ReadArrayStart(DBusType.Struct); while (reader.HasNext(arrayEnd)) { var property = reader.ReadString(); switch (property) { case "version": reader.ReadSignature("u"u8); props.Version = reader.ReadUInt32(); changedList?.Add("Version"); break; default: reader.ReadVariantValue(); break; } } return props; } }
List
csharp
dotnetcore__CAP
src/DotNetCore.CAP.Pulsar/CAP.PulsarOptions.cs
{ "start": 737, "end": 1414 }
public class ____ { private static readonly PulsarClientConfiguration Default = PulsarClientConfiguration.Default; public bool UseTls { get; set; } = Default.UseTls; public bool TlsHostnameVerificationEnable { get; set; } = Default.TlsHostnameVerificationEnable; public bool TlsAllowInsecureConnection { get; set; } = Default.TlsAllowInsecureConnection; public X509Certificate2 TlsTrustCertificate { get; set; } = Default.TlsTrustCertificate; public Authentication Authentication { get; set; } = Default.Authentication; public SslProtocols TlsProtocols { get; set; } = Default.TlsProtocols; } }
TlsOptions
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/ContainerTests/Common_Tests/Common_Discovery.cs
{ "start": 2230, "end": 2915 }
public class ____ : SagaDefinition<DiscoveryPingSaga> { protected override void ConfigureSaga(IReceiveEndpointConfigurator endpointConfigurator, ISagaConfigurator<DiscoveryPingSaga> sagaConfigurator, IRegistrationContext context) { var partition = endpointConfigurator.CreatePartitioner(Environment.ProcessorCount); sagaConfigurator.Message<PingReceived>(x => x.UsePartitioner(partition, m => m.Message.CorrelationId)); sagaConfigurator.Message<PingAcknowledged>(x => x.UsePartitioner(partition, m => m.Message.CorrelationId)); } }
PingSagaDefinition
csharp
nuke-build__nuke
source/Nuke.Common/Tools/Docker/Docker.Generated.cs
{ "start": 622732, "end": 623438 }
public partial class ____ : DockerOptionsBase { /// <summary>Seconds to wait for stop before killing the container.</summary> [Argument(Format = "--time {value}")] public int? Time => Get<int?>(() => Time); /// <summary>CONTAINER</summary> [Argument(Format = "{value}", Position = -1, Separator = " ")] public IReadOnlyList<string> Containers => Get<List<string>>(() => Containers); } #endregion #region DockerConfigSettings /// <inheritdoc cref="DockerTasks.DockerConfig(Nuke.Common.Tools.Docker.DockerConfigSettings)"/> [PublicAPI] [ExcludeFromCodeCoverage] [Command(Type = typeof(DockerTasks), Command = nameof(DockerTasks.DockerConfig), Arguments = "config")]
DockerContainerRestartSettings
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Extensions.Tests/AutoQueryCrudTests.Validate.cs
{ "start": 398, "end": 976 }
public class ____() : TypeValidator("HasForeignKeyReferences", "Has RockstarAlbum References") { public override async Task<bool> IsValidAsync(object dto, IRequest request) { //Example of using compiled accessor delegates to access `Id` property //var id = TypeProperties.Get(dto.GetType()).GetPublicGetter("Id")(dto).ConvertTo<int>(); var id = ((IHasId<int>)dto).Id; using var db = HostContext.AppHost.GetDbConnection(request); return !await db.ExistsAsync<RockstarAlbum>(x => x.RockstarId == id); } }
NoRockstarAlbumReferences
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Queries/Drivers/QueryDisplayDriver.cs
{ "start": 278, "end": 3362 }
public sealed class ____ : DisplayDriver<Query> { private readonly IQueryManager _queryManager; internal readonly IStringLocalizer S; public QueryDisplayDriver( IQueryManager queryManager, IStringLocalizer<QueryDisplayDriver> stringLocalizer) { _queryManager = queryManager; S = stringLocalizer; } public override Task<IDisplayResult> DisplayAsync(Query query, BuildDisplayContext context) { return CombineAsync( Dynamic("Query_Fields_SummaryAdmin", model => { model.Name = query.Name; model.Source = query.Source; model.Schema = query.Schema; model.Query = query; }).Location("Content:1"), Dynamic("Query_Buttons_SummaryAdmin", model => { model.Name = query.Name; model.Source = query.Source; model.Schema = query.Schema; model.Query = query; }).Location("Actions:5") ); } public override Task<IDisplayResult> EditAsync(Query query, BuildEditorContext context) { return CombineAsync( Initialize<EditQueryViewModel>("Query_Fields_Edit", model => { model.Name = query.Name; model.Source = query.Source; model.Schema = query.Schema; model.Query = query; }).Location("Content:1"), Initialize<EditQueryViewModel>("Query_Fields_Buttons", model => { model.Name = query.Name; model.Source = query.Source; model.Schema = query.Schema; model.Query = query; }).Location("Actions:5") ); } public override async Task<IDisplayResult> UpdateAsync(Query model, UpdateEditorContext context) { await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.Name, m => m.Source, m => m.Schema); if (string.IsNullOrEmpty(model.Name)) { context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["Name is required"]); } if (!string.IsNullOrEmpty(model.Schema) && !model.Schema.IsJson()) { context.Updater.ModelState.AddModelError(Prefix, nameof(model.Schema), S["Invalid schema JSON supplied."]); } var safeName = model.Name.ToSafeName(); if (string.IsNullOrEmpty(safeName) || model.Name != safeName) { context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["Name contains illegal characters"]); } else { var existing = await _queryManager.GetQueryAsync(safeName); if (existing != null && existing != model) { context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["A query with the same name already exists"]); } } return await EditAsync(model, context); } }
QueryDisplayDriver
csharp
MapsterMapper__Mapster
src/ExpressionDebugger.Tests/DebugInfoInjectorTest.cs
{ "start": 23873, "end": 24052 }
public partial record ____(string prop2) { public string Prop1 { get; set; } public string Prop3 { get; init; } } }".Trim(), str); }
MockClass
csharp
NLog__NLog
tests/NLog.UnitTests/Config/ServiceRepositoryTests.cs
{ "start": 9030, "end": 9606 }
private class ____ : NLog.LayoutRenderers.LayoutRenderer { private object _wantedDependency; protected override void InitializeLayoutRenderer() { _wantedDependency = ResolveService<IMisingDependencyClass>(); base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_wantedDependency != null ? "Success" : "Failed"); } }
LayoutRendererUsingDependency
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs
{ "start": 388, "end": 780 }
public class ____ : IModelBinderProvider { /// <inheritdoc /> public IModelBinder? GetBinder(ModelBinderProviderContext context) { ArgumentNullException.ThrowIfNull(context); if (context.BindingInfo.BinderType is Type binderType) { return new BinderTypeModelBinder(binderType); } return null; } }
BinderTypeModelBinderProvider
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/DI/RegistrationTests.cs
{ "start": 69, "end": 2097 }
public class ____ : QueryTestBase<RegistrationTests.MySchema> { public override void RegisterServices(IServiceRegister register) { register.TryRegister(typeof(IClassSingle), typeof(ClassSingle1), ServiceLifetime.Transient, RegistrationCompareMode.ServiceType); register.TryRegister(typeof(IClassSingle), typeof(ClassSingle2), ServiceLifetime.Transient, RegistrationCompareMode.ServiceType); register.TryRegister<IClassSingle, ClassSingle1>(p => new ClassSingle1(), ServiceLifetime.Transient, RegistrationCompareMode.ServiceType); register.TryRegister<IClassSingle, ClassSingle2>(p => new ClassSingle2(), ServiceLifetime.Transient, RegistrationCompareMode.ServiceType); register.TryRegister<IClassSingle>(new ClassSingle1(), RegistrationCompareMode.ServiceType); register.TryRegister<IClassSingle>(new ClassSingle2(), RegistrationCompareMode.ServiceType); //------------ register.TryRegister(typeof(IClassMultiple), typeof(ClassMultiple1), ServiceLifetime.Transient, RegistrationCompareMode.ServiceTypeAndImplementationType); register.TryRegister(typeof(IClassMultiple), typeof(ClassMultiple2), ServiceLifetime.Transient, RegistrationCompareMode.ServiceTypeAndImplementationType); register.TryRegister<IClassMultiple, ClassMultiple1>(p => new ClassMultiple1(), ServiceLifetime.Transient, RegistrationCompareMode.ServiceTypeAndImplementationType); register.TryRegister<IClassMultiple, ClassMultiple2>(p => new ClassMultiple2(), ServiceLifetime.Transient, RegistrationCompareMode.ServiceTypeAndImplementationType); register.TryRegister<IClassMultiple>(new ClassMultiple1(), RegistrationCompareMode.ServiceTypeAndImplementationType); register.TryRegister<IClassMultiple>(new ClassMultiple2(), RegistrationCompareMode.ServiceTypeAndImplementationType); base.RegisterServices(register); } [Fact] public void Registration_Should_Work() { Schema.Initialize(); }
RegistrationTests
csharp
dotnet__efcore
src/EFCore.Design/Design/OperationReportHandler.cs
{ "start": 270, "end": 2636 }
public class ____ : MarshalByRefObject, IOperationReportHandler { private readonly Action<string>? _errorHandler; private readonly Action<string>? _warningHandler; private readonly Action<string>? _informationHandler; private readonly Action<string>? _verboseHandler; /// <summary> /// Gets the contract version of this handler. /// </summary> /// <value> The contract version of this handler. </value> public virtual int Version => 0; /// <summary> /// Initializes a new instance of the <see cref="OperationReportHandler" /> class. /// </summary> /// <param name="errorHandler">A callback for <see cref="OnError(string)" />.</param> /// <param name="warningHandler">A callback for <see cref="OnWarning(string)" />.</param> /// <param name="informationHandler">A callback for <see cref="OnInformation(string)" />.</param> /// <param name="verboseHandler">A callback for <see cref="OnVerbose(string)" />.</param> public OperationReportHandler( Action<string>? errorHandler = null, Action<string>? warningHandler = null, Action<string>? informationHandler = null, Action<string>? verboseHandler = null) { _errorHandler = errorHandler; _warningHandler = warningHandler; _informationHandler = informationHandler; _verboseHandler = verboseHandler; } /// <summary> /// Invoked when an error is reported. /// </summary> /// <param name="message">The message.</param> public virtual void OnError(string message) => _errorHandler?.Invoke(message); /// <summary> /// Invoked when a warning is reported. /// </summary> /// <param name="message">The message.</param> public virtual void OnWarning(string message) => _warningHandler?.Invoke(message); /// <summary> /// Invoked when information is reported. /// </summary> /// <param name="message">The message.</param> public virtual void OnInformation(string message) => _informationHandler?.Invoke(message); /// <summary> /// Invoked when verbose information is reported. /// </summary> /// <param name="message">The message.</param> public virtual void OnVerbose(string message) => _verboseHandler?.Invoke(message); }
OperationReportHandler
csharp
ServiceStack__ServiceStack
ServiceStack.Blazor/tests/UI.Gallery/Gallery.Wasm/Gallery.Wasm/Configure.AppHost.cs
{ "start": 215, "end": 2964 }
public class ____ : AppHostBase, IHostingStartup { public AppHost() : base("Blazor Gallery", typeof(MyServices).Assembly) { } public override void Configure(Container container) { SetConfig(new HostConfig { }); Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization", allowOriginWhitelist: new[]{ "http://localhost:5000", "https://localhost:5001", "https://localhost:5002", "http://localhost:3000", "http://localhost:5173", "http://localhost:8080", "https://docs.servicestack.net", "https://servicestack.net", "https://jamstacks.net", "https://razor-ssg.web-templates.io", "https://razor-press.web-templates.io", "https://" + Environment.GetEnvironmentVariable("DEPLOY_CDN") }, allowCredentials: true)); var wwwrootVfs = GetVirtualFileSource<FileSystemVirtualFiles>(); var appDataVfs = new FileSystemVirtualFiles(ContentRootDirectory.RealPath.CombineWith("App_Data").AssertDir()); Plugins.Add(new FilesUploadFeature( new UploadLocation("profiles", wwwrootVfs, allowExtensions: FileExt.WebImages, resolvePath: ctx => $"/profiles/{ctx.FileName}"), new UploadLocation("users", wwwrootVfs, allowExtensions: FileExt.WebImages, resolvePath: ctx => $"/profiles/users/{ctx.UserAuthId}.{ctx.FileExtension}"), new UploadLocation("applications", appDataVfs, maxFileCount: 3, maxFileBytes: 10_000_000, resolvePath: ctx => ctx.GetLocationPath((ctx.Dto is CreateJobApplication create ? $"jobapp/{create.JobId}/{create.ContactId}/{ctx.FileName}" : $"app/{ctx.Dto.GetId()}") + $"/{ctx.DateSegment}/{ctx.FileName}"), readAccessRole: RoleNames.AllowAnon, writeAccessRole: RoleNames.AllowAnon) )); ScriptContext.Args["AppData"] = new AppData { Currencies = NumberCurrency.All, AlphaValues = new() { "Alpha", "Bravo", "Charlie" }, AlphaDictionary = new() { ["A"] = "Alpha", ["B"] = "Bravo", ["C"] = "Charlie", }, AlphaKeyValuePairs = new() { new("A","Alpha"), new("B","Bravo"), new("C","Charlie"), }, }; } public void Configure(IWebHostBuilder builder) => builder .ConfigureServices((context, services) => services.ConfigureNonBreakingSameSiteCookies(context.HostingEnvironment)); }
AppHost
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Models/Knowledgebase/KnowledgebaseCategoryModel.cs
{ "start": 2371, "end": 3376 }
public class ____ : ILocalizedModelLocal, ISlugModelLocal { [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.Name")] public string Name { get; set; } [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.Description")] public string Description { get; set; } [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.MetaKeywords")] public string MetaKeywords { get; set; } [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.MetaDescription")] public string MetaDescription { get; set; } [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.MetaTitle")] public string MetaTitle { get; set; } public string LanguageId { get; set; } [GrandResourceDisplayName("Admin.Content.Knowledgebase.KnowledgebaseCategory.Fields.SeName")] public string SeName { get; set; } }
KnowledgebaseCategoryLocalizedModel
csharp
khellang__Scrutor
test/Scrutor.Tests/ScanningTests.cs
{ "start": 27775, "end": 27879 }
public class ____ : IDefault3Level2, IDefault1, IDefault2 { } [CompilerGenerated]
DefaultAttributes
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/ModelBinding/Metadata/ModelAttributesTest.cs
{ "start": 14767, "end": 15087 }
private class ____ { [IrrelevantAttribute] // We verify this is ignored public void Method( object noAttributes, [Required, Range(1, 100)] int validationAttributes, [BindRequired] BaseModel mergedAttributes) { } }
MethodWithParamAttributesType
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/HtmlModulesFeature.cs
{ "start": 8199, "end": 19909 }
struct ____(int index, string token, IHtmlModuleFragment fragment) { internal int index = index; internal string token = token; internal IHtmlModuleFragment fragment = fragment; }; IHtmlModuleFragment[]? indexFragments; IHtmlModuleFragment[] GetIndexFragments() { if (!HostContext.DebugMode && indexFragments != null) return indexFragments; var indexFile = VirtualFiles!.GetFile(DirPath.CombineWith(IndexFile)); if (indexFile == null) { if (Feature!.IgnoreIfError) return TypeConstants<IHtmlModuleFragment>.EmptyArray; throw HttpError.NotFound(DirPath.CombineWith(IndexFile) + " was not found"); } var indexContentsString = indexFile.ReadAllText(); var indexContents = indexContentsString.AsMemory(); var fragmentDefs = new List<FragmentTuple>(); foreach (var entry in Tokens.Union(Feature?.Tokens ?? new())) { var tokenPos = 0; do { tokenPos = indexContents.IndexOf(entry.Key, tokenPos); if (tokenPos == -1) continue; fragmentDefs.Add(new(tokenPos, entry.Key, new HtmlTokenFragment(entry.Key, entry.Value))); tokenPos += entry.Key.Length; } while (tokenPos >= 0); } foreach (var handler in Handlers.Union(Feature?.Handlers ?? new())) { var htmlCommentPrefix = "<!--" + handler.Name + ":"; var jsCommentPrefix = "/*" + handler.Name + ":"; int htmlPos = 0; int jsPos = 0; do { if (htmlPos != -1) { htmlPos = indexContents.IndexOf(htmlCommentPrefix, htmlPos); if (htmlPos >= 0) { var endPos = indexContents.IndexOf("-->", htmlPos); if (endPos == -1) throw new Exception($"{htmlCommentPrefix} is missing -->"); var token = indexContents.Slice(htmlPos, (endPos - htmlPos) + "-->".Length).ToString(); var args = token.Substring(htmlCommentPrefix.Length, token.Length - htmlCommentPrefix.Length - "-->".Length).Trim(); fragmentDefs.Add(new(htmlPos, token, new HtmlHandlerFragment(token, args, handler.Execute))); htmlPos = endPos; } } if (jsPos != -1) { jsPos = indexContents.IndexOf(jsCommentPrefix, jsPos); if (jsPos >= 0) { var endPos = indexContents.IndexOf("*/", jsPos); if (endPos == -1) throw new Exception($"{jsCommentPrefix} is missing */"); var token = indexContents.Slice(jsPos, endPos - jsPos + "*/".Length).ToString(); var args = token.Substring(jsCommentPrefix.Length, token.Length - jsCommentPrefix.Length - "*/".Length).Trim(); fragmentDefs.Add(new(jsPos, token, new HtmlHandlerFragment(token, args, handler.Execute))); jsPos = endPos; } } } while (htmlPos >= 0 || jsPos >= 0); } fragmentDefs.Sort((a, b) => a.index.CompareTo(b.index)); var fragments = new List<IHtmlModuleFragment>(); var lastPos = 0; for (var i = 0; i < fragmentDefs.Count; i++) { var fragmentDef = fragmentDefs[i]; var startPos = indexContents.IndexOf(fragmentDef.token, lastPos); if (startPos == -1) throw new Exception($"Error parsing {IndexFile}, missing '{fragmentDef.token}'"); fragments.Add(new HtmlTextFragment(TransformContent(indexContents.Slice(lastPos, startPos - lastPos)))); fragments.Add(fragmentDef.fragment); lastPos = startPos + fragmentDef.token.Length; } fragments.Add(new HtmlTextFragment(TransformContent(indexContents.Slice(lastPos)))); indexFragments = fragments.ToArray(); return indexFragments; } public ReadOnlyMemory<char> TransformContent(ReadOnlyMemory<char> content) { if (content.Length == 0 || LineTransformers.Count == 0) return content; int startIndex = 0; var sb = StringBuilderCache.Allocate(); while (content.TryReadLine(out var line, ref startIndex)) { foreach (var lineTransformer in LineTransformers) { line = lineTransformer.Transform(line); if (line.Length == 0) break; } if (line.Length > 0) { sb.AppendLine(line); } } // Trim last new line to remove new lines between tokens & text fragments if (sb.Length > 2) { if (sb[sb.Length - 1] == '\n') sb.Length -= 1; if (sb[sb.Length - 1] == '\r') sb.Length -= 1; } return StringBuilderCache.ReturnAndFree(sb).AsMemory(); } private string? indexFileETag = null; private byte[]? cachedBytes; private ConcurrentDictionary<string, byte[]> zipCache = new(); public void Flush() { zipCache.Clear(); indexFragments = null; } public Func<IHttpRequest, HttpAsyncTaskHandler?> GetHandler(IAppHost appHost) { return req => { if (!req.PathInfo.StartsWith(BasePath)) return null; foreach (var path in PublicPaths) { if (req.PathInfo.StartsWith(BasePath + path)) { var file = VirtualFiles!.GetFile(DirPath + req.PathInfo.Substring(BasePath.Length)); return file != null ? new StaticFileHandler(file) { Filter = appHost.Config.DebugMode ? (request, response, _) => { response.AddHeader(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate"); response.AddHeader(HttpHeaders.Pragma, "no-cache"); response.AddHeader(HttpHeaders.Expires, "0"); } : null } : new NotFoundHttpHandler(); } } return new CustomActionHandlerAsync(async (httpReq, httpRes) => { try { async Task RenderTo(Stream stream) { httpRes.ContentType = MimeTypes.HtmlUtf8; var fragments = GetIndexFragments(); var ctx = new HtmlModuleContext(this, httpReq); foreach (var fragment in fragments) { await fragment.WriteToAsync(ctx, stream).ConfigAwait(); } } var dynamicUi = DynamicPageQueryStrings.Any(x => httpReq.QueryString[x] != null); if (dynamicUi) { await RenderTo(httpRes.OutputStream); return; } if (EnableHttpCaching == true && indexFileETag != null) { httpRes.ContentType ??= MimeTypes.HtmlUtf8; httpRes.AddHeader(HttpHeaders.ContentType, httpRes.ContentType); httpRes.AddHeader(HttpHeaders.ETag, indexFileETag); if (httpRes.GetHeader(HttpHeaders.CacheControl) == null) httpRes.AddHeader(HttpHeaders.CacheControl, CacheControl ?? HtmlModulesFeature.DefaultCacheControl); if (req.ETagMatch(indexFileETag)) { httpRes.EndNotModified(); return; } } if (EnableCompression == true && await TryReturnCompressedResponse(httpReq, httpRes).ConfigAwait()) return; using var ms = MemoryStreamFactory.GetStream(); await RenderTo(ms); ms.Position = 0; // If EnableHttpCaching, calculate ETag hash from entire processed file if (EnableHttpCaching == true && indexFileETag == null) { indexFileETag = ms.ToMd5Hash().Quoted(); httpRes.AddHeader(HttpHeaders.ETag, indexFileETag); if (httpRes.GetHeader(HttpHeaders.CacheControl) == null) httpRes.AddHeader(HttpHeaders.CacheControl, CacheControl ?? HtmlModulesFeature.DefaultCacheControl); } if (EnableCompression == true) { cachedBytes = ms.ToArray(); if (await TryReturnCompressedResponse(httpReq, httpRes).ConfigAwait()) return; } await ms.CopyToAsync(httpRes.OutputStream).ConfigAwait(); } catch (Exception ex) { await httpRes.WriteError(ex).ConfigAwait(); } }); }; } public void Register(IAppHost appHost) { VirtualFiles ??= appHost.VirtualFiles; var fragments = GetIndexFragments(); //force parsing if (fragments.Length == 0) //Feature.IgnoreIfError return; var handlerFn = GetHandler(appHost); appHost.RawHttpHandlers.Add(handlerFn); #if NET8_0_OR_GREATER (appHost as IAppHostNetCore).MapEndpoints(routeBuilder => { routeBuilder.MapGet(BasePath + "/{*path}", httpContext => { var req = httpContext.ToRequest(); var handler = handlerFn(req); if (handler != null) { appHost.InitRequest(handler, req); return handler.ProcessRequestAsync(req, req.Response, httpContext.Request.Path); } return Task.CompletedTask; }) .WithMetadata<string>(name:BasePath, tag:GetType().Name, contentType:MimeTypes.Html, additionalContentTypes:[MimeTypes.JavaScript]); }); #endif } private async Task<bool> TryReturnCompressedResponse(IRequest httpReq, IResponse httpRes) { var compressionType = httpReq.GetCompressionType(); var compressor = compressionType != null && cachedBytes != null ? StreamCompressors.Get(compressionType) : null; if (compressor != null) { var zipBytes = zipCache.GetOrAdd(compressor.Encoding, _ => compressor.Compress(cachedBytes!)); httpRes.AddHeader(HttpHeaders.ContentEncoding, compressor.Encoding); httpRes.AddHeader(HttpHeaders.ContentType, httpRes.ContentType); await httpRes.WriteAsync(zipBytes); return true; } return false; } }
FragmentTuple
csharp
dotnetcore__Util
src/Util.Ui.NgZorro/Components/Tables/TableHeadTagHelper.cs
{ "start": 349, "end": 1089 }
public class ____ : AngularTagHelperBase { /// <summary> /// 配置 /// </summary> private Config _config; /// <summary> /// 扩展属性,是否启用自动创建嵌套结构,默认为 true /// </summary> public bool EnableAutoCreate { get; set; } /// <inheritdoc /> protected override void ProcessBefore( TagHelperContext context, TagHelperOutput output ) { _config = new Config( context, output ); var service = new TableHeadService( _config ); service.Init(); } /// <inheritdoc /> protected override IRender GetRender( TagHelperContext context, TagHelperOutput output, TagHelperContent content ) { _config.Content = content; return new TableHeadRender( _config ); } }
TableHeadTagHelper
csharp
microsoft__semantic-kernel
dotnet/src/Agents/OpenAI/OpenAIThreadCreationOptions.cs
{ "start": 419, "end": 1902 }
public sealed class ____ { /// <summary> /// Gets the optional file IDs made available to the code_interpreter tool, if enabled. /// </summary> [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList<string>? CodeInterpreterFileIds { get; init; } /// <summary> /// Gets the optional messages to initialize the thread with. /// </summary> /// <remarks> /// This property only supports messages with <see href="https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-additional_messages">role = User or Assistant</see>. /// </remarks> [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList<ChatMessageContent>? Messages { get; init; } /// <summary> /// Gets the vector store ID that enables file-search. /// </summary> [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? VectorStoreId { get; init; } /// <summary> /// Gets a set of up to 16 key/value pairs that can be attached to an agent, used for /// storing additional information about that object in a structured format. /// </summary> /// <remarks> /// Keys can be up to 64 characters in length, and values can be up to 512 characters in length. /// </remarks> [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyDictionary<string, string>? Metadata { get; init; } }
OpenAIThreadCreationOptions
csharp
dotnetcore__WTM
demo/WalkingTec.Mvvm.Demo/ViewModels/StudentVMs/StudentApiBatchVM.cs
{ "start": 635, "end": 1055 }
public class ____ : BaseVM { [Display(Name = "账号")] public String ID { get; set; } [Display(Name = "邮箱")] public String Email { get; set; } [Display(Name = "住址")] public String Address { get; set; } [Display(Name = "日期")] public DateRange EnRollDate { get; set; } protected override void InitVM() { } } }
StudentApi_BatchEdit
csharp
unoplatform__uno
src/Uno.UWP/Devices/Enumeration/Internal/Providers/Midi/MidiDeviceConnectionWatcher.wasm.cs
{ "start": 1643, "end": 2036 }
partial class ____ { [JSImport($"globalThis.Uno.Devices.Enumeration.Internal.Providers.Midi.MidiDeviceConnectionWatcher.startStateChanged")] internal static partial void StartStateChanged(); [JSImport($"globalThis.Uno.Devices.Enumeration.Internal.Providers.Midi.MidiDeviceConnectionWatcher.stopStateChanged")] internal static partial void StopStateChanged(); } } }
NativeMethods
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Layout/LayoutHelper.cs
{ "start": 266, "end": 13089 }
public static class ____ { /// <summary> /// Epsilon value used for certain layout calculations. /// Based on the value in WPF LayoutDoubleUtil. /// </summary> public static double LayoutEpsilon { get; } = 0.00000153; /// <summary> /// Calculates a control's size based on its <see cref="Layoutable.Width"/>, /// <see cref="Layoutable.Height"/>, <see cref="Layoutable.MinWidth"/>, /// <see cref="Layoutable.MaxWidth"/>, <see cref="Layoutable.MinHeight"/> and /// <see cref="Layoutable.MaxHeight"/>. /// </summary> /// <param name="control">The control.</param> /// <param name="constraints">The space available for the control.</param> /// <returns>The control's size.</returns> public static Size ApplyLayoutConstraints(Layoutable control, Size constraints) => ApplyLayoutConstraints(new MinMax(control), constraints); internal static Size ApplyLayoutConstraints(MinMax minMax, Size constraints) => new( MathUtilities.Clamp(constraints.Width, minMax.MinWidth, minMax.MaxWidth), MathUtilities.Clamp(constraints.Height, minMax.MinHeight, minMax.MaxHeight)); public static Size MeasureChild(Layoutable? control, Size availableSize, Thickness padding, Thickness borderThickness) { if (IsParentLayoutRounded(control, out double scale)) { padding = RoundLayoutThickness(padding, scale); borderThickness = RoundLayoutThickness(borderThickness, scale); } if (control != null) { control.Measure(availableSize.Deflate(padding + borderThickness)); return control.DesiredSize.Inflate(padding + borderThickness); } return new Size().Inflate(padding + borderThickness); } public static Size MeasureChild(Layoutable? control, Size availableSize, Thickness padding) { if (IsParentLayoutRounded(control, out double scale)) { padding = RoundLayoutThickness(padding, scale); } if (control != null) { control.Measure(availableSize.Deflate(padding)); return control.DesiredSize.Inflate(padding); } return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top); } public static Size ArrangeChild(Layoutable? child, Size availableSize, Thickness padding, Thickness borderThickness) { if (IsParentLayoutRounded(child, out double scale)) { padding = RoundLayoutThickness(padding, scale); borderThickness = RoundLayoutThickness(borderThickness, scale); } return ArrangeChildInternal(child, availableSize, padding + borderThickness); } public static Size ArrangeChild(Layoutable? child, Size availableSize, Thickness padding) { if(IsParentLayoutRounded(child, out double scale)) padding = RoundLayoutThickness(padding, scale); return ArrangeChildInternal(child, availableSize, padding); } private static Size ArrangeChildInternal(Layoutable? child, Size availableSize, Thickness padding) { child?.Arrange(new Rect(availableSize).Deflate(padding)); return availableSize; } private static bool IsParentLayoutRounded(Layoutable? child, out double scale) { var layoutableParent = (child as Visual)?.GetVisualParent() as Layoutable; if (layoutableParent == null || !layoutableParent.UseLayoutRounding) { scale = 1.0; return false; } scale = GetLayoutScale(layoutableParent); return true; } /// <summary> /// Invalidates measure for given control and all visual children recursively. /// </summary> public static void InvalidateSelfAndChildrenMeasure(Layoutable control) { void InnerInvalidateMeasure(Visual target) { if (target is Layoutable targetLayoutable) { targetLayoutable.InvalidateMeasure(); } var visualChildren = target.VisualChildren; var visualChildrenCount = visualChildren.Count; for (int i = 0; i < visualChildrenCount; i++) { Visual child = visualChildren[i]; InnerInvalidateMeasure(child); } } if (control is Visual v) InnerInvalidateMeasure(v); } /// <summary> /// Obtains layout scale of the given control. /// </summary> /// <param name="control">The control.</param> /// <exception cref="Exception">Thrown when control has no root or returned layout scaling is invalid.</exception> public static double GetLayoutScale(Layoutable control) => control.VisualRoot is ILayoutRoot layoutRoot ? layoutRoot.LayoutScaling : 1.0; /// <summary> /// Rounds a size to integer values for layout purposes, compensating for high DPI screen /// coordinates by rounding the size up to the nearest pixel. /// </summary> /// <param name="size">Input size.</param> /// <param name="dpiScaleX">DPI along x-dimension.</param> /// <param name="dpiScaleY">DPI along y-dimension.</param> /// <returns>Value of size that will be rounded under screen DPI.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static Size RoundLayoutSizeUp(Size size, double dpiScaleX, double dpiScaleY) { return new Size(RoundLayoutValueUp(size.Width, dpiScaleX), RoundLayoutValueUp(size.Height, dpiScaleY)); } [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator", Justification = "The DPI scale should have been normalized.")] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Size RoundLayoutSizeUp(Size size, double dpiScale) { // If DPI == 1, don't use DPI-aware rounding. return dpiScale == 1.0 ? new Size( Math.Ceiling(size.Width), Math.Ceiling(size.Height)) : new Size( Math.Ceiling(RoundTo8Digits(size.Width) * dpiScale) / dpiScale, Math.Ceiling(RoundTo8Digits(size.Height) * dpiScale) / dpiScale); } /// <summary> /// Rounds a thickness to integer values for layout purposes, compensating for high DPI screen /// coordinates. /// </summary> /// <param name="thickness">Input thickness.</param> /// <param name="dpiScaleX">DPI along x-dimension.</param> /// <param name="dpiScaleY">DPI along y-dimension.</param> /// <returns>Value of thickness that will be rounded under screen DPI.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static Thickness RoundLayoutThickness(Thickness thickness, double dpiScaleX, double dpiScaleY) { return new Thickness( RoundLayoutValue(thickness.Left, dpiScaleX), RoundLayoutValue(thickness.Top, dpiScaleY), RoundLayoutValue(thickness.Right, dpiScaleX), RoundLayoutValue(thickness.Bottom, dpiScaleY) ); } [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator", Justification = "The DPI scale should have been normalized.")] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Thickness RoundLayoutThickness(Thickness thickness, double dpiScale) { // If DPI == 1, don't use DPI-aware rounding. return dpiScale == 1.0 ? new Thickness( Math.Round(thickness.Left), Math.Round(thickness.Top), Math.Round(thickness.Right), Math.Round(thickness.Bottom)) : new Thickness( Math.Round(thickness.Left * dpiScale) / dpiScale, Math.Round(thickness.Top * dpiScale) / dpiScale, Math.Round(thickness.Right * dpiScale) / dpiScale, Math.Round(thickness.Bottom * dpiScale) / dpiScale); } [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator", Justification = "The DPI scale should have been normalized.")] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Point RoundLayoutPoint(Point point, double dpiScale) { // If DPI == 1, don't use DPI-aware rounding. return dpiScale == 1.0 ? new Point( Math.Round(point.X), Math.Round(point.Y)) : new Point( Math.Round(point.X * dpiScale) / dpiScale, Math.Round(point.Y * dpiScale) / dpiScale); } /// <summary> /// Calculates the value to be used for layout rounding at high DPI by rounding the value /// up or down to the nearest pixel. /// </summary> /// <param name="value">Input value to be rounded.</param> /// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param> /// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static double RoundLayoutValue(double value, double dpiScale) { // If DPI == 1, don't use DPI-aware rounding. return MathUtilities.IsOne(dpiScale) ? Math.Round(value) : Math.Round(value * dpiScale) / dpiScale; } /// <summary> /// Calculates the value to be used for layout rounding at high DPI by rounding the value up /// to the nearest pixel. /// </summary> /// <param name="value">Input value to be rounded.</param> /// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param> /// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static double RoundLayoutValueUp(double value, double dpiScale) { // If DPI == 1, don't use DPI-aware rounding. return MathUtilities.IsOne(dpiScale) ? Math.Ceiling(value) : Math.Ceiling(RoundTo8Digits(value) * dpiScale) / dpiScale; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static double RoundTo8Digits(double value) { // Round the value to avoid FP errors. This is needed because if `value` has a floating // point precision error (e.g. 79.333333333333343) then when it's multiplied by // `dpiScale` and rounded up, it will be rounded up to a value one greater than it // should be. #if NET6_0_OR_GREATER return Math.Round(value, 8, MidpointRounding.ToZero); #else // MidpointRounding.ToZero isn't available in netstandard2.0. return Math.Truncate(value * 1e8) / 1e8; #endif } } }
LayoutHelper
csharp
npgsql__npgsql
src/Npgsql/PostgresTypes/PostgresType.cs
{ "start": 416, "end": 545 }
class ____ its subclasses represent, see /// https://www.postgresql.org/docs/current/static/catalog-pg-type.html. /// </remarks>
and
csharp
microsoft__PowerToys
src/dsc/v3/PowerToys.DSC.UnitTests/SettingsResourceTests/SettingsResourceAppModuleTest.cs
{ "start": 403, "end": 920 }
public sealed class ____ : SettingsResourceModuleTest<GeneralSettings> { public SettingsResourceAppModuleTest() : base(SettingsResource.AppModule) { } protected override Action<GeneralSettings> GetSettingsModifier() { return s => { s.Startup = !s.Startup; s.ShowSysTrayIcon = !s.ShowSysTrayIcon; s.Enabled.Awake = !s.Enabled.Awake; s.Enabled.ColorPicker = !s.Enabled.ColorPicker; }; } }
SettingsResourceAppModuleTest
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/LoadReferencesTests.cs
{ "start": 3137, "end": 3374 }
public class ____ { [AutoIncrement] public int Id { get; set; } public string Name { get; set; } [Reference] public MismatchAliasAddress PrimaryAddress { get; set; } } [Alias("BarCustomerAddress")]
MismatchAliasCustomer
csharp
dotnet__tye
test/E2ETest/testassets/projects/Console.Normalization.svc.Name/Program.cs
{ "start": 63, "end": 198 }
class ____ { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
Program
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs
{ "start": 509, "end": 6000 }
public class ____ : TextOutputFormatter { /// <summary> /// Initializes a new <see cref="SystemTextJsonOutputFormatter"/> instance. /// </summary> /// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/>.</param> public SystemTextJsonOutputFormatter(JsonSerializerOptions jsonSerializerOptions) { SerializerOptions = jsonSerializerOptions; jsonSerializerOptions.MakeReadOnly(); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax); } internal static SystemTextJsonOutputFormatter CreateFormatter(JsonOptions jsonOptions) { var jsonSerializerOptions = jsonOptions.JsonSerializerOptions; if (jsonSerializerOptions.Encoder is null) { // If the user hasn't explicitly configured the encoder, use the less strict encoder that does not encode all non-ASCII characters. jsonSerializerOptions = new JsonSerializerOptions(jsonSerializerOptions) { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; } return new SystemTextJsonOutputFormatter(jsonSerializerOptions); } /// <summary> /// Gets the <see cref="JsonSerializerOptions"/> used to configure the <see cref="JsonSerializer"/>. /// </summary> /// <remarks> /// A single instance of <see cref="SystemTextJsonOutputFormatter"/> is used for all JSON formatting. Any /// changes to the options will affect all output formatting. /// </remarks> public JsonSerializerOptions SerializerOptions { get; } /// <inheritdoc /> public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(selectedEncoding); var httpContext = context.HttpContext; // context.ObjectType reflects the declared model type when specified. // For polymorphic scenarios where the user declares a return type, but returns a derived type, // we want to serialize all the properties on the derived type. This keeps parity with // the behavior you get when the user does not declare the return type. // To enable this our best option is to check if the JsonTypeInfo for the declared type is valid, // if it is use it. If it isn't, serialize the value as 'object' and let JsonSerializer serialize it as necessary. JsonTypeInfo? jsonTypeInfo = null; if (context.ObjectType is not null) { var declaredTypeJsonInfo = SerializerOptions.GetTypeInfo(context.ObjectType); var runtimeType = context.Object?.GetType(); if (declaredTypeJsonInfo.ShouldUseWith(runtimeType)) { jsonTypeInfo = declaredTypeJsonInfo; } } if (selectedEncoding.CodePage == Encoding.UTF8.CodePage) { try { var responseWriter = httpContext.Response.BodyWriter; if (jsonTypeInfo is not null) { await JsonSerializer.SerializeAsync(responseWriter, context.Object, jsonTypeInfo, httpContext.RequestAborted); } else { await JsonSerializer.SerializeAsync(responseWriter, context.Object, SerializerOptions, httpContext.RequestAborted); } } catch (OperationCanceledException) when (context.HttpContext.RequestAborted.IsCancellationRequested) { } } else { // JsonSerializer only emits UTF8 encoded output, but we need to write the response in the encoding specified by // selectedEncoding var transcodingStream = Encoding.CreateTranscodingStream(httpContext.Response.Body, selectedEncoding, Encoding.UTF8, leaveOpen: true); ExceptionDispatchInfo? exceptionDispatchInfo = null; try { if (jsonTypeInfo is not null) { await JsonSerializer.SerializeAsync(transcodingStream, context.Object, jsonTypeInfo); } else { await JsonSerializer.SerializeAsync(transcodingStream, context.Object, SerializerOptions); } await transcodingStream.FlushAsync(); } catch (Exception ex) { // TranscodingStream may write to the inner stream as part of it's disposal. // We do not want this exception "ex" to be eclipsed by any exception encountered during the write. We will stash it and // explicitly rethrow it during the finally block. exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } finally { try { await transcodingStream.DisposeAsync(); } catch when (exceptionDispatchInfo != null) { } exceptionDispatchInfo?.Throw(); } } } }
SystemTextJsonOutputFormatter
csharp
NLog__NLog
tests/NLog.UnitTests/Layouts/CompoundLayoutTests.cs
{ "start": 1789, "end": 8589 }
public class ____ : NLogTestBase { [Fact] public void CodeCompoundLayoutIsRenderedCorrectly() { var compoundLayout = new CompoundLayout { Layouts = { new SimpleLayout("Long date - ${longdate}"), new SimpleLayout("|Before| "), new JsonLayout { SuppressSpaces = false, Attributes = { new JsonAttribute("short_date", "${shortdate}"), new JsonAttribute("message", "${message}"), } }, new SimpleLayout(" |After|"), new SimpleLayout("Last - ${level}") } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 20, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; const string expected = "Long date - 2010-01-20 12:34:56.0000|Before| { \"short_date\": \"2010-01-20\", \"message\": \"hello, world\" } |After|Last - Info"; var actual = compoundLayout.Render(logEventInfo); Assert.Equal(expected, actual); } [Fact] public void XmlCompoundLayoutWithVariables() { const string configXml = @" <nlog> <variable name='jsonLayoutv0.1'> <layout type='JsonLayout'> <attribute name='short_date' layout='${shortdate}' /> <attribute name='message' layout='${message}' /> </layout> </variable> <variable name='compoundLayoutv0.1'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='|Before| ' /> <layout type='${jsonLayoutv0.1}' /> <layout type='SimpleLayout' text=' |After|' /> </layout> </variable> <targets> <target name='compoundFile1' type='File' fileName='log.txt'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='|Before| ' /> <layout type='${jsonLayoutv0.1}' /> <layout type='SimpleLayout' text=' |After|' /> </layout> </target> <target name='compoundFile2' type='file' fileName='other.txt'> <layout type='${compoundLayoutv0.1}' /> </target> </targets> <rules> </rules> </nlog> "; var config = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("compoundFile1"); Assert.NotNull(target); var compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); var layouts = compoundLayout.Layouts; Assert.Equal(3, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(JsonLayout), layouts[1].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[2].GetType()); var innerJsonLayout = (JsonLayout)layouts[1]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); target = config.FindTargetByName<FileTarget>("compoundFile2"); Assert.NotNull(target); compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); layouts = compoundLayout.Layouts; Assert.Equal(3, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(JsonLayout), layouts[1].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[2].GetType()); innerJsonLayout = (JsonLayout)layouts[1]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); } [Fact] public void XmlCompoundLayoutIsRenderedCorrectly() { const string configXml = @" <nlog> <targets> <target name='compoundFile' type='File' fileName='log.txt'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='Long date - ${longdate}' /> <layout type='SimpleLayout' text='|Before| ' /> <layout type='JsonLayout' suppressSpaces='false'> <attribute name='short_date' layout='${shortdate}' /> <attribute name='message' layout='${message}' /> </layout> <layout type='SimpleLayout' text=' |After|' /> <layout type='SimpleLayout' text='Last - ${level}' /> </layout> </target> </targets> <rules> </rules> </nlog> "; var config = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("compoundFile"); Assert.NotNull(target); var compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); var layouts = compoundLayout.Layouts; Assert.NotNull(layouts); Assert.Equal(5, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[1].GetType()); var innerJsonLayout = (JsonLayout)layouts[2]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); Assert.Equal(typeof(SimpleLayout), layouts[3].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[4].GetType()); var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 20, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; const string expected = "Long date - 2010-01-20 12:34:56.0000|Before| { \"short_date\": \"2010-01-20\", \"message\": \"hello, world\" } |After|Last - Info"; var actual = compoundLayout.Render(logEventInfo); Assert.Equal(expected, actual); } } }
CompoundLayoutTests
csharp
dotnet__maui
src/Essentials/src/Vibration/Vibration.netstandard.tvos.watchos.macos.cs
{ "start": 90, "end": 521 }
partial class ____ : IVibration { public bool IsSupported => throw ExceptionUtils.NotSupportedOrImplementedException; void PlatformVibrate() => throw ExceptionUtils.NotSupportedOrImplementedException; void PlatformVibrate(TimeSpan duration) => throw ExceptionUtils.NotSupportedOrImplementedException; void PlatformCancel() => throw ExceptionUtils.NotSupportedOrImplementedException; } }
VibrationImplementation
csharp
dotnet__maui
src/Compatibility/Core/src/Windows/FileImageSourceHandler.cs
{ "start": 346, "end": 2490 }
public sealed class ____ : IImageSourceHandler, IIconElementHandler { public Task<Microsoft.UI.Xaml.Media.ImageSource> LoadImageAsync(ImageSource imagesource, CancellationToken cancellationToken = new CancellationToken()) { Microsoft.UI.Xaml.Media.ImageSource image = null; if (imagesource is FileImageSource filesource) { UpdateImageDirectory(filesource); string file = filesource.File; image = new BitmapImage(new Uri("ms-appx:///" + file)); } return Task.FromResult(image); } public Task<Microsoft.UI.Xaml.Controls.IconSource> LoadIconSourceAsync(ImageSource imagesource, CancellationToken cancellationToken = default(CancellationToken)) { Microsoft.UI.Xaml.Controls.IconSource image = null; if (imagesource is FileImageSource filesource) { UpdateImageDirectory(filesource); string file = filesource.File; image = new Microsoft.UI.Xaml.Controls.BitmapIconSource { UriSource = new Uri("ms-appx:///" + file) }; } return Task.FromResult(image); } public Task<IconElement> LoadIconElementAsync(ImageSource imagesource, CancellationToken cancellationToken = default(CancellationToken)) { IconElement image = null; if (imagesource is FileImageSource filesource) { UpdateImageDirectory(filesource); string file = filesource.File; image = new BitmapIcon { UriSource = new Uri("ms-appx:///" + file) }; } return Task.FromResult(image); } void UpdateImageDirectory(FileImageSource fileSource) { if (fileSource == null || fileSource.File == null) return; var currentApp = Application.Current; if (currentApp == null) return; var imageDirectory = currentApp.OnThisPlatform().GetImageDirectory(); if (!string.IsNullOrEmpty(imageDirectory)) { var filePath = fileSource.File; var directory = IOPath.GetDirectoryName(filePath); if (string.IsNullOrEmpty(directory) || !IOPath.GetFullPath(directory).Equals(IOPath.GetFullPath(imageDirectory), StringComparison.Ordinal)) { filePath = IOPath.Combine(imageDirectory, filePath); fileSource.File = filePath; } } } } }
FileImageSourceHandler
csharp
duplicati__duplicati
Duplicati/Library/Main/Backend/BackendManager.Handler.cs
{ "start": 268, "end": 332 }
partial class ____ { /// <summary> /// Wrapper
BackendManager
csharp
HangfireIO__Hangfire
src/Hangfire.NetCore/AspNetCore/AspNetCoreLogProvider.cs
{ "start": 851, "end": 1344 }
public class ____ : ILogProvider { private readonly ILoggerFactory _loggerFactory; public AspNetCoreLogProvider([NotNull] ILoggerFactory loggerFactory) { if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); _loggerFactory = loggerFactory; } public ILog GetLogger(string name) { return new AspNetCoreLog(_loggerFactory.CreateLogger(name)); } } }
AspNetCoreLogProvider
csharp
dotnet__aspire
src/Aspire.Hosting/IDistributedApplicationBuilder.cs
{ "start": 733, "end": 1203 }
interface ____ defining /// the resources which are orchestrated by the <see cref="DistributedApplication"/> when /// the app host is launched. /// </para> /// <para> /// To create an instance of the <see cref="IDistributedApplicationBuilder"/> interface /// developers should use the <see cref="DistributedApplication.CreateBuilder(string[])"/> /// method. Once the builder is created extension methods which target the <see cref="IDistributedApplicationBuilder"/> ///
for
csharp
MassTransit__MassTransit
src/Transports/MassTransit.ActiveMqTransport/ActiveMqTransport/ActiveMqHost.cs
{ "start": 114, "end": 3087 }
public class ____ : BaseHost, IActiveMqHost { readonly IActiveMqHostConfiguration _hostConfiguration; public ActiveMqHost(IActiveMqHostConfiguration hostConfiguration, IActiveMqBusTopology busTopology) : base(hostConfiguration, busTopology) { _hostConfiguration = hostConfiguration; Topology = busTopology; } public new IActiveMqBusTopology Topology { get; } public override HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter, Action<IReceiveEndpointConfigurator> configureEndpoint = null) { return ConnectReceiveEndpoint(definition, endpointNameFormatter, configureEndpoint); } public override HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IReceiveEndpointConfigurator> configureEndpoint = null) { return ConnectReceiveEndpoint(queueName, configureEndpoint); } public HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter = null, Action<IActiveMqReceiveEndpointConfigurator> configureEndpoint = null) { var queueName = definition.GetEndpointName(endpointNameFormatter ?? DefaultEndpointNameFormatter.Instance); return ConnectReceiveEndpoint(queueName, configurator => { _hostConfiguration.ApplyEndpointDefinition(configurator, definition); configureEndpoint?.Invoke(configurator); }); } public HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IActiveMqReceiveEndpointConfigurator> configure = null) { LogContext.SetCurrentIfNull(_hostConfiguration.LogContext); var configuration = _hostConfiguration.CreateReceiveEndpointConfiguration(queueName, configure); configuration.Validate().ThrowIfContainsFailure("The receive endpoint configuration is invalid:"); TransportLogMessages.ConnectReceiveEndpoint(configuration.InputAddress); configuration.Build(this); return ReceiveEndpoints.Start(queueName); } protected override void Probe(ProbeContext context) { context.Set(new { Type = "ActiveMQ", _hostConfiguration.Settings.Host, _hostConfiguration.Settings.Port, _hostConfiguration.Settings.Username, Password = new string('*', _hostConfiguration.Settings.Password.Length) }); _hostConfiguration.ConnectionContextSupervisor.Probe(context); } protected override IAgent[] GetAgentHandles() { return new IAgent[] { _hostConfiguration.ConnectionContextSupervisor }; } } }
ActiveMqHost
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Concurrency/ImmediateScheduler.cs
{ "start": 547, "end": 3011 }
public sealed class ____ : LocalScheduler { private static readonly Lazy<ImmediateScheduler> StaticInstance = new(static () => new ImmediateScheduler()); private ImmediateScheduler() { } /// <summary> /// Gets the singleton instance of the immediate scheduler. /// </summary> public static ImmediateScheduler Instance => StaticInstance.Value; /// <summary> /// Schedules an action to be executed. /// </summary> /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> /// <param name="state">State passed to the action to be executed.</param> /// <param name="action">Action to be executed.</param> /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception> public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } return action(new AsyncLockScheduler(), state); } /// <summary> /// Schedules an action to be executed after dueTime. /// </summary> /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> /// <param name="state">State passed to the action to be executed.</param> /// <param name="action">Action to be executed.</param> /// <param name="dueTime">Relative time after which to execute the action.</param> /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception> public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var dt = Scheduler.Normalize(dueTime); if (dt.Ticks > 0) { ConcurrencyAbstractionLayer.Current.Sleep(dt); } return action(new AsyncLockScheduler(), state); }
ImmediateScheduler
csharp
dotnet__aspire
src/Shared/DashboardConfigNames.cs
{ "start": 165, "end": 5303 }
internal static class ____ { public static readonly ConfigName DashboardFrontendUrlName = new(KnownConfigNames.AspNetCoreUrls); public static readonly ConfigName DashboardOtlpGrpcUrlName = new(KnownConfigNames.DashboardOtlpGrpcEndpointUrl); public static readonly ConfigName DashboardOtlpHttpUrlName = new(KnownConfigNames.DashboardOtlpHttpEndpointUrl); public static readonly ConfigName DashboardMcpUrlName = new(KnownConfigNames.DashboardMcpEndpointUrl); public static readonly ConfigName DashboardUnsecuredAllowAnonymousName = new(KnownConfigNames.DashboardUnsecuredAllowAnonymous); public static readonly ConfigName DashboardConfigFilePathName = new(KnownConfigNames.DashboardConfigFilePath); public static readonly ConfigName DashboardFileConfigDirectoryName = new(KnownConfigNames.DashboardFileConfigDirectory); public static readonly ConfigName DashboardAIDisabledName = new(KnownConfigNames.DashboardAIDisabled); public static readonly ConfigName ResourceServiceUrlName = new(KnownConfigNames.ResourceServiceEndpointUrl); public static readonly ConfigName ForwardedHeaders = new(KnownConfigNames.DashboardForwardedHeadersEnabled); public static readonly ConfigName DashboardOtlpAuthModeName = new("Dashboard:Otlp:AuthMode", "DASHBOARD__OTLP__AUTHMODE"); public static readonly ConfigName DashboardOtlpPrimaryApiKeyName = new("Dashboard:Otlp:PrimaryApiKey", "DASHBOARD__OTLP__PRIMARYAPIKEY"); public static readonly ConfigName DashboardOtlpSecondaryApiKeyName = new("Dashboard:Otlp:SecondaryApiKey", "DASHBOARD__OTLP__SECONDARYAPIKEY"); public static readonly ConfigName DashboardMcpPublicUrlName = new("Dashboard:Mcp:PublicUrl", "DASHBOARD__MCP__PUBLICURL"); public static readonly ConfigName DashboardMcpAuthModeName = new("Dashboard:Mcp:AuthMode", "DASHBOARD__MCP__AUTHMODE"); public static readonly ConfigName DashboardMcpPrimaryApiKeyName = new("Dashboard:Mcp:PrimaryApiKey", "DASHBOARD__MCP__PRIMARYAPIKEY"); public static readonly ConfigName DashboardMcpDisableName = new("Dashboard:Mcp:Disabled", "DASHBOARD__MCP__DISABLED"); public static readonly ConfigName DashboardOtlpSuppressUnsecuredTelemetryMessageName = new("Dashboard:Otlp:SuppressUnsecuredTelemetryMessage", "DASHBOARD__OTLP__SUPPRESSUNSECUREDTELEMETRYMESSAGE"); public static readonly ConfigName DashboardOtlpCorsAllowedOriginsKeyName = new("Dashboard:Otlp:Cors:AllowedOrigins", "DASHBOARD__OTLP__CORS__ALLOWEDORIGINS"); public static readonly ConfigName DashboardOtlpCorsAllowedHeadersKeyName = new("Dashboard:Otlp:Cors:AllowedHeaders", "DASHBOARD__OTLP__CORS__ALLOWEDHEADERS"); public static readonly ConfigName DashboardOtlpAllowedCertificatesName = new("Dashboard:Otlp:AllowedCertificates", "DASHBOARD__OTLP__ALLOWEDCERTIFICATES"); public static readonly ConfigName DashboardFrontendAuthModeName = new("Dashboard:Frontend:AuthMode", "DASHBOARD__FRONTEND__AUTHMODE"); public static readonly ConfigName DashboardFrontendBrowserTokenName = new("Dashboard:Frontend:BrowserToken", "DASHBOARD__FRONTEND__BROWSERTOKEN"); public static readonly ConfigName DashboardFrontendMaxConsoleLogCountName = new("Dashboard:Frontend:MaxConsoleLogCount", "DASHBOARD__FRONTEND__MAXCONSOLELOGCOUNT"); public static readonly ConfigName DashboardFrontendPublicUrlName = new("Dashboard:Frontend:PublicUrl", "DASHBOARD__FRONTEND__PUBLICURL"); public static readonly ConfigName ResourceServiceClientAuthModeName = new("Dashboard:ResourceServiceClient:AuthMode", "DASHBOARD__RESOURCESERVICECLIENT__AUTHMODE"); public static readonly ConfigName ResourceServiceClientCertificateSourceName = new("Dashboard:ResourceServiceClient:ClientCertificate:Source", "DASHBOARD__RESOURCESERVICECLIENT__CLIENTCERTIFICATE__SOURCE"); public static readonly ConfigName ResourceServiceClientCertificateFilePathName = new("Dashboard:ResourceServiceClient:ClientCertificate:FilePath", "DASHBOARD__RESOURCESERVICECLIENT__CLIENTCERTIFICATE__FILEPATH"); public static readonly ConfigName ResourceServiceClientCertificateSubjectName = new("Dashboard:ResourceServiceClient:ClientCertificate:Subject", "DASHBOARD__RESOURCESERVICECLIENT__CLIENTCERTIFICATE__SUBJECT"); public static readonly ConfigName ResourceServiceClientApiKeyName = new("Dashboard:ResourceServiceClient:ApiKey", "DASHBOARD__RESOURCESERVICECLIENT__APIKEY"); public static readonly ConfigName DebugSessionPortName = new("Dashboard:DebugSession:Port", "DASHBOARD__DEBUGSESSION__PORT"); public static readonly ConfigName DebugSessionServerCertificateName = new("Dashboard:DebugSession:ServerCertificate", "DASHBOARD__DEBUGSESSION__SERVERCERTIFICATE"); public static readonly ConfigName DebugSessionTokenName = new("Dashboard:DebugSession:Token", "DASHBOARD__DEBUGSESSION__TOKEN"); public static readonly ConfigName DebugSessionTelemetryOptOutName = new("Dashboard:DebugSession:TelemetryOptOut", "DASHBOARD__DEBUGSESSION__TELEMETRYOPTOUT"); public static readonly ConfigName UIDisableResourceGraphName = new("Dashboard:UI:DisableResourceGraph", "DASHBOARD__UI__DISABLERESOURCEGRAPH");
DashboardConfigNames
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui.Camera/CameraManager.macios.cs
{ "start": 12608, "end": 13090 }
sealed class ____ : AVCapturePhotoCaptureDelegate { readonly TaskCompletionSource<CapturePhotoResult> taskCompletionSource = new(); public Task<CapturePhotoResult> Task => taskCompletionSource.Task; public override void DidFinishProcessingPhoto(AVCapturePhotoOutput output, AVCapturePhoto photo, NSError? error) { taskCompletionSource.TrySetResult(new() { Output = output, Photo = photo, Error = error }); } }
AVCapturePhotoCaptureDelegateWrapper
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls/Automation/ValuePatternIdentifiers.cs
{ "start": 188, "end": 689 }
public static class ____ { /// <summary> /// Identifies <see cref="IValueProvider.IsReadOnly"/> automation property. /// </summary> public static AutomationProperty IsReadOnlyProperty { get; } = new AutomationProperty(); /// <summary> /// Identifies <see cref="IValueProvider.Value"/> automation property. /// </summary> public static AutomationProperty ValueProperty { get; } = new AutomationProperty(); } }
ValuePatternIdentifiers
csharp
dotnet__extensions
test/Libraries/Microsoft.AspNetCore.Diagnostics.Middleware.Tests/Logging/HttpLoggingServiceExtensionsTests.cs
{ "start": 518, "end": 3928 }
public class ____ { [Fact] public void ShouldThrow_WhenArgsNull() { var services = Mock.Of<IServiceCollection>(); Assert.Throws<ArgumentNullException>(static () => HttpLoggingServiceCollectionExtensions.AddHttpLogEnricher<TestHttpLogEnricher>(null!)); Assert.Throws<ArgumentNullException>( () => HttpLoggingServiceCollectionExtensions.AddHttpLoggingRedaction(services, (IConfigurationSection)null!)); } [Fact] public void AddHttpLogging_WhenConfiguredUsingConfigurationSection_IsCorrect() { var services = new ServiceCollection(); var builder = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string?>("HttpLogging:RequestPathLoggingMode", "Structured"), new KeyValuePair<string, string?>("HttpLogging:RequestPathParameterRedactionMode","None"), new KeyValuePair<string, string?>("HttpLogging:ExcludePathStartsWith:[0]","/path0toexclude"), new KeyValuePair<string, string?>("HttpLogging:ExcludePathStartsWith:[1]","/path1toexclude"), }); var configuration = builder.Build(); services.AddHttpLoggingRedaction(configuration.GetSection("HttpLogging")); using var provider = services.BuildServiceProvider(); var options = provider.GetRequiredService<IOptions<LoggingRedactionOptions>>().Value; Assert.Equal(IncomingPathLoggingMode.Structured, options.RequestPathLoggingMode); Assert.Equal(HttpRouteParameterRedactionMode.None, options.RequestPathParameterRedactionMode); Assert.Contains("/path0toexclude", options.ExcludePathStartsWith); Assert.Contains("/path1toexclude", options.ExcludePathStartsWith); } [Fact] public void AddHttpLogging_CanConfigureDataClasses() { var services = new ServiceCollection(); services.AddHttpLoggingRedaction(o => { o.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", new DataClassification("Taxonomy1", "Value1") }, }; o.RequestHeadersDataClasses = new Dictionary<string, DataClassification> { { "two", new DataClassification("Taxonomy2", "Value2") }, }; o.ResponseHeadersDataClasses = new Dictionary<string, DataClassification> { { "three", new DataClassification("Taxonomy3", "Value3") }, }; }); using var provider = services.BuildServiceProvider(); var options = provider.GetRequiredService<IOptions<LoggingRedactionOptions>>().Value; Assert.Single(options.RouteParameterDataClasses); Assert.Equal("Taxonomy1", options.RouteParameterDataClasses["one"].TaxonomyName); Assert.Equal("Value1", options.RouteParameterDataClasses["one"].Value); Assert.Single(options.RequestHeadersDataClasses); Assert.Equal("Taxonomy2", options.RequestHeadersDataClasses["two"].TaxonomyName); Assert.Equal("Value2", options.RequestHeadersDataClasses["two"].Value); Assert.Single(options.ResponseHeadersDataClasses); Assert.Equal("Taxonomy3", options.ResponseHeadersDataClasses["three"].TaxonomyName); Assert.Equal("Value3", options.ResponseHeadersDataClasses["three"].Value); } } #endif
HttpLoggingServiceExtensionsTests
csharp
dotnet__efcore
src/EFCore.Relational/Query/RelationalEvaluatableExpressionFilterDependencies.cs
{ "start": 1558, "end": 2838 }
public sealed record ____ { /// <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> /// <remarks> /// Do not call this constructor directly from either provider or application code as it may change /// as new dependencies are added. Instead, use this type in your constructor so that an instance /// will be created and injected automatically by the dependency injection container. To create /// an instance with some dependent services replaced, first resolve the object from the dependency /// injection container, then replace selected services using the C# 'with' operator. Do not call /// the constructor at any point in this process. /// </remarks> [EntityFrameworkInternal] public RelationalEvaluatableExpressionFilterDependencies() { } }
RelationalEvaluatableExpressionFilterDependencies
csharp
dotnet__extensions
test/Libraries/Microsoft.AspNetCore.Testing.Tests/FakeCertificateFactoryTests.cs
{ "start": 316, "end": 1508 }
public class ____ { [Fact] public void Create_CreatesCertificate() { using var certificate = FakeSslCertificateFactory.CreateSslCertificate(); Assert.Equal("CN=dotnet-extensions-self-signed-unit-test-certificate", certificate.SubjectName.Name); Assert.Equal("localhost", certificate.GetNameInfo(X509NameType.DnsFromAlternativeName, false)); Assert.True(DateTime.Now > certificate.NotBefore + TimeSpan.FromHours(1)); Assert.True(DateTime.Now < certificate.NotAfter - TimeSpan.FromHours(1)); Assert.False(certificate.Extensions.OfType<X509EnhancedKeyUsageExtension>().Single().Critical); } [ConditionalTheory] [OSSkipCondition(OperatingSystems.Linux)] [InlineData(false)] [InlineData(true)] public void GenerateRsa_RunsOnWindows_GeneratesRsa(bool runsOnWindows) { Assert.NotNull(FakeSslCertificateFactory.GenerateRsa(runsOnWindows)); } [ConditionalFact] [OSSkipCondition(OperatingSystems.Windows)] public void GenerateRsa_DoesNotRunOnWindows_GeneratesRsa() { Assert.NotNull(FakeSslCertificateFactory.GenerateRsa(runsOnWindows: false)); } }
FakeCertificateFactoryTests
csharp
microsoft__PowerToys
src/modules/MouseWithoutBorders/App/Class/NativeMethods.cs
{ "start": 31395, "end": 32259 }
internal struct ____ { internal uint dwSize; internal uint cntUsage; internal uint th32ProcessID; internal IntPtr th32DefaultHeapID; internal uint th32ModuleID; internal uint cntThreads; internal uint th32ParentProcessID; internal int pcPriClassBase; internal uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] internal string szExeFile; } internal const uint TH32CS_SNAPPROCESS = 0x00000002; // internal static int INVALID_HANDLE_VALUE = -1; [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr hSnapshot); [StructLayout(LayoutKind.Sequential)]
PROCESSENTRY32
csharp
dotnet__aspire
src/Aspire.Dashboard/ServiceClient/DashboardClient.cs
{ "start": 33538, "end": 33611 }
private enum ____ { Retry, DoNotRetry } }
RetryResult
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Evaluators/AnomalyDetectionEvaluator.cs
{ "start": 37068, "end": 38453 }
partial class ____ { [TlcModule.EntryPoint(Name = "Models.AnomalyDetectionEvaluator", Desc = "Evaluates an anomaly detection scored dataset.")] public static CommonOutputs.CommonEvaluateOutput AnomalyDetection(IHostEnvironment env, AnomalyDetectionMamlEvaluator.Arguments input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register("EvaluateAnomalyDetection"); host.CheckValue(input, nameof(input)); EntryPointUtils.CheckInputArgs(host, input); string label; string weight; string name; MatchColumns(host, input, out label, out weight, out name); IMamlEvaluator evaluator = new AnomalyDetectionMamlEvaluator(host, input); var data = new RoleMappedData(input.Data, label, null, null, weight, name); var metrics = evaluator.Evaluate(data); var warnings = ExtractWarnings(host, metrics); var overallMetrics = ExtractOverallMetrics(host, metrics, evaluator); var perInstanceMetrics = evaluator.GetPerInstanceMetrics(data); return new CommonOutputs.CommonEvaluateOutput() { Warnings = warnings, OverallMetrics = overallMetrics, PerInstanceMetrics = perInstanceMetrics }; } } }
Evaluate
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Tools/GitReleaseManager/AddAssets/GitReleaseManagerAssetsAdderTests.cs
{ "start": 464, "end": 21080 }
public sealed class ____ { [Fact] public void Should_Throw_If_UserName_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UserName = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "userName"); } [Fact] public void Should_Throw_If_Password_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Password = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "password"); } [Fact] public void Should_Throw_If_Token_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Token = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "token"); } [Fact] public void Should_Throw_If_Owner_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Owner = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "owner"); } [Fact] public void Should_Throw_If_Owner_Is_Null_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Owner = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "owner"); } [Fact] public void Should_Throw_If_Repository_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Repository = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "repository"); } [Fact] public void Should_Throw_If_Repository_Is_Null_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Repository = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "repository"); } [Fact] public void Should_Throw_If_TagName_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.TagName = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "tagName"); } [Fact] public void Should_Throw_If_TagName_Is_Null_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.TagName = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "tagName"); } [Fact] public void Should_Throw_If_Assets_Is_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Assets = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "assets"); } [Fact] public void Should_Throw_If_Assets_Is_Null_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Assets = string.Empty; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "assets"); } [Fact] public void Should_Throw_If_Settings_Are_Null() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_Settings_Are_Null_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_GitReleaseManager_Executable_Was_Not_Found() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Could not locate executable."); } [Fact] public void Should_Throw_If_GitReleaseManager_Executable_Was_Not_Found_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Could not locate executable."); } [Theory] [InlineData("/bin/tools/GitReleaseManager/GitReleaseManager.exe", "/bin/tools/GitReleaseManager/GitReleaseManager.exe")] [InlineData("./tools/GitReleaseManager/GitReleaseManager.exe", "/Working/tools/GitReleaseManager/GitReleaseManager.exe")] public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Theory] [InlineData("/bin/tools/GitReleaseManager/GitReleaseManager.exe", "/bin/tools/GitReleaseManager/GitReleaseManager.exe")] [InlineData("./tools/GitReleaseManager/GitReleaseManager.exe", "/Working/tools/GitReleaseManager/GitReleaseManager.exe")] public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_When_Using_Token(string toolPath, string expected) { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/GitReleaseManager/GitReleaseManager.exe", "C:/GitReleaseManager/GitReleaseManager.exe")] public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/GitReleaseManager/GitReleaseManager.exe", "C:/GitReleaseManager/GitReleaseManager.exe")] public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_On_Windows_When_Using_Token(string toolPath, string expected) { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Process was not started."); } [Fact] public void Should_Throw_If_Process_Was_Not_Started_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Process was not started."); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Process returned an error (exit code 1)."); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "GitReleaseManager: Process returned an error (exit code 1)."); } [Fact] public void Should_Find_GitReleaseManager_Executable_If_Tool_Path_Not_Provided() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/GitReleaseManager.exe", result.Path.FullPath); } [Fact] public void Should_Find_GitReleaseManager_Executable_If_Tool_Path_Not_Provided_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/GitReleaseManager.exe", result.Path.FullPath); } [Fact] public void Should_Add_Mandatory_Arguments() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\"", result.Args); } [Fact] public void Should_Add_Mandatory_Arguments_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\"", result.Args); } [Fact] public void Should_Add_TargetDirectory_To_Arguments_If_Set() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.TargetDirectory = @"/temp"; // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" -d \"/temp\"", result.Args); } [Fact] public void Should_Add_TargetDirectory_To_Arguments_If_Set_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.TargetDirectory = @"/temp"; // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" -d \"/temp\"", result.Args); } [Fact] public void Should_Add_LogFilePath_To_Arguments_If_Set() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.LogFilePath = @"/temp/log.txt"; // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "-l \"/temp/log.txt\"", result.Args); } [Fact] public void Should_Add_LogFilePath_To_Arguments_If_Set_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.LogFilePath = @"/temp/log.txt"; // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "-l \"/temp/log.txt\"", result.Args); } [Fact] public void Should_Add_Debug_To_Arguments_If_Set() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.Debug = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--debug", result.Args); } [Fact] public void Should_All_Debug_To_Arguments_If_Set_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.Debug = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--debug", result.Args); } [Fact] public void Should_Add_Verbose_To_Arguments_If_Set() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.Verbose = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--verbose", result.Args); } [Fact] public void Should_All_Verbose_To_Arguments_If_Set_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.Verbose = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--verbose", result.Args); } [Fact] public void Should_Add_NoLogo_To_Arguments_If_Set() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.Settings.NoLogo = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset -u \"bob\" -p \"password\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--no-logo", result.Args); } [Fact] public void Should_All_NoLogo_To_Arguments_If_Set_When_Using_Token() { // Given var fixture = new GitReleaseManagerAssetsAdderFixture(); fixture.UseToken(); fixture.Settings.NoLogo = true; // When var result = fixture.Run(); // Then Assert.Equal("addasset --token \"token\" " + "-o \"repoOwner\" -r \"repo\" -t \"0.1.0\" " + "-a \"/temp/asset1.txt\" " + "--no-logo", result.Args); } } } }
TheAddAssetsMethod
csharp
RicoSuter__NSwag
src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs
{ "start": 1230, "end": 1529 }
class ____ of the given assembly.</summary> /// <param name="assembly">The assembly.</param> /// <returns>The controller classes.</returns> public static IEnumerable<Type> GetControllerClasses(Assembly assembly) { // TODO: Move to IControllerClassLoader
types
csharp
MassTransit__MassTransit
tests/MassTransit.RabbitMqTransport.Tests/Retry_Specs.cs
{ "start": 3628, "end": 5213 }
public class ____ : RabbitMqTestFixture { [Test] public async Task Should_stop_after_limit_exceeded() { var pingId = NewId.NextGuid(); _attempts[pingId] = 0; Task<ConsumeContext<Fault<PingMessage>>> handler = await ConnectPublishHandler<Fault<PingMessage>>(context => context.Message.Message.CorrelationId == pingId); await Bus.Publish(new PingMessage(pingId)); ConsumeContext<Fault<PingMessage>> handled = await handler; Assert.That(handled.Headers.Get<int>(MessageHeaders.FaultRetryCount), Is.GreaterThan(0)); await InactivityTask; Assert.That(_attempts[pingId], Is.LessThanOrEqualTo(_limit + 1)); } readonly int _limit; readonly IDictionary<Guid, int> _attempts; public When_specifying_redelivery_at_the_bus_level() { _limit = 1; _attempts = new Dictionary<Guid, int>(); } protected override void ConfigureRabbitMqBus(IRabbitMqBusFactoryConfigurator configurator) { configurator.UseDelayedMessageScheduler(); configurator.UseScheduledRedelivery(x => x.Interval(_limit, TimeSpan.FromSeconds(1))); } protected override void ConfigureRabbitMqReceiveEndpoint(IRabbitMqReceiveEndpointConfigurator configurator) { configurator.Consumer(() => new RetryLimitConsumer(_attempts)); } } [TestFixture] [Category("Flaky")]
When_specifying_redelivery_at_the_bus_level
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Rendering/Composition/Server/ServerRenderResource.cs
{ "start": 554, "end": 3386 }
internal class ____ : SimpleServerObject, IServerRenderResource, IDisposable { private bool _pendingInvalidation; private bool _disposed; public bool IsDisposed => _disposed; private RefCountingSmallDictionary<IServerRenderResourceObserver> _observers; public SimpleServerRenderResource(ServerCompositor compositor) : base(compositor) { } protected new void SetValue<T>(CompositionProperty prop, ref T field, T value) => SetValue(ref field, value); protected void SetValue<T>(ref T field, T value) { if (EqualityComparer<T>.Default.Equals(field, value)) return; if (_disposed) { field = value; return; } if (field is IServerRenderResource oldChild) oldChild.RemoveObserver(this); else if (field is IServerRenderResource[] oldChildren) { foreach (var ch in oldChildren) ch?.RemoveObserver(this); } field = value; if (field is IServerRenderResource newChild) newChild.AddObserver(this); else if (field is IServerRenderResource[] newChildren) { foreach (var ch in newChildren) ch.AddObserver(this); } Invalidated(); } protected void Invalidated() { // This is needed to avoid triggering on multiple property changes if (!_pendingInvalidation) { _pendingInvalidation = true; Compositor.EnqueueRenderResourceForInvalidation(this); PropertyChanged(); } } protected override void ValuesInvalidated() { Invalidated(); base.ValuesInvalidated(); } protected void RemoveObserversFromProperty<T>(ref T field) { (field as IServerRenderResource)?.RemoveObserver(this); } public virtual void Dispose() { _disposed = true; // TODO: dispose once we implement pooling _observers = default; } public virtual void DependencyQueuedInvalidate(IServerRenderResource sender) => Compositor.EnqueueRenderResourceForInvalidation(this); protected virtual void PropertyChanged() { } public void AddObserver(IServerRenderResourceObserver observer) { Debug.Assert(!_disposed); if(_disposed) return; _observers.Add(observer); } public void RemoveObserver(IServerRenderResourceObserver observer) { if (_disposed) return; _observers.Remove(observer); } public virtual void QueuedInvalidate() { _pendingInvalidation = false; foreach (var observer in _observers) observer.Key.DependencyQueuedInvalidate(this); } }
SimpleServerRenderResource
csharp
duplicati__duplicati
Duplicati/Library/Backend/OAuthHelper/RetryAfterHelper.cs
{ "start": 1461, "end": 1541 }
class ____ manage the Retry-After header for a given URL. /// </summary>
to
csharp
dotnet__aspnetcore
src/Features/JsonPatch.SystemTextJson/test/TestObjectModels/HeterogenousCollection.cs
{ "start": 677, "end": 746 }
public class ____ { public IList<Shape> Items { get; set; } }
Canvas