Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5