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 | GtkSharp__GtkSharp | Source/Libs/CairoSharp/ScaledFont.cs | {
"start": 1250,
"end": 3528
} | public class ____ : IDisposable
{
protected IntPtr handle = IntPtr.Zero;
internal ScaledFont (IntPtr handle, bool owner)
{
if (handle == IntPtr.Zero)
throw new ArgumentException ("handle should not be NULL", "handle");
this.handle = handle;
if (!owner)
NativeMethods.cairo_scaled_font_reference (handle);
if (CairoDebug.Enabled)
CairoDebug.OnAllocated (handle);
}
public ScaledFont (FontFace fontFace, Matrix matrix, Matrix ctm, FontOptions options)
: this (NativeMethods.cairo_scaled_font_create (fontFace.Handle, matrix, ctm, options.Handle), true)
{
}
~ScaledFont ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public FontExtents FontExtents {
get {
CheckDisposed ();
FontExtents extents;
NativeMethods.cairo_scaled_font_extents (handle, out extents);
return extents;
}
}
public Matrix FontMatrix {
get {
CheckDisposed ();
Matrix m;
NativeMethods.cairo_scaled_font_get_font_matrix (handle, out m);
return m;
}
}
public FontType FontType {
get {
CheckDisposed ();
return NativeMethods.cairo_scaled_font_get_type (handle);
}
}
public TextExtents GlyphExtents (Glyph[] glyphs)
{
CheckDisposed ();
IntPtr ptr = Context.FromGlyphToUnManagedMemory (glyphs);
TextExtents extents;
NativeMethods.cairo_scaled_font_glyph_extents (handle, ptr, glyphs.Length, out extents);
Marshal.FreeHGlobal (ptr);
return extents;
}
public Status Status
{
get {
CheckDisposed ();
return NativeMethods.cairo_scaled_font_status (handle);
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposing || CairoDebug.Enabled)
CairoDebug.OnDisposed<ScaledFont> (handle, disposing);
if (handle == IntPtr.Zero)
return;
NativeMethods.cairo_scaled_font_destroy (handle);
handle = IntPtr.Zero;
}
void CheckDisposed ()
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("Object has already been disposed");
}
[Obsolete]
protected void Reference ()
{
CheckDisposed ();
NativeMethods.cairo_scaled_font_reference (handle);
}
}
}
| ScaledFont |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Cluster/MemberInfoTests.cs | {
"start": 350,
"end": 1798
} | public class ____ {
[Test]
public void member_with_dns_endpoint_should_equal() {
var ipAddress = "127.0.0.1";
var port = 1113;
var memberWithDnsEndPoint = MemberInfo.Initial(Guid.Empty, DateTime.UtcNow,
VNodeState.Unknown, true,
new DnsEndPoint(ipAddress, port),
new DnsEndPoint(ipAddress, port),
new DnsEndPoint(ipAddress, port),
new DnsEndPoint(ipAddress, port),
new DnsEndPoint(ipAddress, port),
null, 0, 0,
0, false);
var ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
var dnsEndPoint = new DnsEndPoint(ipAddress, port);
Assert.True(memberWithDnsEndPoint.Is(ipEndPoint));
Assert.True(memberWithDnsEndPoint.Is(dnsEndPoint));
}
[Test]
public void member_with_ip_endpoint_should_equal() {
var ipAddress = "127.0.0.1";
var port = 1113;
var memberWithDnsEndPoint = MemberInfo.Initial(Guid.Empty, DateTime.UtcNow,
VNodeState.Unknown, true,
new IPEndPoint(IPAddress.Parse(ipAddress), port),
new IPEndPoint(IPAddress.Parse(ipAddress), port),
new IPEndPoint(IPAddress.Parse(ipAddress), port),
new IPEndPoint(IPAddress.Parse(ipAddress), port),
new IPEndPoint(IPAddress.Parse(ipAddress), port),
null, 0, 0, 0, false);
var ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
var dnsEndPoint = new DnsEndPoint(ipAddress, port);
Assert.True(memberWithDnsEndPoint.Is(ipEndPoint));
Assert.True(memberWithDnsEndPoint.Is(dnsEndPoint));
}
}
| MemberInfoTests |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/ContainerTests/Common_Tests/Common_ConsumeContext.cs | {
"start": 446,
"end": 2851
} | public class ____ :
InMemoryContainerTestFixture
{
Task<ConsumeContext> ConsumeContext => ServiceProvider.GetRequiredService<TaskCompletionSource<ConsumeContext>>().Task;
Task<IPublishEndpoint> PublishEndpoint => ServiceProvider.GetRequiredService<TaskCompletionSource<IPublishEndpoint>>().Task;
Task<ISendEndpointProvider> SendEndpointProvider => ServiceProvider.GetRequiredService<TaskCompletionSource<ISendEndpointProvider>>().Task;
[Test]
public async Task Should_provide_the_consume_context()
{
await InputQueueSendEndpoint.Send(new PingMessage());
var consumeContext = await ConsumeContext;
Assert.That(consumeContext.TryGetPayload(out MessageConsumeContext<PingMessage> _), "Is MessageConsumeContext");
var publishEndpoint = await PublishEndpoint;
var sendEndpointProvider = await SendEndpointProvider;
Assert.Multiple(() =>
{
Assert.That(ReferenceEquals(publishEndpoint, sendEndpointProvider), "ReferenceEquals(publishEndpoint, sendEndpointProvider)");
Assert.That(ReferenceEquals(consumeContext, sendEndpointProvider), "ReferenceEquals(messageConsumeContext, sendEndpointProvider)");
});
}
protected override IServiceCollection ConfigureServices(IServiceCollection collection)
{
TaskCompletionSource<ConsumeContext> pingTask = GetTask<ConsumeContext>();
TaskCompletionSource<IPublishEndpoint> sendEndpointProviderTask = GetTask<IPublishEndpoint>();
TaskCompletionSource<ISendEndpointProvider> publishEndpointTask = GetTask<ISendEndpointProvider>();
return collection.AddSingleton(pingTask)
.AddSingleton(sendEndpointProviderTask)
.AddSingleton(publishEndpointTask)
.AddScoped<IService, Service>()
.AddScoped<IAnotherService, AnotherService>();
}
protected override void ConfigureMassTransit(IBusRegistrationConfigurator configurator)
{
configurator.AddConsumer<DependentConsumer>();
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.ConfigureConsumers(BusRegistrationContext);
}
}
| Common_ConsumeContext |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Contexts/FaultedActivityOptions.cs | {
"start": 74,
"end": 1008
} | public interface ____
{
/// <summary>
/// When specified, uses the scheduler to delay execution of the next activity by the specified duration
/// </summary>
TimeSpan? Delay { set; }
/// <summary>
/// Add or update the variables on the routing slip with the specified object (properties are mapped to variables)
/// </summary>
/// <param name="variables"></param>
void SetVariables(object variables);
/// <summary>
/// Add or update the variables on the routing slip with the specified values
/// </summary>
/// <param name="variables"></param>
void SetVariables(IEnumerable<KeyValuePair<string, object>> variables);
/// <summary>
/// Add or update the variable on the routing slip with the specified object
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void SetVariable(string key, object value);
}
| FaultedActivityOptions |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/DotNet/DotNet.Generated.cs | {
"start": 866405,
"end": 874774
} | partial class ____
{
#region PackageName
/// <inheritdoc cref="DotNetToolInstallSettings.PackageName"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.PackageName))]
public static T SetPackageName<T>(this T o, string v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.PackageName, v));
/// <inheritdoc cref="DotNetToolInstallSettings.PackageName"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.PackageName))]
public static T ResetPackageName<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.PackageName));
#endregion
#region Sources
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T SetSources<T>(this T o, params string[] v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T SetSources<T>(this T o, IEnumerable<string> v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T AddSources<T>(this T o, params string[] v) where T : DotNetToolInstallSettings => o.Modify(b => b.AddCollection(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T AddSources<T>(this T o, IEnumerable<string> v) where T : DotNetToolInstallSettings => o.Modify(b => b.AddCollection(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T RemoveSources<T>(this T o, params string[] v) where T : DotNetToolInstallSettings => o.Modify(b => b.RemoveCollection(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T RemoveSources<T>(this T o, IEnumerable<string> v) where T : DotNetToolInstallSettings => o.Modify(b => b.RemoveCollection(() => o.Sources, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Sources"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Sources))]
public static T ClearSources<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.ClearCollection(() => o.Sources));
#endregion
#region ConfigFile
/// <inheritdoc cref="DotNetToolInstallSettings.ConfigFile"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.ConfigFile))]
public static T SetConfigFile<T>(this T o, string v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.ConfigFile, v));
/// <inheritdoc cref="DotNetToolInstallSettings.ConfigFile"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.ConfigFile))]
public static T ResetConfigFile<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.ConfigFile));
#endregion
#region Framework
/// <inheritdoc cref="DotNetToolInstallSettings.Framework"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Framework))]
public static T SetFramework<T>(this T o, string v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Framework, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Framework"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Framework))]
public static T ResetFramework<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.Framework));
#endregion
#region Global
/// <inheritdoc cref="DotNetToolInstallSettings.Global"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Global))]
public static T SetGlobal<T>(this T o, bool? v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Global, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Global"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Global))]
public static T ResetGlobal<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.Global));
/// <inheritdoc cref="DotNetToolInstallSettings.Global"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Global))]
public static T EnableGlobal<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Global, true));
/// <inheritdoc cref="DotNetToolInstallSettings.Global"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Global))]
public static T DisableGlobal<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Global, false));
/// <inheritdoc cref="DotNetToolInstallSettings.Global"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Global))]
public static T ToggleGlobal<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Global, !o.Global));
#endregion
#region ToolInstallationPath
/// <inheritdoc cref="DotNetToolInstallSettings.ToolInstallationPath"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.ToolInstallationPath))]
public static T SetToolInstallationPath<T>(this T o, string v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.ToolInstallationPath, v));
/// <inheritdoc cref="DotNetToolInstallSettings.ToolInstallationPath"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.ToolInstallationPath))]
public static T ResetToolInstallationPath<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.ToolInstallationPath));
#endregion
#region Verbosity
/// <inheritdoc cref="DotNetToolInstallSettings.Verbosity"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Verbosity))]
public static T SetVerbosity<T>(this T o, DotNetVerbosity v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Verbosity, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Verbosity"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Verbosity))]
public static T ResetVerbosity<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.Verbosity));
#endregion
#region Version
/// <inheritdoc cref="DotNetToolInstallSettings.Version"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Version))]
public static T SetVersion<T>(this T o, string v) where T : DotNetToolInstallSettings => o.Modify(b => b.Set(() => o.Version, v));
/// <inheritdoc cref="DotNetToolInstallSettings.Version"/>
[Pure] [Builder(Type = typeof(DotNetToolInstallSettings), Property = nameof(DotNetToolInstallSettings.Version))]
public static T ResetVersion<T>(this T o) where T : DotNetToolInstallSettings => o.Modify(b => b.Remove(() => o.Version));
#endregion
}
#endregion
#region DotNetToolRestoreSettingsExtensions
/// <inheritdoc cref="DotNetTasks.DotNetToolRestore(Nuke.Common.Tools.DotNet.DotNetToolRestoreSettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static | DotNetToolInstallSettingsExtensions |
csharp | ServiceStack__ServiceStack.Text | src/ServiceStack.Text/HttpMethods.cs | {
"start": 60,
"end": 1439
} | public static class ____
{
static readonly string[] allVerbs = {
"OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", // RFC 2616
"PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", // RFC 2518
"VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
"MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY", // RFC 3253
"ORDERPATCH", // RFC 3648
"ACL", // RFC 3744
"PATCH", // https://datatracker.ietf.org/doc/draft-dusseault-http-patch/
"SEARCH", // https://datatracker.ietf.org/doc/draft-reschke-webdav-search/
"BCOPY", "BDELETE", "BMOVE", "BPROPFIND", "BPROPPATCH", "NOTIFY",
"POLL", "SUBSCRIBE", "UNSUBSCRIBE" //MS Exchange WebDav: http://msdn.microsoft.com/en-us/library/aa142917.aspx
};
public static HashSet<string> AllVerbs = new(allVerbs);
public static bool Exists(string httpMethod) => AllVerbs.Contains(httpMethod.ToUpper());
public static bool HasVerb(string httpVerb) => Exists(httpVerb);
public const string Get = "GET";
public const string Put = "PUT";
public const string Post = "POST";
public const string Delete = "DELETE";
public const string Options = "OPTIONS";
public const string Head = "HEAD";
public const string Patch = "PATCH";
} | HttpMethods |
csharp | MaterialDesignInXAML__MaterialDesignInXamlToolkit | src/MaterialDesignColors.Wpf/Recommended/DeepOrangeSwatch.cs | {
"start": 73,
"end": 2496
} | public class ____ : ISwatch
{
public static Color DeepOrange50 { get; } = (Color)ColorConverter.ConvertFromString("#FBE9E7");
public static Color DeepOrange100 { get; } = (Color)ColorConverter.ConvertFromString("#FFCCBC");
public static Color DeepOrange200 { get; } = (Color)ColorConverter.ConvertFromString("#FFAB91");
public static Color DeepOrange300 { get; } = (Color)ColorConverter.ConvertFromString("#FF8A65");
public static Color DeepOrange400 { get; } = (Color)ColorConverter.ConvertFromString("#FF7043");
public static Color DeepOrange500 { get; } = (Color)ColorConverter.ConvertFromString("#FF5722");
public static Color DeepOrange600 { get; } = (Color)ColorConverter.ConvertFromString("#F4511E");
public static Color DeepOrange700 { get; } = (Color)ColorConverter.ConvertFromString("#E64A19");
public static Color DeepOrange800 { get; } = (Color)ColorConverter.ConvertFromString("#D84315");
public static Color DeepOrange900 { get; } = (Color)ColorConverter.ConvertFromString("#BF360C");
public static Color DeepOrangeA100 { get; } = (Color)ColorConverter.ConvertFromString("#FF9E80");
public static Color DeepOrangeA200 { get; } = (Color)ColorConverter.ConvertFromString("#FF6E40");
public static Color DeepOrangeA400 { get; } = (Color)ColorConverter.ConvertFromString("#FF3D00");
public static Color DeepOrangeA700 { get; } = (Color)ColorConverter.ConvertFromString("#DD2C00");
public string Name { get; } = "DeepOrange";
public IDictionary<MaterialDesignColor, Color> Lookup { get; } = new Dictionary<MaterialDesignColor, Color>
{
{ MaterialDesignColor.DeepOrange50, DeepOrange50 },
{ MaterialDesignColor.DeepOrange100, DeepOrange100 },
{ MaterialDesignColor.DeepOrange200, DeepOrange200 },
{ MaterialDesignColor.DeepOrange300, DeepOrange300 },
{ MaterialDesignColor.DeepOrange400, DeepOrange400 },
{ MaterialDesignColor.DeepOrange500, DeepOrange500 },
{ MaterialDesignColor.DeepOrange600, DeepOrange600 },
{ MaterialDesignColor.DeepOrange700, DeepOrange700 },
{ MaterialDesignColor.DeepOrange800, DeepOrange800 },
{ MaterialDesignColor.DeepOrange900, DeepOrange900 },
{ MaterialDesignColor.DeepOrangeA100, DeepOrangeA100 },
{ MaterialDesignColor.DeepOrangeA200, DeepOrangeA200 },
{ MaterialDesignColor.DeepOrangeA400, DeepOrangeA400 },
{ MaterialDesignColor.DeepOrangeA700, DeepOrangeA700 },
};
public IEnumerable<Color> Hues => Lookup.Values;
}
| DeepOrangeSwatch |
csharp | dotnet__tye | src/Microsoft.Tye.Core/CombineStep.cs | {
"start": 347,
"end": 6729
} | public sealed class ____ : ApplicationExecutor.ServiceStep
{
public override string DisplayText => "Compiling Services...";
public string Environment { get; set; } = "production";
public override Task ExecuteAsync(OutputContext output, ApplicationBuilder application, ServiceBuilder service)
{
// No need to do this computation for a non-project since we're not deploying it.
if (!(service is ProjectServiceBuilder project))
{
return Task.CompletedTask;
}
// Compute ASPNETCORE_URLS based on the bindings exposed by *this* project.
foreach (var binding in service.Bindings)
{
if (binding.Protocol == null && binding.ConnectionString == null)
{
binding.Protocol = "http";
}
if (binding.Port == null && binding.Protocol == "http")
{
binding.Port = 80;
}
if (binding.Protocol == "http")
{
var port = binding.ContainerPort ?? binding.Port ?? 80;
var urls = $"http://*{(port == 80 ? "" : $":{port}")}";
project.EnvironmentVariables.Add(new EnvironmentVariableBuilder("ASPNETCORE_URLS") { Value = urls, });
project.EnvironmentVariables.Add(new EnvironmentVariableBuilder("PORT") { Value = port.ToString(CultureInfo.InvariantCulture), });
break;
}
}
var services = new List<string>() { service.Name };
services.AddRange(service.Dependencies);
// Process bindings and turn them into environment variables and secrets. There's
// some duplication with the code in m8s (Application.cs) for populating environments.
//
// service.Service.Bindings is the bindings OUT - this step computes bindings IN.
service.Outputs.Add(ComputeBindings(application, services));
foreach (var sidecar in project.Sidecars)
{
sidecar.Outputs.Add(ComputeBindings(application, services));
}
return Task.CompletedTask;
}
private ComputedBindings ComputeBindings(ApplicationBuilder application, IEnumerable<string> dependencies)
{
var bindings = new ComputedBindings();
foreach (var dependency in dependencies)
{
var other = application.Services.Single(a => a.Name == dependency);
foreach (var binding in other.Bindings)
{
if (other is ProjectServiceBuilder)
{
// The other thing is a project, and will be deployed along with this
// service.
var configName =
(binding.Name is null || binding.Name == other.Name) ?
other.Name.ToUpperInvariant() :
$"{other.Name.ToUpperInvariant()}__{binding.Name.ToUpperInvariant()}";
if (!string.IsNullOrEmpty(binding.ConnectionString))
{
// Special case for connection strings
bindings.Bindings.Add(new EnvironmentVariableInputBinding($"CONNECTIONSTRINGS__{configName}", binding.ConnectionString));
continue;
}
if (binding.Protocol == "https")
{
// We skip https for now in deployment, because the E2E requires certificates
// and we haven't done those features yet.
continue;
}
binding.Protocol ??= "http";
if (binding.Port == null && binding.Protocol == "http")
{
binding.Port = 80;
}
if (!string.IsNullOrEmpty(binding.Protocol))
{
bindings.Bindings.Add(new EnvironmentVariableInputBinding($"SERVICE__{configName}__PROTOCOL", binding.Protocol));
}
if (binding.Port != null)
{
bindings.Bindings.Add(new EnvironmentVariableInputBinding($"SERVICE__{configName}__PORT", binding.Port.Value.ToString()));
}
bindings.Bindings.Add(new EnvironmentVariableInputBinding($"SERVICE__{configName}__HOST", binding.Host ?? other.Name));
}
else
{
// The other service is not a project, so we'll use secrets.
if (!string.IsNullOrEmpty(binding.ConnectionString))
{
bindings.Bindings.Add(new SecretConnectionStringInputBinding(
name: $"binding-{Environment}-{(binding.Name == null ? other.Name.ToLowerInvariant() : (other.Name.ToLowerInvariant() + "-" + binding.Name.ToLowerInvariant()))}-secret",
other,
binding,
keyname: $"CONNECTIONSTRINGS__{(binding.Name == null ? other.Name.ToUpperInvariant() : (other.Name.ToUpperInvariant() + "__" + binding.Name.ToUpperInvariant()))}"));
}
else
{
bindings.Bindings.Add(new SecretUrlInputBinding(
name: $"binding-{Environment}-{(binding.Name == null ? other.Name.ToLowerInvariant() : (other.Name.ToLowerInvariant() + "-" + binding.Name.ToLowerInvariant()))}-secret",
other,
binding,
keynamebase: $"SERVICE__{(binding.Name == null ? other.Name.ToUpperInvariant() : (other.Name.ToUpperInvariant() + "__" + binding.Name.ToUpperInvariant()))}"));
}
}
}
}
return bindings;
}
}
}
| CombineStep |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Elements/KeyboardScrollingNonScrollingPageSmallTitlesGallery.cs | {
"start": 154,
"end": 602
} | public class ____ : ContentViewGalleryPage
{
public KeyboardScrollingNonScrollingPageSmallTitlesGallery()
{
On<iOS>().SetLargeTitleDisplay(LargeTitleDisplayMode.Never);
Add(new KeyboardScrollingEntriesPage());
Add(new KeyboardScrollingEditorsPage());
Add(new KeyboardScrollingEntryNextEditorPage());
}
protected override bool SupportsScroll
{
get { return false; }
}
}
}
| KeyboardScrollingNonScrollingPageSmallTitlesGallery |
csharp | rabbitmq__rabbitmq-dotnet-client | projects/RabbitMQ.Client/Framing/ConnectionSecureOk.cs | {
"start": 1485,
"end": 2160
} | struct ____ : IOutgoingAmqpMethod
{
public readonly byte[] _response;
public ConnectionSecureOk(byte[] Response)
{
_response = Response;
}
public ProtocolCommandId ProtocolCommandId => ProtocolCommandId.ConnectionSecureOk;
public int WriteTo(Span<byte> span)
{
return WireFormatting.WriteLongstr(ref span.GetStart(), _response);
}
public int GetRequiredBufferSize()
{
int bufferSize = 4; // bytes for length of _response
bufferSize += _response.Length; // _response in bytes
return bufferSize;
}
}
}
| ConnectionSecureOk |
csharp | louthy__language-ext | LanguageExt.Core/Monads/Alternative Monads/These/These.cs | {
"start": 114,
"end": 2322
} | partial record ____<A, B> : K<These<A>, B>
{
/// <summary>
/// Stop other types deriving from These
/// </summary>
private These() {}
/// <summary>
/// Case analysis for the `These` type
/// </summary>
/// <param name="This">Match for `This` state</param>
/// <param name="That">Match for `That` state</param>
/// <param name="Both">Match for `Both` state</param>
/// <typeparam name="C">Result type</typeparam>
/// <returns>Result of running either `This`, `That`, or `Both`</returns>
public abstract C Match<C>(Func<A, C> This, Func<B, C> That, Func<A, B, C> Both);
/// <summary>
/// Takes two default values and produces a tuple
/// </summary>
/// <param name="x">Default value A</param>
/// <param name="y">Default value B</param>
/// <returns>Tuple</returns>
public abstract (A, B) ToTuple(A x, B y);
/// <summary>
/// Bi-functor map operation
/// </summary>
/// <param name="This">Mapping of `This`</param>
/// <param name="That">Mapping of `That`</param>
/// <typeparam name="C">Resulting `This` bound value type</typeparam>
/// <typeparam name="D">Resulting `That` bound value type</typeparam>
/// <returns></returns>
public abstract These<C, D> BiMap<C, D>(Func<A, C> This, Func<B, D> That)
where C : Semigroup<C>;
/// <summary>
/// Functor map operation
/// </summary>
/// <param name="f">Mapping function</param>
public abstract These<A, C> Map<C>(Func<B, C> f);
/// <summary>
/// Traverse
/// </summary>
public K<F, These<A, C>> Traverse<F, C>(Func<B, K<F, C>> f)
where F : Applicative<F> =>
this.Kind().Traverse(f).Map(ac => ac.As());
/// <summary>
/// Bi-map and coalesce results with the provided operation.
/// </summary>
/// <param name="This">This mapping</param>
/// <param name="That">That mapping</param>
/// <param name="Both">Both mapping</param>
/// <typeparam name="C"></typeparam>
/// <returns></returns>
public C Merge<C>(Func<A, C> This, Func<B, C> That, Func<C, C, C> Both)
where C : Semigroup<C> =>
BiMap(This, That).Merge(Both);
}
| These |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types.NodaTime/OffsetTimeType.cs | {
"start": 335,
"end": 2385
} | public class ____ : StringToStructBaseType<OffsetTime>
{
private readonly IPattern<OffsetTime>[] _allowedPatterns;
private readonly IPattern<OffsetTime> _serializationPattern;
/// <summary>
/// Initializes a new instance of <see cref="OffsetTimeType"/>.
/// </summary>
public OffsetTimeType(params IPattern<OffsetTime>[] allowedPatterns) : base("OffsetTime")
{
if (allowedPatterns.Length == 0)
{
throw ThrowHelper.PatternCannotBeEmpty(this);
}
_allowedPatterns = allowedPatterns;
_serializationPattern = _allowedPatterns[0];
Description = CreateDescription(
allowedPatterns,
NodaTimeResources.OffsetTimeType_Description,
NodaTimeResources.OffsetTimeType_Description_Extended);
SerializationType = ScalarSerializationType.String;
}
/// <summary>
/// Initializes a new instance of <see cref="OffsetTimeType"/>.
/// </summary>
[ActivatorUtilitiesConstructor]
public OffsetTimeType() : this(OffsetTimePattern.GeneralIso)
{
}
/// <inheritdoc />
protected override string Serialize(OffsetTime runtimeValue)
=> _serializationPattern
.Format(runtimeValue);
/// <inheritdoc />
protected override bool TryDeserialize(
string resultValue,
[NotNullWhen(true)] out OffsetTime? runtimeValue)
=> _allowedPatterns.TryParse(resultValue, out runtimeValue);
protected override Dictionary<IPattern<OffsetTime>, string> PatternMap => new()
{
{ OffsetTimePattern.GeneralIso, "hh:mm:ss±hh:mm" },
{ OffsetTimePattern.ExtendedIso, "hh:mm:ss.sssssssss±hh:mm" },
{ OffsetTimePattern.Rfc3339, "hh:mm:ss.sssssssss±hh:mm" }
};
protected override Dictionary<IPattern<OffsetTime>, string> ExampleMap => new()
{
{ OffsetTimePattern.GeneralIso, "20:00:00Z" },
{ OffsetTimePattern.ExtendedIso, "20:00:00.999Z" },
{ OffsetTimePattern.Rfc3339, "20:00:00.999999999Z" }
};
}
| OffsetTimeType |
csharp | NLog__NLog | examples/targets/Configuration API/File/Archive4/Example.cs | {
"start": 52,
"end": 2284
} | class ____
{
static void Main(string[] args)
{
FileTarget target = new FileTarget();
target.Layout = "${longdate} ${logger} ${message}";
target.FileName = "${basedir}/logs/logfile.${level}.txt";
// where to store the archive files
target.ArchiveFileName = "${basedir}/archives/${level}/log.{#####}.txt";
target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute;
target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling;
target.MaxArchiveFiles = 3;
target.ArchiveAboveSize = 10000;
LoggingConfiguration nlogConfig = new LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(target);
LogManager.Configuration = nlogConfig;
Logger logger = LogManager.GetLogger("Example");
// generate a large number of messages, sleeping 1/10 of second between writes
// to observe time-based archiving which occurs every minute
// the volume is high enough to cause ArchiveAboveSize to be triggered
// so that log files larger than 10000 bytes are archived as well
// in this version, a single File target keeps track of 3 sets of log and
// archive files, one for each level
// you get:
// logs/logfile.Debug.txt
// logs/logfile.Error.txt
// logs/logfile.Fatal.txt
//
// and your archives go to:
//
// archives/Debug/log.00000.txt
// archives/Debug/log.00001.txt
// archives/Debug/log.00002.txt
// archives/Debug/log.00003.txt
// archives/Error/log.00000.txt
// archives/Error/log.00001.txt
// archives/Error/log.00002.txt
// archives/Error/log.00003.txt
// archives/Fatal/log.00000.txt
// archives/Fatal/log.00001.txt
// archives/Fatal/log.00002.txt
// archives/Fatal/log.00003.txt
for (int i = 0; i < 2500; ++i)
{
logger.Debug("log message {i}", i);
logger.Error("log message {i}", i);
logger.Fatal("log message {i}", i);
System.Threading.Thread.Sleep(100);
}
}
}
| Example |
csharp | dotnet__machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/ApplyOnnxModel.cs | {
"start": 129,
"end": 1295
} | public static class ____
{
public static void Example()
{
// Download the squeeznet image model from ONNX model zoo, version 1.2
// https://github.com/onnx/models/tree/master/squeezenet or
// https://s3.amazonaws.com/download.onnx/models/opset_8/squeezenet.tar.gz
// or use Microsoft.ML.Onnx.TestModels nuget.
var modelPath = @"squeezenet\00000001\model.onnx";
// Create ML pipeline to score the data using OnnxScoringEstimator
var mlContext = new MLContext();
// Generate sample test data.
var samples = GetTensorData();
// Convert training data to IDataView, the general data type used in
// ML.NET.
var data = mlContext.Data.LoadFromEnumerable(samples);
// Create the pipeline to score using provided onnx model.
var pipeline = mlContext.Transforms.ApplyOnnxModel(modelPath);
// Fit the pipeline and get the transformed values
var transformedValues = pipeline.Fit(data).Transform(data);
// Retrieve model scores into Prediction | ApplyOnnxModel |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Markup/Reader/XamlObjectBuilder.cs | {
"start": 56647,
"end": 57116
} | private class ____
{
private readonly object _instance;
private readonly MethodInfo _method;
public EventHandlerWrapper(object instance, MethodInfo method)
{
_instance = instance;
_method = method;
}
public void Handler2(object sender, object args)
{
_method.Invoke(_instance, Array.Empty<object>());
}
public void Handler1(object sender)
{
_method.Invoke(_instance, Array.Empty<object>());
}
}
| EventHandlerWrapper |
csharp | louthy__language-ext | LanguageExt.Core/Monads/Alternative Monads/Try/Operators/Try.Operators.Monad.cs | {
"start": 78,
"end": 1530
} | partial class ____
{
extension<A, B>(K<Try, A> self)
{
/// <summary>
/// Monad bind operator
/// </summary>
/// <param name="ma">Monad to bind</param>
/// <param name="f">Binding function</param>
/// <returns>Mapped monad</returns>
public static Try<B> operator >> (K<Try, A> ma, Func<A, K<Try, B>> f) =>
+ma.Bind(f);
/// <summary>
/// Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such
/// as the semicolon) in C#.
/// </summary>
/// <param name="lhs">First action to run</param>
/// <param name="rhs">Second action to run</param>
/// <returns>Result of the second action</returns>
public static Try<B> operator >> (K<Try, A> lhs, K<Try, B> rhs) =>
lhs >> (_ => rhs);
}
extension<A>(K<Try, A> self)
{
/// <summary>
/// Sequentially compose two actions. The second action is a unit-returning action, so the result of the
/// first action is propagated.
/// </summary>
/// <param name="lhs">First action to run</param>
/// <param name="rhs">Second action to run</param>
/// <returns>Result of the first action</returns>
public static Try<A> operator >> (K<Try, A> lhs, K<Try, Unit> rhs) =>
lhs >> (x => (_ => x) * rhs);
}
}
| TryExtensions |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/IntegrationTests/dxaml/controls/inc/PanelsHelper.cs | {
"start": 2085,
"end": 2908
} | class ____>
// static TItemsControl^ CreateItemsControlWithPanel(Platform::String^ xamlPanelProperties = L"")
//{
// TItemsControl ^ itemsControl = nullptr;
// await RunOnUIThread(()
// {
// LOG_OUTPUT("Creating a %s with a %s as its panel.", GetClassName<TItemsControl>().Data(), GetClassName<TPanel>().Data());
// itemsControl = ref new TItemsControl();
// itemsControl.Width = 300;
// itemsControl.Height = 300;
// itemsControl.ItemsPanel =
// dynamic_cast < ItemsPanelTemplate ^> (XamlReader::Load(
// L"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'><" + GetClassName<TPanel>() + L" " + xamlPanelProperties + "/></ItemsPanelTemplate>"));
// ApplyContainerStyle<TItemsControl>(itemsControl);
// });
// return itemsControl;
//}
//template< | TPanel |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs | {
"start": 1624,
"end": 3208
} | public class ____ : TestFixtureBase
{
[Test]
public void List()
{
FSharpList<int> l = ListModule.OfSeq(new List<int> { 1, 2, 3 });
string json = JsonConvert.SerializeObject(l, Formatting.Indented);
StringAssert.AreEqual(@"[
1,
2,
3
]", json);
FSharpList<int> l2 = JsonConvert.DeserializeObject<FSharpList<int>>(json);
Assert.AreEqual(l.Length, l2.Length);
CollectionAssert.AreEquivalent(l, l2);
}
[Test]
public void Set()
{
FSharpSet<int> l = SetModule.OfSeq(new List<int> { 1, 2, 3 });
string json = JsonConvert.SerializeObject(l, Formatting.Indented);
StringAssert.AreEqual(@"[
1,
2,
3
]", json);
FSharpSet<int> l2 = JsonConvert.DeserializeObject<FSharpSet<int>>(json);
Assert.AreEqual(l.Count, l2.Count);
CollectionAssert.AreEquivalent(l, l2);
}
[Test]
public void Map()
{
FSharpMap<string, int> m1 = MapModule.OfSeq(new List<Tuple<string, int>> { Tuple.Create("one", 1), Tuple.Create("II", 2), Tuple.Create("3", 3) });
string json = JsonConvert.SerializeObject(m1, Formatting.Indented);
FSharpMap<string, int> m2 = JsonConvert.DeserializeObject<FSharpMap<string, int>>(json);
Assert.AreEqual(m1.Count, m2.Count);
Assert.AreEqual(1, m2["one"]);
Assert.AreEqual(2, m2["II"]);
Assert.AreEqual(3, m2["3"]);
}
}
}
#endif | FSharpTests |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/Issue21837.xaml.cs | {
"start": 230,
"end": 577
} | public partial class ____ : ContentPage
{
private int _tapCount;
public int TapCount
{
get => _tapCount;
set
{
_tapCount = value;
OnPropertyChanged();
}
}
public Command TapCommand { get; set; }
public Issue21837()
{
InitializeComponent();
TapCommand = new Command(() => ++TapCount);
BindingContext = this;
}
}
| Issue21837 |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.DataIngestion/Processors/KeywordEnricher.cs | {
"start": 615,
"end": 4496
} | public sealed class ____ : IngestionChunkProcessor<string>
{
private const int DefaultMaxKeywords = 5;
private readonly EnricherOptions _options;
private readonly ChatMessage _systemPrompt;
private readonly ILogger? _logger;
/// <summary>
/// Initializes a new instance of the <see cref="KeywordEnricher"/> class.
/// </summary>
/// <param name="options">The options for generating keywords.</param>
/// <param name="predefinedKeywords">The set of predefined keywords for extraction.</param>
/// <param name="maxKeywords">The maximum number of keywords to extract. When not provided, it defaults to 5.</param>
/// <param name="confidenceThreshold">The confidence threshold for keyword inclusion. When not provided, it defaults to 0.7.</param>
/// <remarks>
/// If no predefined keywords are provided, the model will extract keywords based on the content alone.
/// Such results may vary more significantly between different AI models.
/// </remarks>
public KeywordEnricher(EnricherOptions options, ReadOnlySpan<string> predefinedKeywords,
int? maxKeywords = null, double? confidenceThreshold = null)
{
_options = Throw.IfNull(options).Clone();
Validate(predefinedKeywords);
double threshold = confidenceThreshold.HasValue
? Throw.IfOutOfRange(confidenceThreshold.Value, 0.0, 1.0, nameof(confidenceThreshold))
: 0.7;
int keywordsCount = maxKeywords.HasValue
? Throw.IfLessThanOrEqual(maxKeywords.Value, 0, nameof(maxKeywords))
: DefaultMaxKeywords;
_systemPrompt = CreateSystemPrompt(keywordsCount, predefinedKeywords, threshold);
_logger = _options.LoggerFactory?.CreateLogger<KeywordEnricher>();
}
/// <summary>
/// Gets the metadata key used to store the keywords.
/// </summary>
public static string MetadataKey => "keywords";
/// <inheritdoc/>
public override IAsyncEnumerable<IngestionChunk<string>> ProcessAsync(IAsyncEnumerable<IngestionChunk<string>> chunks, CancellationToken cancellationToken = default)
=> Batching.ProcessAsync<string[]>(chunks, _options, MetadataKey, _systemPrompt, _logger, cancellationToken);
private static void Validate(ReadOnlySpan<string> predefinedKeywords)
{
if (predefinedKeywords.Length == 0)
{
return;
}
HashSet<string> result = new(StringComparer.Ordinal);
foreach (string keyword in predefinedKeywords)
{
if (!result.Add(keyword))
{
Throw.ArgumentException(nameof(predefinedKeywords), $"Duplicate keyword found: '{keyword}'");
}
}
}
private static ChatMessage CreateSystemPrompt(int maxKeywords, ReadOnlySpan<string> predefinedKeywords, double confidenceThreshold)
{
StringBuilder sb = new($"You are a keyword extraction expert. For each of the following texts, extract up to {maxKeywords} most relevant keywords. ");
if (predefinedKeywords.Length > 0)
{
#pragma warning disable IDE0058 // Expression value is never used
sb.Append("Focus on extracting keywords from the following predefined list: ");
#if NET9_0_OR_GREATER
sb.AppendJoin(", ", predefinedKeywords!);
#else
for (int i = 0; i < predefinedKeywords.Length; i++)
{
sb.Append(predefinedKeywords[i]);
if (i < predefinedKeywords.Length - 1)
{
sb.Append(", ");
}
}
#endif
sb.Append(". ");
}
sb.Append("Exclude keywords with confidence score below ").Append(confidenceThreshold).Append('.');
#pragma warning restore IDE0058 // Expression value is never used
return new(ChatRole.System, sb.ToString());
}
}
| KeywordEnricher |
csharp | dotnet__aspire | src/Aspire.Cli/Mcp/ListResourcesTool.cs | {
"start": 255,
"end": 1696
} | internal sealed class ____ : CliMcpTool
{
public override string Name => "list_resources";
public override string Description => "List the application resources. Includes information about their type (.NET project, container, executable), running state, source, HTTP endpoints, health status, commands, configured environment variables, and relationships.";
public override JsonElement GetInputSchema()
{
return JsonDocument.Parse("{ \"type\": \"object\", \"properties\": {} }").RootElement;
}
public override async ValueTask<CallToolResult> CallToolAsync(ModelContextProtocol.Client.McpClient mcpClient, IReadOnlyDictionary<string, JsonElement>? arguments, CancellationToken cancellationToken)
{
// Convert JsonElement arguments to Dictionary<string, object?>
Dictionary<string, object?>? convertedArgs = null;
if (arguments != null)
{
convertedArgs = new Dictionary<string, object?>();
foreach (var kvp in arguments)
{
convertedArgs[kvp.Key] = kvp.Value.ValueKind == JsonValueKind.Null ? null : kvp.Value;
}
}
// Forward the call to the dashboard's MCP server
return await mcpClient.CallToolAsync(
Name,
convertedArgs,
serializerOptions: McpJsonUtilities.DefaultOptions,
cancellationToken: cancellationToken);
}
}
| ListResourcesTool |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/Messaging/Permissions.Messaging.cs | {
"start": 1006,
"end": 1464
} | public static class ____
{
public const string Self = "cms.messagetemplate";
public const string Read = "cms.messagetemplate.read";
public const string Update = "cms.messagetemplate.update";
public const string Create = "cms.messagetemplate.create";
public const string Delete = "cms.messagetemplate.delete";
}
}
public static | MessageTemplate |
csharp | xunit__xunit | src/xunit.v3.runner.utility.tests/Visitors/TestDiscoverySinkTests.cs | {
"start": 41,
"end": 640
} | public class ____
{
[Fact]
public void CollectsTestCases()
{
var visitor = new TestDiscoverySink();
var testCase1 = TestData.TestCaseDiscovered();
var testCase2 = TestData.TestCaseDiscovered();
var testCase3 = TestData.TestCaseDiscovered();
visitor.OnMessage(testCase1);
visitor.OnMessage(testCase2);
visitor.OnMessage(testCase3);
visitor.OnMessage(TestData.DiagnosticMessage()); // Ignored
Assert.Collection(
visitor.TestCases,
msg => Assert.Same(testCase1, msg),
msg => Assert.Same(testCase2, msg),
msg => Assert.Same(testCase3, msg)
);
}
}
| TestDiscoverySinkTests |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/ObserverTest.cs | {
"start": 24184,
"end": 26212
} | private class ____ : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
Task.Run(() => d(state));
}
}
[TestMethod]
public void Observer_ToProgress_ArgumentChecking()
{
var s = Scheduler.Immediate;
var o = Observer.Create<int>(_ => { });
ReactiveAssert.Throws<ArgumentNullException>(() => Observer.ToProgress<int>(default));
ReactiveAssert.Throws<ArgumentNullException>(() => Observer.ToProgress<int>(default, s));
ReactiveAssert.Throws<ArgumentNullException>(() => Observer.ToProgress(o, default));
}
[TestMethod]
public void Observer_ToProgress()
{
var xs = new List<int>();
var p = Observer.Create<int>(xs.Add).ToProgress();
p.Report(42);
p.Report(43);
Assert.True(xs.SequenceEqual([42, 43]));
}
[TestMethod]
public void Observer_ToProgress_Scheduler()
{
var s = new TestScheduler();
var o = s.CreateObserver<int>();
var p = o.ToProgress(s);
s.ScheduleAbsolute(200, () =>
{
p.Report(42);
p.Report(43);
});
s.Start();
o.Messages.AssertEqual(
OnNext(201, 42),
OnNext(202, 43)
);
}
[TestMethod]
public void Progress_ToObserver_ArgumentChecking()
{
ReactiveAssert.Throws<ArgumentNullException>(() => Observer.ToObserver(default(IProgress<int>)));
}
[TestMethod]
public void Progress_ToObserver()
{
var xs = new List<int>();
var p = new MyProgress<int>(xs.Add);
var o = p.ToObserver();
o.OnNext(42);
o.OnNext(43);
Assert.True(xs.SequenceEqual([42, 43]));
}
| MySyncCtx |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Automation/Peers/HyperlinkButtonAutomationPeer.cs | {
"start": 458,
"end": 1005
} | public partial class ____ : ButtonBaseAutomationPeer, Provider.IInvokeProvider
{
public HyperlinkButtonAutomationPeer(HyperlinkButton owner) : base(owner)
{
}
protected override string GetClassNameCore() => "Hyperlink";
protected override AutomationControlType GetAutomationControlTypeCore()
=> AutomationControlType.Hyperlink;
public void Invoke()
{
if (!IsEnabled())
{
// UIA_E_ELEMENTNOTENABLED
throw new ElementNotEnabledException();
}
(Owner as HyperlinkButton).AutomationPeerClick();
}
}
| HyperlinkButtonAutomationPeer |
csharp | dotnet__aspire | tests/Aspire.Hosting.Tests/Utils/ResourceNotificationServiceTestHelpers.cs | {
"start": 299,
"end": 904
} | public static class ____
{
public static ResourceNotificationService Create(ILogger<ResourceNotificationService>? logger = null, IHostApplicationLifetime? hostApplicationLifetime = null, ResourceLoggerService? resourceLoggerService = null)
{
return new ResourceNotificationService(
logger ?? new NullLogger<ResourceNotificationService>(),
hostApplicationLifetime ?? new TestHostApplicationLifetime(),
TestServiceProvider.Instance,
resourceLoggerService ?? new ResourceLoggerService()
);
}
}
| ResourceNotificationServiceTestHelpers |
csharp | dotnet__maui | src/BlazorWebView/src/Maui/Android/BlazorWebChromeClient.cs | {
"start": 334,
"end": 2944
} | class ____ : WebChromeClient
{
public override bool OnCreateWindow(global::Android.Webkit.WebView? view, bool isDialog, bool isUserGesture, Message? resultMsg)
{
if (view?.Context is not null)
{
// Intercept _blank target <a> tags to always open in device browser
// regardless of UrlLoadingStrategy.OpenInWebview
var requestUrl = view.GetHitTestResult().Extra;
var intent = new Intent(Intent.ActionView, Uri.Parse(requestUrl));
view.Context.StartActivity(intent);
}
// We don't actually want to create a new WebView window so we just return false
return false;
}
public override bool OnShowFileChooser(global::Android.Webkit.WebView? view, IValueCallback? filePathCallback, FileChooserParams? fileChooserParams)
{
if (filePathCallback is null)
{
return base.OnShowFileChooser(view, filePathCallback, fileChooserParams);
}
CallFilePickerAsync(filePathCallback, fileChooserParams).FireAndForget();
return true;
}
private static async Task CallFilePickerAsync(IValueCallback filePathCallback, FileChooserParams? fileChooserParams)
{
var pickOptions = GetPickOptions(fileChooserParams);
var fileResults = fileChooserParams?.Mode == ChromeFileChooserMode.OpenMultiple ?
await FilePicker.PickMultipleAsync(pickOptions) :
new[] { (await FilePicker.PickAsync(pickOptions))! };
if (fileResults?.All(f => f is null) ?? true)
{
// Task was cancelled, return null to original callback
filePathCallback.OnReceiveValue(null);
return;
}
var fileUris = new List<Uri>(fileResults.Count());
foreach (var fileResult in fileResults)
{
if (fileResult is null)
{
continue;
}
var javaFile = new File(fileResult.FullPath);
var androidUri = Uri.FromFile(javaFile);
if (androidUri is not null)
{
fileUris.Add(androidUri);
}
}
filePathCallback.OnReceiveValue(fileUris.ToArray());
return;
}
private static PickOptions? GetPickOptions(FileChooserParams? fileChooserParams)
{
var acceptedFileTypes = fileChooserParams?.GetAcceptTypes();
if (acceptedFileTypes is null ||
// When the accept attribute isn't provided GetAcceptTypes returns: [ "" ]
// this must be filtered out.
(acceptedFileTypes.Length == 1 && string.IsNullOrEmpty(acceptedFileTypes[0])))
{
return null;
}
var pickOptions = new PickOptions()
{
FileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
{
{ DevicePlatform.Android, acceptedFileTypes }
})
};
return pickOptions;
}
}
}
| BlazorWebChromeClient |
csharp | dotnetcore__FreeSql | Examples/base_entity/MessagePackMap.cs | {
"start": 586,
"end": 4951
} | public static class ____
{
internal static int _isAoped = 0;
static ConcurrentDictionary<Type, bool> _dicTypes = new ConcurrentDictionary<Type, bool>();
static MethodInfo MethodMessagePackSerializerDeserialize = typeof(MessagePackSerializer).GetMethod("Deserialize", new[] { typeof(Type), typeof(ReadOnlyMemory<byte>), typeof(MessagePackSerializerOptions), typeof(CancellationToken) });
static MethodInfo MethodMessagePackSerializerSerialize = typeof(MessagePackSerializer).GetMethod("Serialize", new[] { typeof(Type), typeof(object), typeof(MessagePackSerializerOptions), typeof(CancellationToken) });
static ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>> _dicMessagePackMapFluentApi = new ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>>();
static object _concurrentObj = new object();
public static ColumnFluent MessagePackMap(this ColumnFluent col)
{
_dicMessagePackMapFluentApi.GetOrAdd(col._entityType, et => new ConcurrentDictionary<string, bool>())
.GetOrAdd(col._property.Name, pn => true);
return col;
}
public static void UseMessagePackMap(this IFreeSql that)
{
UseMessagePackMap(that, MessagePackSerializerOptions.Standard);
}
public static void UseMessagePackMap(this IFreeSql that, MessagePackSerializerOptions settings)
{
if (Interlocked.CompareExchange(ref _isAoped, 1, 0) == 0)
{
FreeSql.Internal.Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, Type type) =>
{
if (_dicTypes.ContainsKey(type))
return Expression.IfThenElse(
Expression.TypeIs(valueExp, type),
Expression.Return(returnTarget, valueExp),
Expression.Return(returnTarget, Expression.TypeAs(
Expression.Call(MethodMessagePackSerializerDeserialize,
Expression.Constant(type),
Expression.New(typeof(ReadOnlyMemory<byte>).GetConstructor(new[] { typeof(byte[]) }), Expression.Convert(valueExp, typeof(byte[]))),
Expression.Constant(settings, typeof(MessagePackSerializerOptions)),
Expression.Constant(default(CancellationToken), typeof(CancellationToken)))
, type))
);
return null;
});
}
that.Aop.ConfigEntityProperty += (s, e) =>
{
var isMessagePackMap = e.Property.GetCustomAttributes(typeof(MessagePackMapAttribute), false).Any() || _dicMessagePackMapFluentApi.TryGetValue(e.EntityType, out var tryjmfu) && tryjmfu.ContainsKey(e.Property.Name);
if (isMessagePackMap)
{
e.ModifyResult.MapType = typeof(byte[]);
e.ModifyResult.StringLength = -2;
if (_dicTypes.TryAdd(e.Property.PropertyType, true))
{
lock (_concurrentObj)
{
FreeSql.Internal.Utils.dicExecuteArrayRowReadClassOrTuple[e.Property.PropertyType] = true;
FreeSql.Internal.Utils.GetDataReaderValueBlockExpressionObjectToBytesIfThenElse.Add((LabelTarget returnTarget, Expression valueExp, Expression elseExp, Type type) =>
{
return Expression.IfThenElse(
Expression.TypeIs(valueExp, e.Property.PropertyType),
Expression.Return(returnTarget,
Expression.Call(MethodMessagePackSerializerSerialize,
Expression.Constant(e.Property.PropertyType, typeof(Type)),
Expression.Convert(valueExp, typeof(object)),
Expression.Constant(settings, typeof(MessagePackSerializerOptions)),
Expression.Constant(default(CancellationToken), typeof(CancellationToken)))
, typeof(object)),
elseExp);
});
}
}
}
};
}
} | FreeSqlMessagePackMapCoreExtensions |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Users/Startup.cs | {
"start": 23874,
"end": 24829
} | public sealed class ____ : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddDisplayDriver<User, CustomUserSettingsDisplayDriver>();
services.AddPermissionProvider<CustomUserSettingsPermissions>();
services.AddDeployment<CustomUserSettingsDeploymentSource, CustomUserSettingsDeploymentStep, CustomUserSettingsDeploymentStepDriver>();
services.AddScoped<IStereotypesProvider, CustomUserSettingsStereotypesProvider>();
services.Configure<ContentTypeDefinitionOptions>(options =>
{
options.Stereotypes.TryAdd("CustomUserSettings", new ContentTypeDefinitionDriverOptions
{
ShowCreatable = false,
ShowListable = false,
ShowDraftable = false,
ShowVersionable = false,
});
});
}
}
[RequireFeatures("OrchardCore.Deployment")]
| CustomUserSettingsStartup |
csharp | EventStore__EventStore | src/KurrentDB.Core/Messages/ElectionMessageDtos.cs | {
"start": 4497,
"end": 5229
} | public class ____ {
public Guid ServerId { get; set; }
public Guid LeaderId { get; set; }
public string ServerHttpAddress { get; set; }
public int ServerHttpPort { get; set; }
public string LeaderHttpAddress { get; set; }
public int LeaderHttpPort { get; set; }
public int View { get; set; }
public AcceptDto() {
}
public AcceptDto(ElectionMessage.Accept message) {
ServerId = message.ServerId;
LeaderId = message.LeaderId;
ServerHttpAddress = message.ServerHttpEndPoint.GetHost();
ServerHttpPort = message.ServerHttpEndPoint.GetPort();
LeaderHttpAddress = message.LeaderHttpEndPoint.GetHost();
LeaderHttpPort = message.LeaderHttpEndPoint.GetPort();
View = message.View;
}
}
| AcceptDto |
csharp | dotnet__aspnetcore | src/DefaultBuilder/src/ForwardedHeadersStartupFilter.cs | {
"start": 286,
"end": 898
} | internal sealed class ____ : IStartupFilter
{
private readonly IConfiguration _configuration;
public ForwardedHeadersStartupFilter(IConfiguration configuration)
{
_configuration = configuration;
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
if (!string.Equals("true", _configuration["ForwardedHeaders_Enabled"], StringComparison.OrdinalIgnoreCase))
{
return next;
}
return app =>
{
app.UseForwardedHeaders();
next(app);
};
}
}
| ForwardedHeadersStartupFilter |
csharp | dotnet__aspnetcore | src/Http/Http.Results/tools/ResultsOfTGenerator/Program.cs | {
"start": 36657,
"end": 37054
} | class ____{typeArgNumber} : ChecksumResult");
writer.WriteIndentedLine(1, "{");
writer.WriteIndentedLine(2, $"public ChecksumResult{typeArgNumber}(int checksum = 0) : base(checksum) {{ }}");
writer.WriteIndentedLine(1, "}");
}
}
static void Generate_ProvidesMetadataResultClass(StreamWriter writer, int typeArgNumber)
{
// | ChecksumResult |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp/Reflection/ReflectionHelper.cs | {
"start": 2938,
"end": 4123
} | class ____ and it's declaring type including inherited attributes.
/// </summary>
/// <typeparam name="TAttribute">Type of the attribute</typeparam>
/// <param name="memberInfo">MemberInfo</param>
/// <param name="inherit">Inherit attribute from base classes</param>
public static List<TAttribute> GetAttributesOfMemberAndDeclaringType<TAttribute>(MemberInfo memberInfo, bool inherit = true)
where TAttribute : Attribute
{
var attributeList = new List<TAttribute>();
if (memberInfo.IsDefined(typeof(TAttribute), inherit))
{
attributeList.AddRange(memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>());
}
if (memberInfo.DeclaringType != null && memberInfo.DeclaringType.GetTypeInfo().IsDefined(typeof(TAttribute), inherit))
{
attributeList.AddRange(memberInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>());
}
return attributeList;
}
/// <summary>
/// Gets a list of attributes defined for a | member |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Interfaces/IApiKey.cs | {
"start": 145,
"end": 538
} | public interface ____ : IMeta
{
string Key { get; }
string? Environment { get; }
string? UserAuthId { get; }
DateTime CreatedDate { get; }
DateTime? ExpiryDate { get; }
DateTime? CancelledDate { get; }
int? RefId { get; }
string RefIdStr { get; }
bool HasScope(string scope);
bool HasFeature(string feature);
bool CanAccess(Type requestType);
}
| IApiKey |
csharp | dotnet__efcore | src/EFCore.Relational/Metadata/Internal/TableMappingBaseComparer.cs | {
"start": 666,
"end": 6502
} | public sealed class ____ : IEqualityComparer<ITableMappingBase>, IComparer<ITableMappingBase>
{
private TableMappingBaseComparer()
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static readonly TableMappingBaseComparer Instance = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public int Compare(ITableMappingBase? x, ITableMappingBase? y)
{
if (ReferenceEquals(x, y))
{
return 0;
}
if (x is null)
{
return -1;
}
if (y is null)
{
return 1;
}
var result = 0;
if (y.IsSharedTablePrincipal == null)
{
if (x.IsSharedTablePrincipal != null)
{
return 1;
}
}
else
{
if (x.IsSharedTablePrincipal == null)
{
return -1;
}
result = y.IsSharedTablePrincipal.Value.CompareTo(x.IsSharedTablePrincipal.Value);
if (result != 0)
{
return result;
}
}
if (y.IncludesDerivedTypes == null)
{
if (x.IncludesDerivedTypes != null)
{
return -1;
}
}
else
{
if (x.IncludesDerivedTypes == null)
{
return 1;
}
result = y.IncludesDerivedTypes.Value.CompareTo(x.IncludesDerivedTypes.Value);
if (result != 0)
{
return result;
}
}
if (y.IsSplitEntityTypePrincipal == null)
{
if (x.IsSplitEntityTypePrincipal != null)
{
return -1;
}
}
else
{
if (x.IsSplitEntityTypePrincipal == null)
{
return 1;
}
result = y.IsSplitEntityTypePrincipal.Value.CompareTo(x.IsSplitEntityTypePrincipal.Value);
if (result != 0)
{
return result;
}
}
result = TypeBaseNameComparer.Instance.Compare(x.TypeBase, y.TypeBase);
if (result != 0)
{
return result;
}
result = StringComparer.Ordinal.Compare(x.Table.Name, y.Table.Name);
if (result != 0)
{
return result;
}
result = StringComparer.Ordinal.Compare(x.Table.Schema, y.Table.Schema);
if (result != 0)
{
return result;
}
result = x.ColumnMappings.Count().CompareTo(y.ColumnMappings.Count());
if (result != 0)
{
return result;
}
return x.ColumnMappings.Zip(
y.ColumnMappings, (xc, yc) =>
{
var columnResult = StringComparer.Ordinal.Compare(xc.Property.Name, yc.Property.Name);
return columnResult != 0 ? columnResult : StringComparer.Ordinal.Compare(xc.Column.Name, yc.Column.Name);
})
.FirstOrDefault(r => r != 0);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public bool Equals(ITableMappingBase? x, ITableMappingBase? y)
=> ReferenceEquals(x, y)
|| x is not null
&& y is not null
&& (x.TypeBase == y.TypeBase
&& x.Table == y.Table
&& x.IncludesDerivedTypes == y.IncludesDerivedTypes
&& x.ColumnMappings.SequenceEqual(y.ColumnMappings));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public int GetHashCode(ITableMappingBase obj)
{
var hashCode = new HashCode();
hashCode.Add(obj.TypeBase, TypeBaseNameComparer.Instance);
hashCode.Add(obj.Table.Name);
hashCode.Add(obj.Table.Schema);
foreach (var columnMapping in obj.ColumnMappings)
{
hashCode.Add(columnMapping.Property.Name);
hashCode.Add(columnMapping.Column.Name);
}
hashCode.Add(obj.IncludesDerivedTypes);
return hashCode.ToHashCode();
}
}
| TableMappingBaseComparer |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/UIElementCollection.Android.cs | {
"start": 249,
"end": 1903
} | public partial class ____ : IList<UIElement>, IEnumerable<UIElement>
{
private readonly BindableView _owner;
public UIElementCollection(BindableView owner)
{
_owner = owner;
}
private int IndexOfCore(UIElement item)
{
return _owner.GetChildren().IndexOf(item);
}
private void InsertCore(int index, UIElement item)
{
_owner.AddView(item, index);
}
private UIElement RemoveAtCore(int index)
{
var view = _owner.GetChildAt(index);
_owner.RemoveViewAt(index);
return view as UIElement;
}
private UIElement GetAtIndexCore(int index)
{
return _owner.GetChildAt(index) as UIElement;
}
private UIElement SetAtIndexCore(int index, UIElement value)
{
var view = _owner.GetChildAt(index);
_owner.RemoveViewAt(index);
_owner.AddView(value, index);
return view as UIElement;
}
private void AddCore(UIElement item)
{
_owner.AddView(item);
}
private IEnumerable<View> ClearCore()
{
var views = _owner.GetChildren().ToArray();
_owner.RemoveAllViews();
return views;
}
private bool ContainsCore(UIElement item)
{
return _owner.GetChildren().Contains(item);
}
private void CopyToCore(UIElement[] array, int arrayIndex)
{
_owner.GetChildren().ToArray().CopyTo(array, arrayIndex);
}
private bool RemoveCore(UIElement item)
{
if (item != null)
{
_owner.RemoveView(item);
return true;
}
else
{
return false;
}
}
private int CountCore()
{
return _owner.ChildCount;
}
private void MoveCore(uint oldIndex, uint newIndex)
{
_owner.MoveViewTo((int)oldIndex, (int)newIndex);
}
}
}
| UIElementCollection |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWeb/Test.dtos.cs | {
"start": 6424,
"end": 6573
} | public partial class ____
{
public virtual ObjectDesign data { get; set; }
}
[Route("/code/object", "GET")]
| ObjectDesignResponse |
csharp | microsoft__semantic-kernel | dotnet/src/Agents/UnitTests/OpenAI/OpenAIAssistantAgentTests.cs | {
"start": 35938,
"end": 36569
} | private sealed class ____ : AIFunction
{
public TestAIFunction(string name, string description = "")
{
this.Name = name;
this.Description = description;
}
public override string Name { get; }
public override string Description { get; }
protected override ValueTask<object?> InvokeCoreAsync(AIFunctionArguments? arguments = null, CancellationToken cancellationToken = default)
{
return ValueTask.FromResult<object?>("Test result");
}
}
}
#pragma warning restore CS0419 // Ambiguous reference in cref attribute
| TestAIFunction |
csharp | AvaloniaUI__Avalonia | src/Windows/Avalonia.Win32/WinRT/Composition/WinUiCompositionShared.cs | {
"start": 84,
"end": 1505
} | internal class ____ : IDisposable
{
public ICompositor Compositor { get; }
public ICompositor5 Compositor5 { get; }
public ICompositorDesktopInterop DesktopInterop { get; }
public ICompositionBrush BlurBrush { get; }
public ICompositionBrush? MicaBrushLight { get; }
public ICompositionBrush? MicaBrushDark { get; }
public object SyncRoot { get; } = new();
public static readonly Version MinWinCompositionVersion = new(10, 0, 17134);
public static readonly Version MinAcrylicVersion = new(10, 0, 15063);
public static readonly Version MinHostBackdropVersion = new(10, 0, 22000);
public WinUiCompositionShared(ICompositor compositor)
{
Compositor = compositor.CloneReference();
Compositor5 = compositor.QueryInterface<ICompositor5>();
BlurBrush = WinUiCompositionUtils.CreateAcrylicBlurBackdropBrush(compositor);
MicaBrushLight = WinUiCompositionUtils.CreateMicaBackdropBrush(compositor, 242, 0.6f);
MicaBrushDark = WinUiCompositionUtils.CreateMicaBackdropBrush(compositor, 32, 0.8f);
DesktopInterop = compositor.QueryInterface<ICompositorDesktopInterop>();
}
public void Dispose()
{
BlurBrush.Dispose();
MicaBrushLight?.Dispose();
MicaBrushDark?.Dispose();
DesktopInterop.Dispose();
Compositor.Dispose();
Compositor5.Dispose();
}
}
| WinUiCompositionShared |
csharp | microsoft__PowerToys | src/modules/peek/Peek.FilePreviewer/Controls/SpecialFolderPreview/SpecialFolderInformationalPreviewControl.xaml.cs | {
"start": 357,
"end": 1536
} | partial class ____ : UserControl
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
nameof(Source),
typeof(SpecialFolderPreviewData),
typeof(SpecialFolderInformationalPreviewControl),
new PropertyMetadata(null));
public SpecialFolderPreviewData? Source
{
get { return (SpecialFolderPreviewData)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public SpecialFolderInformationalPreviewControl()
{
InitializeComponent();
}
public string FormatFileType(string? fileType) => FormatField("UnsupportedFile_FileType", fileType);
public string FormatFileSize(string? fileSize) => FormatField("UnsupportedFile_FileSize", fileSize);
public string FormatFileDateModified(string? fileDateModified) => FormatField("UnsupportedFile_DateModified", fileDateModified);
private static string FormatField(string resourceId, string? fieldValue)
{
return string.IsNullOrWhiteSpace(fieldValue) ? string.Empty : ReadableStringHelper.FormatResourceString(resourceId, fieldValue);
}
}
| SpecialFolderInformationalPreviewControl |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests.Provider.Custom/PostgreSQL/PostgreSQLExpression/DateTimeTest.cs | {
"start": 170,
"end": 311
} | public class ____
{
ISelect<Topic> select => g.pgsql.Select<Topic>();
[Table(Name = "tb_topic111333")]
| DateTimeTest |
csharp | DuendeSoftware__IdentityServer | identity-server/hosts/UI/Main/Pages/Grants/ViewModel.cs | {
"start": 292,
"end": 813
} | public class ____
{
public string? ClientId { get; set; }
public string? ClientName { get; set; }
public string? ClientUrl { get; set; }
public string? ClientLogoUrl { get; set; }
public string? Description { get; set; }
public DateTime Created { get; set; }
public DateTime? Expires { get; set; }
public IEnumerable<string> IdentityGrantNames { get; set; } = Enumerable.Empty<string>();
public IEnumerable<string> ApiGrantNames { get; set; } = Enumerable.Empty<string>();
}
| GrantViewModel |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/TimedTextRubyReserve.cs | {
"start": 256,
"end": 925
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
None = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Before = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
After = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Both = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Outside = 4,
#endif
}
#endif
}
| TimedTextRubyReserve |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Bson/ObjectModel/BsonBinarySubType.cs | {
"start": 731,
"end": 1985
} | public enum ____
{
/// <summary>
/// Binary data.
/// </summary>
Binary = 0x00,
/// <summary>
/// A function.
/// </summary>
Function = 0x01,
/// <summary>
/// Obsolete binary data subtype (use Binary instead).
/// </summary>
[Obsolete("Use Binary instead")]
OldBinary = 0x02,
/// <summary>
/// A UUID in a driver dependent legacy byte order.
/// </summary>
UuidLegacy = 0x03,
/// <summary>
/// A UUID in standard network byte order.
/// </summary>
UuidStandard = 0x04,
/// <summary>
/// An MD5 hash.
/// </summary>
MD5 = 0x05,
/// <summary>
/// Encrypted binary data.
/// </summary>
Encrypted = 0x06,
/// <summary>
/// Column data.
/// </summary>
Column = 0x07,
/// <summary>
/// Sensitive data.
/// </summary>
Sensitive = 0x08,
/// <summary>
/// Vector data.
/// </summary>
Vector = 0x09,
/// <summary>
/// User defined binary data.
/// </summary>
UserDefined = 0x80
}
}
| BsonBinarySubType |
csharp | atata-framework__atata | src/Atata/WebDriver/Builders/Driver/ChromiumDriverBuilder`3.cs | {
"start": 440,
"end": 4191
} | public abstract class ____<TBuilder, TService, TOptions>
: WebDriverBuilder<TBuilder, TService, TOptions>
where TBuilder : ChromiumDriverBuilder<TBuilder, TService, TOptions>
where TService : ChromiumDriverService
where TOptions : ChromiumOptions, new()
{
protected ChromiumDriverBuilder(string alias, string browserName)
: base(alias, browserName)
{
}
/// <summary>
/// Adds arguments to be appended to the browser executable command line.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns>The same builder instance.</returns>
public TBuilder WithArguments(params string[] arguments) =>
WithArguments(arguments.AsEnumerable());
/// <summary>
/// Adds arguments to be appended to the browser executable command line.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns>The same builder instance.</returns>
public TBuilder WithArguments(IEnumerable<string> arguments) =>
WithOptions(options => options.AddArguments(arguments));
/// <summary>
/// Adds the <c>download.default_directory</c> user profile preference to options
/// with the value of Artifacts directory path.
/// </summary>
/// <returns>The same builder instance.</returns>
public TBuilder WithArtifactsAsDownloadDirectory() =>
WithDownloadDirectory(() => AtataContext.ResolveCurrent().ArtifactsPath);
/// <summary>
/// Adds the <c>download.default_directory</c> user profile preference to options
/// with the value specified by <paramref name="directoryPath"/>.
/// </summary>
/// <param name="directoryPath">The directory path.</param>
/// <returns>The same builder instance.</returns>
public TBuilder WithDownloadDirectory(string directoryPath)
{
Guard.ThrowIfNull(directoryPath);
return WithDownloadDirectory(() => directoryPath);
}
/// <summary>
/// Adds the <c>download.default_directory</c> user profile preference to options
/// with the value specified by <paramref name="directoryPathBuilder"/>.
/// </summary>
/// <param name="directoryPathBuilder">The directory path builder.</param>
/// <returns>The same builder instance.</returns>
public TBuilder WithDownloadDirectory(Func<string> directoryPathBuilder)
{
Guard.ThrowIfNull(directoryPathBuilder);
return WithOptions(x => x
.AddUserProfilePreference("download.default_directory", directoryPathBuilder.Invoke()));
}
protected static void ReplaceLocalhostInDebuggerAddress(ICapabilities capabilities, string optionsCapabilityName)
{
if (capabilities.GetCapability(optionsCapabilityName) is Dictionary<string, object> chromiumOptions
&& chromiumOptions.TryGetValue("debuggerAddress", out object debuggerAddressObject)
&& debuggerAddressObject is string debuggerAddress
&& debuggerAddress.Contains("localhost:"))
{
string portString = debuggerAddress[(debuggerAddress.IndexOf(':') + 1)..];
if (int.TryParse(portString, out int port))
{
IPEndPoint? ipEndPoint = GetIPEndPoint(port);
if (ipEndPoint?.AddressFamily == AddressFamily.InterNetwork)
chromiumOptions["debuggerAddress"] = $"127.0.0.1:{port}";
}
}
}
private static IPEndPoint? GetIPEndPoint(int port)
{
try
{
return IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpListeners()
.FirstOrDefault(x => x.Port == port);
}
catch
{
return null;
}
}
}
| ChromiumDriverBuilder |
csharp | OrchardCMS__OrchardCore | test/OrchardCore.Tests/Modules/OrchardCore.Twitter/TwitterClientTests.cs | {
"start": 6989,
"end": 7438
} | public class ____ : HttpMessageHandler
{
public virtual HttpResponseMessage Send(HttpRequestMessage request)
{
throw new NotImplementedException("Now we can setup this method with our mocking framework");
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
return Task.FromResult(Send(request));
}
}
| FakeHttpMessageHandler |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/ClickHouse/ClickhouseIssueTest.cs | {
"start": 229,
"end": 4234
} | public class ____
{
private readonly ITestOutputHelper _output;
private static IFreeSql _fsql;
public ClickhouseIssueTest(ITestOutputHelper output)
{
_output = output;
_fsql = new FreeSqlBuilder().UseConnectionString(DataType.ClickHouse,
"Host=192.168.1.123;Port=8123;Database=test_issue;Compress=True;Min Pool Size=1")
.UseMonitorCommand(cmd => _output.WriteLine($"线程:{cmd.CommandText}\r\n"))
.UseNoneCommandParameter(true)
.UseAdoConnectionPool(true)
.Build();
}
#region https: //github.com/dotnetcore/FreeSql/issues/1813
[Fact]
public void TestIssue1813()
{
//普通修改
_fsql.Update<Person>()
.Set(p => p.Name == "update_name")
.Set(p => p.UpdateTime == DateTime.Now)
.Where(p => p.Id == "25e8d92e-29f2-43ff-b861-9ade0eec4041")
.ExecuteAffrows();
//批量修改
var updatePerson = new List<Person>();
updatePerson.Add(new Person
{
Id = "9cd7af52-85cc-4d26-898a-4020cadb0491",
Name = "update_name1",
UpdateTime = DateTime.Now,
CreateTime = DateTime.Parse("2024-05-30 10:01:02")
});
updatePerson.Add(new Person
{
Id = "bd9f9ed6-bd03-4675-abb4-12b7fdac7678",
Name = "update_name2",
UpdateTime = DateTime.Now,
CreateTime = DateTime.Parse("2024-05-30 10:01:02")
});
var sql = _fsql.Update<Person>().SetSource(updatePerson)
.UpdateColumns(person => new
{
person.Name,
person.UpdateTime,
person.CreateTime
}).ToSql();
}
[Fact]
public void TestIssue1813CodeFirst()
{
_fsql.CodeFirst.SyncStructure<Person>();
var insertSingle = _fsql.Insert(new Person
{
Name = $"test{DateTime.Now.Millisecond}",
Age = 18,
CreateTime = DateTime.Now
}).ExecuteAffrows();
_output.WriteLine(insertSingle.ToString());
var persons = new List<Person>
{
new Person
{
Name = $"test2{DateTime.Now.Millisecond}",
Age = 20,
CreateTime = DateTime.Now
},
new Person
{
Name = "test3" + 286,
Age = 22,
CreateTime = DateTime.Now
}
};
var insertMany = _fsql.Insert(persons).ExecuteAffrows();
}
[Fact]
public void TestIssue1813CodeFirst2()
{
_fsql.CodeFirst.SyncStructure<Person>();
var insertSingle = _fsql.Insert(new Person
{
Id = Guid.NewGuid().ToString(),
Name = $"test{DateTime.Now.Millisecond}",
Age = 18,
CreateTime = DateTime.Now
}).ExecuteAffrows();
_output.WriteLine(insertSingle.ToString());
var persons = new List<Person>
{
new Person
{
Id = Guid.NewGuid().ToString(),
Name = $"test2{DateTime.Now.Millisecond}",
Age = 20,
CreateTime = DateTime.Now
},
new Person
{
Id = Guid.NewGuid().ToString(),
Name = "test3" + 286,
Age = 22,
CreateTime = DateTime.Now
}
};
var insertMany = _fsql.Insert(persons).ExecuteAffrows();
}
| ClickhouseIssueTest |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls.Primitives/ButtonBase.cs | {
"start": 272,
"end": 2675
} | public partial class ____ : global::Microsoft.UI.Xaml.Controls.ContentControl
{
// Skipping already declared property CommandParameter
// Skipping already declared property Command
// Skipping already declared property ClickMode
// Skipping already declared property IsPointerOver
// Skipping already declared property IsPressed
// Skipping already declared property ClickModeProperty
// Skipping already declared property CommandParameterProperty
// Skipping already declared property CommandProperty
// Skipping already declared property IsPointerOverProperty
// Skipping already declared property IsPressedProperty
// Skipping already declared method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.ButtonBase()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.ButtonBase()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.ClickMode.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.ClickMode.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.IsPointerOver.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.IsPressed.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.Command.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.Command.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.CommandParameter.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.CommandParameter.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.Click.add
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.Click.remove
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.ClickModeProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.IsPointerOverProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.IsPressedProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.CommandProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.CommandParameterProperty.get
// Skipping already declared event Microsoft.UI.Xaml.Controls.Primitives.ButtonBase.Click
}
}
| ButtonBase |
csharp | dotnetcore__FreeSql | Providers/FreeSql.Provider.Sqlite/Curd/SqliteSelect.cs | {
"start": 22741,
"end": 23308
} | class ____ T13 : class
{
public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
public override string ToSql(string field = null) => SqliteSelect<T1>.ToSqlStatic(_commonUtils, _commonExpression, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, this.GetTableRuleUnions(), _aliasRule, _tosqlAppendContent, _whereGlobalFilter, _orm);
}
| where |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1887178,
"end": 1889535
} | public partial class ____ : global::System.IEquatable<OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress>, IOnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress
{
public OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.ProcessingState state)
{
this.__typename = __typename;
State = state;
}
/// <summary>
/// The name of the current Object type at runtime.
/// </summary>
public global::System.String __typename { get; }
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ProcessingState State { get; }
public virtual global::System.Boolean Equals(OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (__typename.Equals(other.__typename)) && State.Equals(other.State);
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * __typename.GetHashCode();
hash ^= 397 * State.GetHashCode();
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_OperationInProgress |
csharp | dotnet__efcore | test/EFCore.Tests/Infrastructure/ModelValidatorTestBase.cs | {
"start": 11214,
"end": 11393
} | protected class ____
{
public int BlogOwnedEntityId { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
| BlogOwnedEntity |
csharp | atata-framework__atata | src/Atata/ScopeSearch/Strategies/FindLastDescendantStrategy.cs | {
"start": 19,
"end": 273
} | public class ____ : XPathComponentScopeFindStrategy
{
protected override string Build(ComponentScopeXPathBuilder builder, ComponentScopeFindOptions options) =>
builder.Wrap(x => x.OuterXPath.ComponentXPath)["last()"];
}
| FindLastDescendantStrategy |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.ActivityLog/Models/Activity.cs | {
"start": 160,
"end": 597
} | public class ____ : EntityBase
{
public long ActivityTypeId { get; set; }
public ActivityType ActivityType { get; set; }
public long UserId { get; set; }
public DateTimeOffset CreatedOn { get; set; }
public long EntityId { get; set; }
[Required(ErrorMessage = "The {0} field is required.")]
[StringLength(450)]
public string EntityTypeId { get; set; }
}
}
| Activity |
csharp | dotnet__reactive | Ix.NET/Source/System.Linq.Async/System/Linq/Operators/AppendPrepend.cs | {
"start": 4949,
"end": 11115
} | private sealed class ____<TSource> : AppendPrependAsyncIterator<TSource>
{
private readonly TSource _item;
private readonly bool _appending;
private bool _hasEnumerator;
public AppendPrepend1AsyncIterator(IAsyncEnumerable<TSource> source, TSource item, bool appending)
: base(source)
{
_item = item;
_appending = appending;
}
public override AsyncIteratorBase<TSource> Clone()
{
return new AppendPrepend1AsyncIterator<TSource>(_source, _item, _appending);
}
protected override async ValueTask<bool> MoveNextCore()
{
switch (_state)
{
case AsyncIteratorState.Allocated:
_hasEnumerator = false;
_state = AsyncIteratorState.Iterating;
if (!_appending)
{
_current = _item;
return true;
}
goto case AsyncIteratorState.Iterating;
case AsyncIteratorState.Iterating:
if (!_hasEnumerator)
{
GetSourceEnumerator(_cancellationToken);
_hasEnumerator = true;
}
if (_enumerator != null)
{
if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
{
return true;
}
if (_appending)
{
_current = _item;
return true;
}
}
break;
}
await DisposeAsync().ConfigureAwait(false);
return false;
}
public override AppendPrependAsyncIterator<TSource> Append(TSource element)
{
if (_appending)
{
return new AppendPrependNAsyncIterator<TSource>(_source, null, new SingleLinkedNode<TSource>(_item).Add(element), prependCount: 0, appendCount: 2);
}
else
{
return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(_item), new SingleLinkedNode<TSource>(element), prependCount: 1, appendCount: 1);
}
}
public override AppendPrependAsyncIterator<TSource> Prepend(TSource element)
{
if (_appending)
{
return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(element), new SingleLinkedNode<TSource>(_item), prependCount: 1, appendCount: 1);
}
else
{
return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(_item).Add(element), null, prependCount: 2, appendCount: 0);
}
}
public override async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
{
var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
if (count == -1)
{
return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
var array = new TSource[count];
int index;
if (_appending)
{
index = 0;
}
else
{
array[0] = _item;
index = 1;
}
if (_source is ICollection<TSource> sourceCollection)
{
sourceCollection.CopyTo(array, index);
}
else
{
await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
array[index] = item;
++index;
}
}
if (_appending)
{
array[array.Length - 1] = _item;
}
return array;
}
public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
{
var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var list = count == -1 ? [] : new List<TSource>(count);
if (!_appending)
{
list.Add(_item);
}
await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
list.Add(item);
}
if (_appending)
{
list.Add(_item);
}
return list;
}
public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
{
if (_source is IAsyncIListProvider<TSource> listProv)
{
var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
return count == -1 ? -1 : count + 1;
}
return !onlyIfCheap || _source is ICollection<TSource> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + 1 : -1;
}
}
| AppendPrepend1AsyncIterator |
csharp | CommunityToolkit__Maui | samples/CommunityToolkit.Maui.Sample/ViewModels/Converters/InvertedBoolConverterViewModel.cs | {
"start": 109,
"end": 247
} | public partial class ____ : BaseViewModel
{
[ObservableProperty]
public partial bool IsToggled { get; set; }
} | InvertedBoolConverterViewModel |
csharp | dotnet__orleans | src/api/Orleans.Streaming/Orleans.Streaming.cs | {
"start": 43371,
"end": 43586
} | partial class ____
{
[Id(0)]
public GeneratedEventType EventType { get { throw null; } set { } }
[Id(1)]
public int[] Payload { get { throw null; } set { } }
| GeneratedEvent |
csharp | dotnet__maui | src/TestUtils/src/Microsoft.Maui.IntegrationTests/Utilities/Categories.cs | {
"start": 45,
"end": 667
} | static class ____
{
// this is a special job that runs on the samples
public const string Samples = nameof(Samples);
// these are special run on "device" jobs
public const string RunOnAndroid = nameof(RunOnAndroid);
public const string RunOniOS = nameof(RunOniOS);
// these are normal jobs
public const string WindowsTemplates = nameof(WindowsTemplates);
public const string macOSTemplates = nameof(macOSTemplates);
public const string Build = nameof(Build);
public const string Blazor = nameof(Blazor);
public const string MultiProject = nameof(MultiProject);
public const string AOT = nameof(AOT);
}
| Categories |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue27519.cs | {
"start": 197,
"end": 647
} | public class ____ : _IssuesUITest
{
public Issue27519(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "When opening the Picker, the first item is selected instead of the currently selected item";
[Test]
[Category(UITestCategories.Picker)]
public void CorrectItemShouldBeSelectedWhenOpeningPicker()
{
App.WaitForElement("Picker");
App.Click("Picker");
VerifyScreenshot();
}
}
}
#endif | Issue27519 |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexDeploymentStepDriver.cs | {
"start": 285,
"end": 2010
} | public sealed class ____ : DisplayDriver<DeploymentStep, AzureAISearchIndexDeploymentStep>
{
private readonly IIndexProfileStore _store;
public AzureAISearchIndexDeploymentStepDriver(IIndexProfileStore store)
{
_store = store;
}
public override Task<IDisplayResult> DisplayAsync(AzureAISearchIndexDeploymentStep step, BuildDisplayContext context)
{
return CombineAsync(
View("AzureAISearchIndexDeploymentStep_Fields_Summary", step).Location(OrchardCoreConstants.DisplayType.Summary, "Content"),
View("AzureAISearchIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content")
);
}
public override IDisplayResult Edit(AzureAISearchIndexDeploymentStep step, BuildEditorContext context)
{
return Initialize<AzureAISearchIndexDeploymentStepViewModel>("AzureAISearchIndexDeploymentStep_Fields_Edit", async model =>
{
model.IncludeAll = step.IncludeAll;
model.IndexNames = step.IndexNames;
model.AllIndexNames = (await _store.GetByProviderAsync(AzureAISearchConstants.ProviderName)).Select(x => x.IndexName).ToArray();
}).Location("Content");
}
public override async Task<IDisplayResult> UpdateAsync(AzureAISearchIndexDeploymentStep step, UpdateEditorContext context)
{
step.IndexNames = [];
await context.Updater.TryUpdateModelAsync(step, Prefix,
p => p.IncludeAll,
p => p.IndexNames);
if (step.IncludeAll)
{
// Clear index names if the user select include all.
step.IndexNames = [];
}
return Edit(step, context);
}
}
| AzureAISearchIndexDeploymentStepDriver |
csharp | protobuf-net__protobuf-net | src/Examples/SetTests.cs | {
"start": 3640,
"end": 6708
} | class ____
{
public NotEmptySetData() => Data = new HashSet<int>(new[] { 1 });
public NotEmptySetData(ISet<int> data) => Data = data;
[ProtoMember(1)]
public ISet<int> Data { get; }
}
[Fact]
public void TestEmptyNestedSetWithStrings()
{
var set = new HashSet<string>();
var input = new SetData<string>() { Data = set };
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
Assert.Null(clone.Data);
}
[Fact]
public void TestNullNestedSetWithStrings()
{
var input = new SetData<string>() { Data = null };
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
Assert.Equal(input.Data, clone.Data);
}
[Fact]
public void TestNestedSetWithStrings()
{
var set = new HashSet<string>();
set.Add("hello");
set.Add("world");
var input = new SetData<string>() { Data = set };
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
AssertEqual(input.Data, clone.Data);
}
[Fact]
public void TestNestedSetWithInt32()
{
var set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);
set.Add(3);
var input = new SetData<int>() { Data = set };
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
AssertEqual(input.Data, clone.Data);
}
[Fact]
public void RoundtripSet()
{
ISet<int> lookup = new HashSet<int>(new[] { 1, 2, 3 });
var clone = Serializer.DeepClone(lookup);
AssertEqual(lookup, clone);
}
[Fact]
public void TestNonEmptySetStrings()
{
var set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(2);
var input = new NotEmptySetData(set);
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
AssertEqual(input.Data, clone.Data);
}
[Fact]
public void TestDefaultCtorValueOverwritten()
{
var set = new HashSet<int>();
set.Add(3);
var input = new NotEmptySetData(set);
var clone = Serializer.DeepClone(input);
Assert.NotSame(input, clone);
Assert.True(clone.Data.Contains(new NotEmptySetData().Data.Single()));
Assert.True(clone.Data.Contains(3));
}
static void AssertEqual<T>(
ISet<T> expected,
ISet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
foreach (var value in expected)
Assert.True(actual.Contains(value));
}
}
#if NET6_0_OR_GREATER
| NotEmptySetData |
csharp | dotnet__reactive | Ix.NET/Source/System.Linq.Async/System/Linq/Operators/DefaultIfEmpty.cs | {
"start": 449,
"end": 2614
} | partial class ____
#endif
{
#if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
/// <summary>
/// Returns the elements of the specified sequence or the type parameter's default value in a singleton sequence if the sequence is empty.
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence (if any), whose default value will be taken if the sequence is empty.</typeparam>
/// <param name="source">The sequence to return a default value for if it is empty.</param>
/// <returns>An async-enumerable sequence that contains the default value for the TSource type if the source is empty; otherwise, the elements of the source itself.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source) =>
DefaultIfEmpty(source, default!);
/// <summary>
/// Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence (if any), and the specified default value which will be taken if the sequence is empty.</typeparam>
/// <param name="source">The sequence to return the specified value for if it is empty.</param>
/// <param name="defaultValue">The value to return if the sequence is empty.</param>
/// <returns>An async-enumerable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source, TSource defaultValue)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
return new DefaultIfEmptyAsyncIterator<TSource>(source, defaultValue);
}
| AsyncEnumerable |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/Mappings/ConstructorParameter/CultureInfoAttributeTests.cs | {
"start": 3731,
"end": 4071
} | private class ____
{
public int Id { get; private set; }
public decimal Amount1 { get; private set; }
public decimal Amount2 { get; private set; }
public Foo(int id, [CultureInfo("fr-FR")] decimal amount1, decimal amount2)
{
Id = id;
Amount1 = amount1;
Amount2 = amount2;
}
}
[CultureInfo("en-GB")]
| Foo |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/TypeFilterTests.cs | {
"start": 9104,
"end": 9462
} | public class ____
{
// None of these methods are actually Benchmarks!!
[UsedImplicitly]
public void Method1() { }
[UsedImplicitly]
public void Method2() { }
[UsedImplicitly]
public void Method3() { }
}
[GenericTypeArguments(typeof(int))]
[GenericTypeArguments(typeof(string))]
| ClassC |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/Client/src/Core/OperationRequest.cs | {
"start": 288,
"end": 7702
} | public sealed class ____ : IEquatable<OperationRequest>
{
private Dictionary<string, object?>? _extensions;
private Dictionary<string, object?>? _contextData;
private string? _hash;
/// <summary>
/// Creates a new instance of <see cref="OperationRequest"/>.
/// </summary>
/// <param name="name">The operation name.</param>
/// <param name="document">The GraphQL query document containing this operation.</param>
/// <param name="variables">The request variable values.</param>
/// <param name="strategy">The request strategy to the connection.</param>
/// <param name="files">The files of this request</param>
public OperationRequest(
string name,
IDocument document,
IReadOnlyDictionary<string, object?>? variables = null,
IReadOnlyDictionary<string, Upload?>? files = null,
RequestStrategy strategy = RequestStrategy.Default)
: this(null, name, document, variables, files, strategy)
{
}
/// <summary>
/// Creates a new instance of <see cref="OperationRequest"/>.
/// </summary>
/// <param name="id">The the optional request id.</param>
/// <param name="name">The operation name.</param>
/// <param name="document">The GraphQL query document containing this operation.</param>
/// <param name="variables">The request variable values.</param>
/// <param name="strategy">The request strategy to the connection.</param>
/// <param name="files">The files of this request</param>
public OperationRequest(
string? id,
string name,
IDocument document,
IReadOnlyDictionary<string, object?>? variables = null,
IReadOnlyDictionary<string, Upload?>? files = null,
RequestStrategy strategy = RequestStrategy.Default)
{
Id = id;
Name = name ?? throw new ArgumentNullException(nameof(name));
Document = document ?? throw new ArgumentNullException(nameof(document));
Variables = variables ?? ImmutableDictionary<string, object?>.Empty;
Files = files ?? ImmutableDictionary<string, Upload?>.Empty;
Strategy = strategy;
}
/// <summary>
/// Deconstructs <see cref="OperationRequest"/>.
/// </summary>
/// <param name="id">The the optional request id.</param>
/// <param name="name">The operation name.</param>
/// <param name="document">The GraphQL query document containing this operation.</param>
/// <param name="variables">The request variable values.</param>
/// <param name="extensions">The request extension values.</param>
/// <param name="contextData">The local context data.</param>
/// <param name="strategy">The request strategy to the connection.</param>
/// <param name="files">The files of the request</param>
public void Deconstruct(
out string? id,
out string name,
out IDocument document,
out IReadOnlyDictionary<string, object?> variables,
out IReadOnlyDictionary<string, object?>? extensions,
out IReadOnlyDictionary<string, object?>? contextData,
out IReadOnlyDictionary<string, Upload?>? files,
out RequestStrategy strategy)
{
id = Id;
name = Name;
document = Document;
variables = Variables;
extensions = _extensions;
contextData = _contextData;
files = Files;
strategy = Strategy;
}
/// <summary>
/// Gets the optional request id.
/// </summary>
public string? Id { get; }
/// <summary>
/// Gets the operation name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the GraphQL query document containing this operation.
/// </summary>
public IDocument Document { get; }
/// <summary>
/// Gets the request variable values.
/// </summary>
public IReadOnlyDictionary<string, object?> Variables { get; }
/// <summary>
/// The files of the request
/// </summary>
public IReadOnlyDictionary<string, Upload?> Files { get; }
/// <summary>
/// Gets the request extension values.
/// </summary>
public IDictionary<string, object?> Extensions
{
get
{
return _extensions ??= [];
}
}
/// <summary>
/// Gets the local context data.
/// </summary>
public IDictionary<string, object?> ContextData
{
get
{
return _contextData ??= [];
}
}
/// <summary>
/// Defines the request strategy to the connection.
/// </summary>
public RequestStrategy Strategy { get; }
/// <summary>
/// Gets the request extension values or null.
/// </summary>
public IReadOnlyDictionary<string, object?>? GetExtensionsOrNull() =>
_extensions;
/// <summary>
/// Gets the request context data values or null.
/// </summary>
public IReadOnlyDictionary<string, object?>? GetContextDataOrNull() =>
_contextData;
public bool Equals(OperationRequest? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Id == other.Id
&& Name == other.Name
&& Document.Equals(other.Document)
&& ComparisonHelper.DictionaryEqual(Variables, other.Variables);
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((OperationRequest)obj);
}
public string GetHash()
{
if (_hash is null)
{
using var writer = new ArrayWriter();
var serializer = new JsonOperationRequestSerializer();
serializer.Serialize(this, writer, ignoreExtensions: true);
using var sha256 = SHA256.Create();
var buffer = sha256.ComputeHash(writer.GetInternalBuffer(), 0, writer.Length);
_hash = Convert.ToBase64String(buffer);
}
return _hash;
}
public override int GetHashCode()
{
unchecked
{
var hash =
(Id?.GetHashCode() ?? 0) * 397
^ Name.GetHashCode() * 397
^ Document.GetHashCode() * 397;
foreach (var variable in Variables)
{
if (variable.Value is not string && variable.Value is IEnumerable inner)
{
hash ^= GetHashCodeFromList(inner) * 397;
}
else
{
hash ^= variable.GetHashCode();
}
}
return hash;
}
}
private static int GetHashCodeFromList(IEnumerable enumerable)
{
var hash = 17;
foreach (var element in enumerable)
{
if (element is not string && element is IEnumerable inner)
{
hash ^= GetHashCodeFromList(inner) * 397;
}
else if (element is not null)
{
hash ^= element.GetHashCode() * 397;
}
}
return hash;
}
}
| OperationRequest |
csharp | Testably__Testably.Abstractions | Source/Testably.Abstractions.Interface/IRandomSystem.cs | {
"start": 170,
"end": 431
} | public interface ____
{
/// <summary>
/// Abstractions for <see cref="System.Guid" />.
/// </summary>
IGuid Guid { get; }
/// <summary>
/// Abstractions for <see cref="System.Random" />.
/// </summary>
IRandomFactory Random { get; }
}
| IRandomSystem |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/TypeSystem/ITypeDefinitionOrUnknown.cs | {
"start": 1251,
"end": 1351
} | record ____ unknown type.
/// For partial classes, this represents the whole class.
/// </summary>
| or |
csharp | dotnet__aspnetcore | src/Http/Http.Abstractions/src/HttpResults/IResult.cs | {
"start": 276,
"end": 627
} | public interface ____
{
/// <summary>
/// Write an HTTP response reflecting the result.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> for the current request.</param>
/// <returns>A task that represents the asynchronous execute operation.</returns>
Task ExecuteAsync(HttpContext httpContext);
}
| IResult |
csharp | Xabaril__AspNetCore.Diagnostics.HealthChecks | test/HealthChecks.Publisher.Seq.Tests/DependencyInjection/RegistrationTests.cs | {
"start": 69,
"end": 710
} | public class ____
{
[Fact]
public void add_healthcheck_when_properly_configured()
{
var services = new ServiceCollection();
services
.AddHealthChecks()
.AddSeqPublisher(setup =>
{
setup.Endpoint = "endpoint";
setup.DefaultInputLevel = Seq.SeqInputLevel.Information;
setup.ApiKey = "apiKey";
});
using var serviceProvider = services.BuildServiceProvider();
var publisher = serviceProvider.GetService<IHealthCheckPublisher>();
publisher.ShouldNotBeNull();
}
}
| seq_publisher_registration_should |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json/Utilities/DynamicUtils.cs | {
"start": 1674,
"end": 8024
} | internal static class ____
{
#if !HAVE_REFLECTION_BINDER
public const string CSharpAssemblyName = "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
private const string BinderTypeName = "Microsoft.CSharp.RuntimeBinder.Binder, " + CSharpAssemblyName;
private const string CSharpArgumentInfoTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo, " + CSharpAssemblyName;
private const string CSharpArgumentInfoFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, " + CSharpAssemblyName;
private const string CSharpBinderFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, " + CSharpAssemblyName;
private static object? _getCSharpArgumentInfoArray;
private static object? _setCSharpArgumentInfoArray;
private static MethodCall<object?, object?>? _getMemberCall;
private static MethodCall<object?, object?>? _setMemberCall;
private static bool _init;
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static void Init()
{
if (!_init)
{
Type? binderType = Type.GetType(BinderTypeName, false);
if (binderType == null)
{
throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName));
}
// None
_getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0);
// None, Constant | UseCompileTimeType
_setCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0, 3);
CreateMemberCalls();
_init = true;
}
}
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static object CreateSharpArgumentInfoArray(params int[] values)
{
Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!;
Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName, true)!;
Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length);
for (int i = 0; i < values.Length; i++)
{
MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) })!;
object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null })!;
a.SetValue(arg, i);
}
return a;
}
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static void CreateMemberCalls()
{
Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!;
Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true)!;
Type binderType = Type.GetType(BinderTypeName, true)!;
Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType);
MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!;
_getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object?>(getMemberMethod);
MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!;
_setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object?>(setMemberMethod);
}
#endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static CallSiteBinder GetMember(string name, Type context)
{
#if !HAVE_REFLECTION_BINDER
Init();
MiscellaneousUtils.Assert(_getMemberCall != null);
MiscellaneousUtils.Assert(_getCSharpArgumentInfoArray != null);
return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray)!;
#else
return Binder.GetMember(
CSharpBinderFlags.None, name, context, new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
#endif
}
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static CallSiteBinder SetMember(string name, Type context)
{
#if !HAVE_REFLECTION_BINDER
Init();
MiscellaneousUtils.Assert(_setMemberCall != null);
MiscellaneousUtils.Assert(_setCSharpArgumentInfoArray != null);
return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray)!;
#else
return Binder.SetMember(
CSharpBinderFlags.None, name, context, new[]
{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null)
});
#endif
}
}
public static IEnumerable<string> GetDynamicMemberNames(this IDynamicMetaObjectProvider dynamicProvider)
{
DynamicMetaObject metaObject = dynamicProvider.GetMetaObject(Expression.Constant(dynamicProvider));
return metaObject.GetDynamicMemberNames();
}
}
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
| BinderWrapper |
csharp | nunit__nunit | src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs | {
"start": 11555,
"end": 13272
} | public class ____ : IDictionary
{
private readonly int _key;
public TestNonGenericDictionary(int key)
{
_key = key;
}
public bool Contains(object key)
{
return _key == (int)key;
}
public void Add(object key, object? value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public IDictionaryEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void Remove(object key)
{
throw new NotImplementedException();
}
public object? this[object key]
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public ICollection Keys => throw new NotImplementedException();
public ICollection Values => throw new NotImplementedException();
public bool IsReadOnly { get; }
public bool IsFixedSize { get; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public int Count { get; }
public object SyncRoot => throw new NotImplementedException();
public bool IsSynchronized { get; }
}
| TestNonGenericDictionary |
csharp | dotnet__aspnetcore | src/Security/CookiePolicy/test/CookieConsentTests.cs | {
"start": 536,
"end": 26803
} | public class ____
{
[Fact]
public async Task ConsentChecksOffByDefault()
{
var httpContext = await RunTestAsync(options => { }, requestContext => { }, context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.False(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task ConsentEnabledForTemplateScenario()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { }, context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task NonEssentialCookiesWithOptionsExcluded()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { }, context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = false });
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task NonEssentialCookiesCanBeAllowedViaOnAppendCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.OnAppendCookie = context =>
{
Assert.True(context.IsConsentNeeded);
Assert.False(context.HasConsent);
Assert.False(context.IssueCookie);
context.IssueCookie = true;
};
},
requestContext => { }, context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = false });
return Task.CompletedTask;
});
Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task NeedsConsentDoesNotPreventEssentialCookies()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { }, context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = true });
return Task.CompletedTask;
});
Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task EssentialCookiesCanBeExcludedByOnAppendCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.OnAppendCookie = context =>
{
Assert.True(context.IsConsentNeeded);
Assert.True(context.HasConsent);
Assert.True(context.IssueCookie);
context.IssueCookie = false;
};
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = true });
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task HasConsentReadsRequestCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task HasConsentIgnoresInvalidRequestCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=IAmATeapot";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task GrantConsentSetsCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Equal(2, cookies.Count);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent", consentCookie.Name.AsSpan());
Assert.Equal("yes", consentCookie.Value.AsSpan());
Assert.True(consentCookie.Expires.HasValue);
Assert.True(consentCookie.Expires.Value > DateTimeOffset.Now + TimeSpan.FromDays(364));
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
var testCookie = cookies[1];
Assert.Equal("Test", testCookie.Name.AsSpan());
Assert.Equal("Value", testCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite);
Assert.Null(testCookie.Expires);
}
[Fact]
public async Task GrantConsentAppliesPolicyToConsentCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Http.SameSiteMode.Strict;
options.OnAppendCookie = context =>
{
Assert.Equal(".AspNet.Consent", context.CookieName.AsSpan());
Assert.Equal("yes", context.CookieValue.AsSpan());
Assert.Equal(Http.SameSiteMode.Strict, context.CookieOptions.SameSite);
context.CookieName += "1";
context.CookieValue += "1";
context.CookieOptions.Extensions.Add("extension");
};
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent1", consentCookie.Name.AsSpan());
Assert.Equal("yes1", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
Assert.Contains("extension", consentCookie.Extensions);
}
[Fact]
public async Task GrantConsentWhenAlreadyHasItDoesNotSetCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task GrantConsentAfterResponseStartsSetsHasConsentButDoesNotSetCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { },
async context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
await context.Response.WriteAsync("Started.");
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
Assert.Throws<InvalidOperationException>(() => context.Response.Cookies.Append("Test", "Value"));
await context.Response.WriteAsync("Granted.");
});
var reader = new StreamReader(httpContext.Response.Body);
Assert.Equal("Started.Granted.", await reader.ReadToEndAsync());
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task WithdrawConsentWhenNotHasConsentNoOps()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.WithdrawConsent();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value");
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task WithdrawConsentDeletesCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value1");
feature.WithdrawConsent();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value2");
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Equal(2, cookies.Count);
var testCookie = cookies[0];
Assert.Equal("Test", testCookie.Name.AsSpan());
Assert.Equal("Value1", testCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite);
Assert.Null(testCookie.Expires);
var consentCookie = cookies[1];
Assert.Equal(".AspNet.Consent", consentCookie.Name.AsSpan());
Assert.Equal("", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
}
[Fact]
public async Task WithdrawConsentAppliesPolicyToDeleteCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Http.SameSiteMode.Strict;
options.OnDeleteCookie = context =>
{
Assert.Equal(".AspNet.Consent", context.CookieName.AsSpan());
context.CookieName += "1";
};
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
feature.WithdrawConsent();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent1", consentCookie.Name.AsSpan());
Assert.Equal("", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
}
[Fact]
public async Task WithdrawConsentAfterResponseHasStartedDoesNotDeleteCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext =>
{
requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes";
},
async context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
context.Response.Cookies.Append("Test", "Value1");
await context.Response.WriteAsync("Started.");
feature.WithdrawConsent();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
// Doesn't throw the normal InvalidOperationException because the cookie is never written
context.Response.Cookies.Append("Test", "Value2");
await context.Response.WriteAsync("Withdrawn.");
});
var reader = new StreamReader(httpContext.Response.Body);
Assert.Equal("Started.Withdrawn.", await reader.ReadToEndAsync());
Assert.Equal("Test=Value1; path=/", httpContext.Response.Headers.SetCookie);
}
[Fact]
public async Task DeleteCookieDoesNotRequireConsent()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Delete("Test");
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var testCookie = cookies[0];
Assert.Equal("Test", testCookie.Name.AsSpan());
Assert.Equal("", testCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite);
Assert.NotNull(testCookie.Expires);
}
[Fact]
public async Task OnDeleteCookieCanSuppressCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.OnDeleteCookie = context =>
{
Assert.True(context.IsConsentNeeded);
Assert.False(context.HasConsent);
Assert.True(context.IssueCookie);
context.IssueCookie = false;
};
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
context.Response.Cookies.Delete("Test");
return Task.CompletedTask;
});
Assert.Equal(0, httpContext.Response.Headers.SetCookie.Count);
}
[Fact]
public async Task CreateConsentCookieMatchesGrantConsentCookie()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
var cookie = feature.CreateConsentCookie();
context.Response.Headers["ManualCookie"] = cookie;
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent", consentCookie.Name.AsSpan());
Assert.Equal("yes", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]);
Assert.Single(cookies);
var manualCookie = cookies[0];
Assert.Equal(consentCookie.Name, manualCookie.Name);
Assert.Equal(consentCookie.Value, manualCookie.Value);
Assert.Equal(consentCookie.SameSite, manualCookie.SameSite);
Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second.
}
[Fact]
public async Task CreateConsentCookieAppliesPolicy()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Http.SameSiteMode.Strict;
options.OnAppendCookie = context =>
{
Assert.Equal(".AspNet.Consent", context.CookieName);
Assert.Equal("yes", context.CookieValue);
Assert.Equal(Http.SameSiteMode.Strict, context.CookieOptions.SameSite);
context.CookieName += "1";
context.CookieValue += "1";
};
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
var cookie = feature.CreateConsentCookie();
context.Response.Headers["ManualCookie"] = cookie;
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent1", consentCookie.Name.AsSpan());
Assert.Equal("yes1", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]);
Assert.Single(cookies);
var manualCookie = cookies[0];
Assert.Equal(consentCookie.Name, manualCookie.Name);
Assert.Equal(consentCookie.Value, manualCookie.Value);
Assert.Equal(consentCookie.SameSite, manualCookie.SameSite);
Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second.
}
[Fact]
public async Task CreateConsentCookieMatchesGrantConsentCookieWhenCookieValueIsCustom()
{
var httpContext = await RunTestAsync(options =>
{
options.CheckConsentNeeded = context => true;
options.ConsentCookieValue = "true";
},
requestContext => { },
context =>
{
var feature = context.Features.Get<ITrackingConsentFeature>();
Assert.True(feature.IsConsentNeeded);
Assert.False(feature.HasConsent);
Assert.False(feature.CanTrack);
feature.GrantConsent();
Assert.True(feature.IsConsentNeeded);
Assert.True(feature.HasConsent);
Assert.True(feature.CanTrack);
var cookie = feature.CreateConsentCookie();
context.Response.Headers["ManualCookie"] = cookie;
return Task.CompletedTask;
});
var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);
Assert.Single(cookies);
var consentCookie = cookies[0];
Assert.Equal(".AspNet.Consent", consentCookie.Name.AsSpan());
Assert.Equal("true", consentCookie.Value.AsSpan());
Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite);
Assert.NotNull(consentCookie.Expires);
cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]);
Assert.Single(cookies);
var manualCookie = cookies[0];
Assert.Equal(consentCookie.Name, manualCookie.Name);
Assert.Equal(consentCookie.Value, manualCookie.Value);
Assert.Equal(consentCookie.SameSite, manualCookie.SameSite);
Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second.
}
[Theory]
[InlineData(null, "Value cannot be null.")]
[InlineData("", "The value cannot be an empty string.")]
public void CreateCookiePolicyOptionsWithEmptyConsentCookieValueThrows(string value, string expectedMessage)
{
var options = new CookiePolicyOptions();
ExceptionAssert.ThrowsArgument(
() => options.ConsentCookieValue = value,
"value",
expectedMessage);
}
private async Task<HttpContext> RunTestAsync(Action<CookiePolicyOptions> configureOptions, Action<HttpContext> configureRequest, RequestDelegate handleRequest)
{
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy();
app.Run(handleRequest);
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.Configure(configureOptions);
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
return await server.SendAsync(configureRequest);
}
}
| CookieConsentTests |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWeb/AutoQueryCrudModels.cs | {
"start": 17999,
"end": 18175
} | public class ____ : RockstarBase, IUpdateDb<NamedRockstar>, IReturn<RockstarWithIdAndResultResponse>
{
public int Id { get; set; }
}
} | UpdateConnectionInfoRockstar |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Data/Mapping/Builders/Topics/TopicTemplateBuilder.cs | {
"start": 197,
"end": 715
} | public partial class ____ : NopEntityBuilder<TopicTemplate>
{
#region Methods
/// <summary>
/// Apply entity configuration
/// </summary>
/// <param name="table">Create table expression builder</param>
public override void MapEntity(CreateTableExpressionBuilder table)
{
table
.WithColumn(nameof(TopicTemplate.Name)).AsString(400).NotNullable()
.WithColumn(nameof(TopicTemplate.ViewPath)).AsString(400).NotNullable();
}
#endregion
} | TopicTemplateBuilder |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Input/GestureRecognizerTests/TappedTest.xaml.cs | {
"start": 294,
"end": 1030
} | partial class ____ : Page
{
public TappedTest()
{
this.InitializeComponent();
}
private void TargetTapped(object sender, TappedRoutedEventArgs e)
{
var target = (FrameworkElement)sender;
var position = e.GetPosition(target).LogicalToPhysicalPixels();
LastTapped.Text = FormattableString.Invariant($"{target.Name}@{position.X:F2},{position.Y:F2}");
e.Handled = target.Name.Contains("Handling");
}
private void ItemTapped(object sender, TappedRoutedEventArgs e)
{
var target = (FrameworkElement)sender;
var position = e.GetPosition(target).LogicalToPhysicalPixels();
LastTapped.Text = FormattableString.Invariant($"Item_{target.DataContext}@{position.X:F2},{position.Y:F2}");
}
}
}
| TappedTest |
csharp | duplicati__duplicati | Duplicati/Library/Backend/OneDrive/MicrosoftGraphTypes.cs | {
"start": 12846,
"end": 13032
} | public class ____
{
[JsonProperty("remoteItem", NullValueHandling = NullValueHandling.Ignore)]
public RemoteItemFacet? RemoteItem { get; set; }
}
| RemoteItemFacet |
csharp | jellyfin__jellyfin | src/Jellyfin.Drawing/ImageProcessor.cs | {
"start": 848,
"end": 17272
} | public sealed class ____ : IImageProcessor, IDisposable
{
// Increment this when there's a change requiring caches to be invalidated
private const char Version = '3';
private static readonly HashSet<string> _transparentImageTypes
= new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif", ".svg" };
private readonly ILogger<ImageProcessor> _logger;
private readonly IFileSystem _fileSystem;
private readonly IServerApplicationPaths _appPaths;
private readonly IImageEncoder _imageEncoder;
private readonly AsyncNonKeyedLocker _parallelEncodingLimit;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="ImageProcessor"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="appPaths">The server application paths.</param>
/// <param name="fileSystem">The filesystem.</param>
/// <param name="imageEncoder">The image encoder.</param>
/// <param name="config">The configuration.</param>
public ImageProcessor(
ILogger<ImageProcessor> logger,
IServerApplicationPaths appPaths,
IFileSystem fileSystem,
IImageEncoder imageEncoder,
IServerConfigurationManager config)
{
_logger = logger;
_fileSystem = fileSystem;
_imageEncoder = imageEncoder;
_appPaths = appPaths;
var semaphoreCount = config.Configuration.ParallelImageEncodingLimit;
if (semaphoreCount < 1)
{
semaphoreCount = Environment.ProcessorCount;
}
_parallelEncodingLimit = new(semaphoreCount);
}
private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
/// <inheritdoc />
public IReadOnlyCollection<string> SupportedInputFormats =>
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"tiff",
"tif",
"jpeg",
"jpg",
"png",
"aiff",
"cr2",
"crw",
"nef",
"orf",
"pef",
"arw",
"webp",
"gif",
"bmp",
"erf",
"raf",
"rw2",
"nrw",
"dng",
"ico",
"astc",
"ktx",
"pkm",
"wbmp",
"avif"
};
/// <inheritdoc />
public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation;
/// <inheritdoc />
public IReadOnlyCollection<ImageFormat> GetSupportedImageOutputFormats()
=> _imageEncoder.SupportedOutputFormats;
/// <inheritdoc />
public async Task<(string Path, string? MimeType, DateTime DateModified)> ProcessImage(ImageProcessingOptions options)
{
ItemImageInfo originalImage = options.Image;
BaseItem item = options.Item;
string originalImagePath = originalImage.Path;
DateTime dateModified = originalImage.DateModified;
ImageDimensions? originalImageSize = null;
if (originalImage.Width > 0 && originalImage.Height > 0)
{
originalImageSize = new ImageDimensions(originalImage.Width, originalImage.Height);
}
var mimeType = MimeTypes.GetMimeType(originalImagePath);
if (!_imageEncoder.SupportsImageEncoding)
{
return (originalImagePath, mimeType, dateModified);
}
var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
originalImagePath = supportedImageInfo.Path;
// Original file doesn't exist, or original file is gif.
if (!File.Exists(originalImagePath) || string.Equals(mimeType, MediaTypeNames.Image.Gif, StringComparison.OrdinalIgnoreCase))
{
return (originalImagePath, mimeType, dateModified);
}
dateModified = supportedImageInfo.DateModified;
bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath));
bool autoOrient = false;
ImageOrientation? orientation = null;
if (item is Photo photo)
{
if (photo.Orientation.HasValue)
{
if (photo.Orientation.Value != ImageOrientation.TopLeft)
{
autoOrient = true;
orientation = photo.Orientation;
}
}
else
{
// Orientation unknown, so do it
autoOrient = true;
orientation = photo.Orientation;
}
}
if (options.HasDefaultOptions(originalImagePath, originalImageSize) && (!autoOrient || !options.RequiresAutoOrientation))
{
// Just spit out the original file if all the options are default
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
int quality = options.Quality;
ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
string cacheFilePath = GetCacheFilePath(
originalImagePath,
options.Width,
options.Height,
options.MaxWidth,
options.MaxHeight,
options.FillWidth,
options.FillHeight,
quality,
dateModified,
outputFormat,
options.PercentPlayed,
options.UnplayedCount,
options.Blur,
options.BackgroundColor,
options.ForegroundLayer);
try
{
if (!File.Exists(cacheFilePath))
{
string resultPath;
// Limit number of parallel (more precisely: concurrent) image encodings to prevent a high memory usage
using (await _parallelEncodingLimit.LockAsync().ConfigureAwait(false))
{
resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);
}
if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
{
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
}
return (cacheFilePath, outputFormat.GetMimeType(), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
}
catch (Exception ex)
{
// If it fails for whatever reason, return the original image
_logger.LogError(ex, "Error encoding image");
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
}
private ImageFormat GetOutputFormat(IReadOnlyCollection<ImageFormat> clientSupportedFormats, bool requiresTransparency)
{
var serverFormats = GetSupportedImageOutputFormats();
// Client doesn't care about format, so start with webp if supported
if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp))
{
return ImageFormat.Webp;
}
// If transparency is needed and webp isn't supported, than png is the only option
if (requiresTransparency && clientSupportedFormats.Contains(ImageFormat.Png))
{
return ImageFormat.Png;
}
foreach (var format in clientSupportedFormats)
{
if (serverFormats.Contains(format))
{
return format;
}
}
// We should never actually get here
return ImageFormat.Jpg;
}
/// <summary>
/// Gets the cache file path based on a set of parameters.
/// </summary>
private string GetCacheFilePath(
string originalPath,
int? width,
int? height,
int? maxWidth,
int? maxHeight,
int? fillWidth,
int? fillHeight,
int quality,
DateTime dateModified,
ImageFormat format,
double percentPlayed,
int? unwatchedCount,
int? blur,
string backgroundColor,
string foregroundLayer)
{
var filename = new StringBuilder(256);
filename.Append(originalPath);
filename.Append(",quality=");
filename.Append(quality);
filename.Append(",datemodified=");
filename.Append(dateModified.Ticks);
filename.Append(",f=");
filename.Append(format);
if (width.HasValue)
{
filename.Append(",width=");
filename.Append(width.Value);
}
if (height.HasValue)
{
filename.Append(",height=");
filename.Append(height.Value);
}
if (maxWidth.HasValue)
{
filename.Append(",maxwidth=");
filename.Append(maxWidth.Value);
}
if (maxHeight.HasValue)
{
filename.Append(",maxheight=");
filename.Append(maxHeight.Value);
}
if (fillWidth.HasValue)
{
filename.Append(",fillwidth=");
filename.Append(fillWidth.Value);
}
if (fillHeight.HasValue)
{
filename.Append(",fillheight=");
filename.Append(fillHeight.Value);
}
if (percentPlayed > 0)
{
filename.Append(",p=");
filename.Append(percentPlayed);
}
if (unwatchedCount.HasValue)
{
filename.Append(",p=");
filename.Append(unwatchedCount.Value);
}
if (blur.HasValue)
{
filename.Append(",blur=");
filename.Append(blur.Value);
}
if (!string.IsNullOrEmpty(backgroundColor))
{
filename.Append(",b=");
filename.Append(backgroundColor);
}
if (!string.IsNullOrEmpty(foregroundLayer))
{
filename.Append(",fl=");
filename.Append(foregroundLayer);
}
filename.Append(",v=");
filename.Append(Version);
return GetCachePath(ResizedImageCachePath, filename.ToString(), format.GetExtension());
}
/// <inheritdoc />
public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info)
{
int width = info.Width;
int height = info.Height;
if (height > 0 && width > 0)
{
return new ImageDimensions(width, height);
}
string path = info.Path;
_logger.LogDebug("Getting image size for item {ItemType} {Path}", item.GetType().Name, path);
ImageDimensions size = GetImageDimensions(path);
info.Width = size.Width;
info.Height = size.Height;
return size;
}
/// <inheritdoc />
public ImageDimensions GetImageDimensions(string path)
=> _imageEncoder.GetImageSize(path);
/// <inheritdoc />
public string GetImageBlurHash(string path)
{
var size = GetImageDimensions(path);
return GetImageBlurHash(path, size);
}
/// <inheritdoc />
public string GetImageBlurHash(string path, ImageDimensions imageDimensions)
{
if (imageDimensions.Width <= 0 || imageDimensions.Height <= 0)
{
return string.Empty;
}
// We want tiles to be as close to square as possible, and to *mostly* keep under 16 tiles for performance.
// One tile is (width / xComp) x (height / yComp) pixels, which means that ideally yComp = xComp * height / width.
// See more at https://github.com/woltapp/blurhash/#how-do-i-pick-the-number-of-x-and-y-components
float xCompF = MathF.Sqrt(16.0f * imageDimensions.Width / imageDimensions.Height);
float yCompF = xCompF * imageDimensions.Height / imageDimensions.Width;
int xComp = Math.Min((int)xCompF + 1, 9);
int yComp = Math.Min((int)yCompF + 1, 9);
return _imageEncoder.GetImageBlurHash(xComp, yComp, path);
}
/// <inheritdoc />
public string GetImageCacheTag(string baseItemPath, DateTime imageDateModified)
=> (baseItemPath + imageDateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture);
/// <inheritdoc />
public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
=> GetImageCacheTag(item.Path, image.DateModified);
/// <inheritdoc />
public string GetImageCacheTag(BaseItemDto item, ItemImageInfo image)
=> GetImageCacheTag(item.Path, image.DateModified);
/// <inheritdoc />
public string? GetImageCacheTag(BaseItemDto item, ChapterInfo chapter)
{
if (chapter.ImagePath is null)
{
return null;
}
return GetImageCacheTag(item.Path, chapter.ImageDateModified);
}
/// <inheritdoc />
public string? GetImageCacheTag(BaseItem item, ChapterInfo chapter)
{
if (chapter.ImagePath is null)
{
return null;
}
return GetImageCacheTag(item, new ItemImageInfo
{
Path = chapter.ImagePath,
Type = ImageType.Chapter,
DateModified = chapter.ImageDateModified
});
}
/// <inheritdoc />
public string? GetImageCacheTag(User user)
{
if (user.ProfileImage is null)
{
return null;
}
return GetImageCacheTag(user.ProfileImage.Path, user.ProfileImage.LastModified);
}
private Task<(string Path, DateTime DateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified)
{
var inputFormat = Path.GetExtension(originalImagePath.AsSpan()).TrimStart('.').ToString();
// These are just jpg files renamed as tbn
if (string.Equals(inputFormat, "tbn", StringComparison.OrdinalIgnoreCase))
{
return Task.FromResult((originalImagePath, dateModified));
}
return Task.FromResult((originalImagePath, dateModified));
}
/// <summary>
/// Gets the cache path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="uniqueName">Name of the unique.</param>
/// <param name="fileExtension">The file extension.</param>
/// <returns>System.String.</returns>
/// <exception cref="ArgumentNullException">
/// path
/// or
/// uniqueName
/// or
/// fileExtension.
/// </exception>
public string GetCachePath(string path, string uniqueName, string fileExtension)
{
ArgumentException.ThrowIfNullOrEmpty(path);
ArgumentException.ThrowIfNullOrEmpty(uniqueName);
ArgumentException.ThrowIfNullOrEmpty(fileExtension);
var filename = uniqueName.GetMD5() + fileExtension;
return GetCachePath(path, filename);
}
/// <summary>
/// Gets the cache path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
/// <exception cref="ArgumentNullException">
/// path
/// or
/// filename.
/// </exception>
public string GetCachePath(ReadOnlySpan<char> path, ReadOnlySpan<char> filename)
{
if (path.IsEmpty)
{
throw new ArgumentException("Path can't be empty.", nameof(path));
}
if (filename.IsEmpty)
{
throw new ArgumentException("Filename can't be empty.", nameof(filename));
}
var prefix = filename.Slice(0, 1);
return Path.Join(path, prefix, filename);
}
/// <inheritdoc />
public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
_logger.LogDebug("Creating image collage and saving to {Path}", options.OutputPath);
_imageEncoder.CreateImageCollage(options, libraryName);
_logger.LogDebug("Completed creation of image collage and saved to {Path}", options.OutputPath);
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
if (_imageEncoder is IDisposable disposable)
{
disposable.Dispose();
}
_parallelEncodingLimit?.Dispose();
_disposed = true;
}
}
| ImageProcessor |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/test/ModelBinding/ParameterBinderTest.cs | {
"start": 32680,
"end": 32771
} | private class ____
{
public BaseModel Model { get; set; }
}
| TestController |
csharp | unoplatform__uno | src/SamplesApp/SamplesApp.UITests/TestFramework/TestFrameworkTests.cs | {
"start": 961,
"end": 1353
} | public partial class ____
{
static int Setup_Count = 0;
[SetUp]
public void Setup()
{
Console.WriteLine($"Setup: {++Setup_Count}");
if (Setup_Count < AutoRetryAttribute.AutoRetryDefaultCount)
{
throw new NotImplementedException();
}
}
[Test]
[AutoRetry]
public void When_Success()
{
Console.WriteLine($"When_Success: {++Setup_Count}");
}
}
| RetrySetup |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/Model/Pfa/ICanSavePfa.cs | {
"start": 347,
"end": 1017
} | internal interface ____
{
/// <summary>
/// Whether this object really is capable of saving itself as part of a PFA
/// pipeline. An implementor of this object might implement this interface,
/// but still return <c>false</c> if there is some characteristic of this object
/// only detectable during runtime that would prevent its being savable. (For example,
/// it may wrap some other object that may or may not be savable.)
/// </summary>
bool CanSavePfa { get; }
}
/// <summary>
/// This component know how to save himself in Pfa format.
/// </summary>
[BestFriend]
| ICanSavePfa |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 152051,
"end": 152268
} | public class ____
{
public int Id { get; set; }
public RelatedEntity701 ParentEntity { get; set; }
public IEnumerable<RelatedEntity703> ChildEntities { get; set; }
}
| RelatedEntity702 |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/Support/GithubGateway.cs | {
"start": 3013,
"end": 3517
} | public class ____
{
public string Id { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public string Name { get; set; }
public int Comment_Count { get; set; }
public GithubByUser Committer { get; set; }
public GithubByUser Author { get; set; }
public bool? ShouldSerialize(string fieldName)
{
return fieldName != "Committer" && fieldName != "Author";
}
}
| GithubCommit |
csharp | FastEndpoints__FastEndpoints | Src/Library/Messaging/Jobs/PendingJobSearchParams.cs | {
"start": 246,
"end": 1180
} | public struct ____<TStorageRecord> where TStorageRecord : IJobStorageRecord
{
/// <summary>
/// the ID of the job queue for fetching the next batch of records for.
/// </summary>
public string QueueID { get; internal set; }
/// <summary>
/// a boolean lambda expression to match the next batch of records
/// <code>
/// r => r.QueueID == "xxx" &&
/// !r.IsComplete &&
/// DateTime.UtcNow >= r.ExecuteAfter &&
/// DateTime.UtcNow <= r.ExpireOn
/// </code>
/// </summary>
public Expression<Func<TStorageRecord, bool>> Match { get; internal set; }
/// <summary>
/// the number of pending records to fetch
/// </summary>
public int Limit { get; internal set; }
/// <summary>
/// cancellation token
/// </summary>
public CancellationToken CancellationToken { get; internal set; }
} | PendingJobSearchParams |
csharp | MonoGame__MonoGame | MonoGame.Framework/Graphics/SpriteFont.cs | {
"start": 517,
"end": 1154
} | internal static class ____
{
public const string TextContainsUnresolvableCharacters =
"Text contains characters that cannot be resolved by this SpriteFont.";
public const string UnresolvableCharacter =
"Character cannot be resolved by this SpriteFont.";
}
private readonly Glyph[] _glyphs;
private readonly CharacterRegion[] _regions;
private char? _defaultCharacter;
private int _defaultGlyphIndex = -1;
private readonly Texture2D _texture;
/// <summary>
/// All the glyphs in this SpriteFont.
/// </summary>
public Glyph[] Glyphs { get { return _glyphs; } }
| Errors |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.Tax/Data/TaxCustomModelBuilder.cs | {
"start": 205,
"end": 641
} | public class ____ : ICustomModelBuilder
{
public void Build(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TaxClass>().HasData(new TaxClass(1) { Name = "Standard VAT" });
modelBuilder.Entity<AppSetting>().HasData(
new AppSetting("Tax.DefaultTaxClassId") { Module = "Tax", IsVisibleInCommonSettingPage = true, Value = "1" }
);
}
}
}
| TaxCustomModelBuilder |
csharp | ShareX__ShareX | ShareX/WatchFolderManager.cs | {
"start": 1151,
"end": 5428
} | public class ____ : IDisposable
{
public List<WatchFolder> WatchFolders { get; private set; }
public void UpdateWatchFolders()
{
if (WatchFolders != null)
{
UnregisterAllWatchFolders();
}
WatchFolders = new List<WatchFolder>();
foreach (WatchFolderSettings defaultWatchFolderSetting in Program.DefaultTaskSettings.WatchFolderList)
{
AddWatchFolder(defaultWatchFolderSetting, Program.DefaultTaskSettings);
}
foreach (HotkeySettings hotkeySetting in Program.HotkeysConfig.Hotkeys)
{
foreach (WatchFolderSettings watchFolderSetting in hotkeySetting.TaskSettings.WatchFolderList)
{
AddWatchFolder(watchFolderSetting, hotkeySetting.TaskSettings);
}
}
}
private WatchFolder FindWatchFolder(WatchFolderSettings watchFolderSetting)
{
return WatchFolders.FirstOrDefault(watchFolder => watchFolder.Settings == watchFolderSetting);
}
private bool IsExist(WatchFolderSettings watchFolderSetting)
{
return FindWatchFolder(watchFolderSetting) != null;
}
public void AddWatchFolder(WatchFolderSettings watchFolderSetting, TaskSettings taskSettings)
{
if (!IsExist(watchFolderSetting))
{
if (!taskSettings.WatchFolderList.Contains(watchFolderSetting))
{
taskSettings.WatchFolderList.Add(watchFolderSetting);
}
WatchFolder watchFolder = new WatchFolder();
watchFolder.Settings = watchFolderSetting;
watchFolder.TaskSettings = taskSettings;
watchFolder.FileWatcherTrigger += origPath =>
{
TaskSettings taskSettingsCopy = TaskSettings.GetSafeTaskSettings(taskSettings);
string destPath = origPath;
if (watchFolderSetting.MoveFilesToScreenshotsFolder)
{
string screenshotsFolder = TaskHelpers.GetScreenshotsFolder(taskSettingsCopy);
string fileName = Path.GetFileName(origPath);
destPath = TaskHelpers.HandleExistsFile(screenshotsFolder, fileName, taskSettingsCopy);
FileHelpers.CreateDirectoryFromFilePath(destPath);
File.Move(origPath, destPath);
}
UploadManager.UploadFile(destPath, taskSettingsCopy);
};
WatchFolders.Add(watchFolder);
if (taskSettings.WatchFolderEnabled)
{
watchFolder.Enable();
}
}
}
public void RemoveWatchFolder(WatchFolderSettings watchFolderSetting)
{
using (WatchFolder watchFolder = FindWatchFolder(watchFolderSetting))
{
if (watchFolder != null)
{
watchFolder.TaskSettings.WatchFolderList.Remove(watchFolderSetting);
WatchFolders.Remove(watchFolder);
}
}
}
public void UpdateWatchFolderState(WatchFolderSettings watchFolderSetting)
{
WatchFolder watchFolder = FindWatchFolder(watchFolderSetting);
if (watchFolder != null)
{
if (watchFolder.TaskSettings.WatchFolderEnabled)
{
watchFolder.Enable();
}
else
{
watchFolder.Dispose();
}
}
}
public void UnregisterAllWatchFolders()
{
if (WatchFolders != null)
{
foreach (WatchFolder watchFolder in WatchFolders)
{
if (watchFolder != null)
{
watchFolder.Dispose();
}
}
}
}
public void Dispose()
{
UnregisterAllWatchFolders();
}
}
} | WatchFolderManager |
csharp | icsharpcode__SharpZipLib | src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterEngine.cs | {
"start": 1415,
"end": 24726
} | public class ____
{
#region Constants
private const int TooFar = 4096;
#endregion Constants
#region Constructors
/// <summary>
/// Construct instance with pending buffer
/// Adler calculation will be performed
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>
public DeflaterEngine(DeflaterPending pending)
: this (pending, false)
{
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>
/// <param name="noAdlerCalculation">
/// If no adler calculation should be performed
/// </param>
public DeflaterEngine(DeflaterPending pending, bool noAdlerCalculation)
{
this.pending = pending;
huffman = new DeflaterHuffman(pending);
if (!noAdlerCalculation)
adler = new Adler32();
window = new byte[2 * DeflaterConstants.WSIZE];
head = new short[DeflaterConstants.HASH_SIZE];
prev = new short[DeflaterConstants.WSIZE];
// We start at index 1, to avoid an implementation deficiency, that
// we cannot build a repeat pattern at index 0.
blockStart = strstart = 1;
}
#endregion Constructors
/// <summary>
/// Deflate drives actual compression of data
/// </summary>
/// <param name="flush">True to flush input buffers</param>
/// <param name="finish">Finish deflation with the current input.</param>
/// <returns>Returns true if progress has been made.</returns>
public bool Deflate(bool flush, bool finish)
{
bool progress;
do
{
FillWindow();
bool canFlush = flush && (inputOff == inputEnd);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("window: [" + blockStart + "," + strstart + ","
+ lookahead + "], " + compressionFunction + "," + canFlush);
}
#endif
switch (compressionFunction)
{
case DeflaterConstants.DEFLATE_STORED:
progress = DeflateStored(canFlush, finish);
break;
case DeflaterConstants.DEFLATE_FAST:
progress = DeflateFast(canFlush, finish);
break;
case DeflaterConstants.DEFLATE_SLOW:
progress = DeflateSlow(canFlush, finish);
break;
default:
throw new InvalidOperationException("unknown compressionFunction");
}
} while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made
return progress;
}
/// <summary>
/// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code>
/// returns true
/// </summary>
/// <param name="buffer">The buffer containing input data.</param>
/// <param name="offset">The offset of the first byte of data.</param>
/// <param name="count">The number of bytes of data to use as input.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (inputOff < inputEnd)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if ((offset > end) || (end > buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
inputBuf = buffer;
inputOff = offset;
inputEnd = end;
}
/// <summary>
/// Determines if more <see cref="SetInput">input</see> is needed.
/// </summary>
/// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns>
public bool NeedsInput()
{
return (inputEnd == inputOff);
}
/// <summary>
/// Set compression dictionary
/// </summary>
/// <param name="buffer">The buffer containing the dictionary data</param>
/// <param name="offset">The offset in the buffer for the first byte of data</param>
/// <param name="length">The length of the dictionary data.</param>
public void SetDictionary(byte[] buffer, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart != 1) )
{
throw new InvalidOperationException("strstart not 1");
}
#endif
adler?.Update(new ArraySegment<byte>(buffer, offset, length));
if (length < DeflaterConstants.MIN_MATCH)
{
return;
}
if (length > DeflaterConstants.MAX_DIST)
{
offset += length - DeflaterConstants.MAX_DIST;
length = DeflaterConstants.MAX_DIST;
}
System.Array.Copy(buffer, offset, window, strstart, length);
UpdateHash();
--length;
while (--length > 0)
{
InsertString();
strstart++;
}
strstart += 2;
blockStart = strstart;
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
huffman.Reset();
adler?.Reset();
blockStart = strstart = 1;
lookahead = 0;
totalIn = 0;
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
for (int i = 0; i < DeflaterConstants.HASH_SIZE; i++)
{
head[i] = 0;
}
for (int i = 0; i < DeflaterConstants.WSIZE; i++)
{
prev[i] = 0;
}
}
/// <summary>
/// Reset Adler checksum
/// </summary>
public void ResetAdler()
{
adler?.Reset();
}
/// <summary>
/// Get current value of Adler checksum
/// </summary>
public int Adler
{
get
{
return (adler != null) ? unchecked((int)adler.Value) : 0;
}
}
/// <summary>
/// Total data processed
/// </summary>
public long TotalIn
{
get
{
return totalIn;
}
}
/// <summary>
/// Get/set the <see cref="DeflateStrategy">deflate strategy</see>
/// </summary>
public DeflateStrategy Strategy
{
get
{
return strategy;
}
set
{
strategy = value;
}
}
/// <summary>
/// Set the deflate level (0-9)
/// </summary>
/// <param name="level">The value to set the level to.</param>
public void SetLevel(int level)
{
if ((level < 0) || (level > 9))
{
throw new ArgumentOutOfRangeException(nameof(level));
}
goodLength = DeflaterConstants.GOOD_LENGTH[level];
max_lazy = DeflaterConstants.MAX_LAZY[level];
niceLength = DeflaterConstants.NICE_LENGTH[level];
max_chain = DeflaterConstants.MAX_CHAIN[level];
if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("Change from " + compressionFunction + " to "
+ DeflaterConstants.COMPR_FUNC[level]);
}
#endif
switch (compressionFunction)
{
case DeflaterConstants.DEFLATE_STORED:
if (strstart > blockStart)
{
huffman.FlushStoredBlock(window, blockStart,
strstart - blockStart, false);
blockStart = strstart;
}
UpdateHash();
break;
case DeflaterConstants.DEFLATE_FAST:
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
break;
case DeflaterConstants.DEFLATE_SLOW:
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart, false);
blockStart = strstart;
}
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
break;
}
compressionFunction = DeflaterConstants.COMPR_FUNC[level];
}
}
/// <summary>
/// Fill the window
/// </summary>
public void FillWindow()
{
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (strstart >= DeflaterConstants.WSIZE + DeflaterConstants.MAX_DIST)
{
SlideWindow();
}
/* If there is not enough lookahead, but still some input left,
* read in the input
*/
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
{
int more = 2 * DeflaterConstants.WSIZE - lookahead - strstart;
if (more > inputEnd - inputOff)
{
more = inputEnd - inputOff;
}
System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
adler?.Update(new ArraySegment<byte>(inputBuf, inputOff, more));
inputOff += more;
totalIn += more;
lookahead += more;
}
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
UpdateHash();
}
}
private void UpdateHash()
{
/*
if (DEBUGGING) {
Console.WriteLine("updateHash: "+strstart);
}
*/
ins_h = (window[strstart] << DeflaterConstants.HASH_SHIFT) ^ window[strstart + 1];
}
/// <summary>
/// Inserts the current string in the head hash and returns the previous
/// value for this hash.
/// </summary>
/// <returns>The previous hash value</returns>
private int InsertString()
{
short match;
int hash = ((ins_h << DeflaterConstants.HASH_SHIFT) ^ window[strstart + (DeflaterConstants.MIN_MATCH - 1)]) & DeflaterConstants.HASH_MASK;
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^
(window[strstart + 1] << HASH_SHIFT) ^
(window[strstart + 2])) & HASH_MASK)) {
throw new SharpZipBaseException("hash inconsistent: " + hash + "/"
+window[strstart] + ","
+window[strstart + 1] + ","
+window[strstart + 2] + "," + HASH_SHIFT);
}
}
#endif
prev[strstart & DeflaterConstants.WMASK] = match = head[hash];
head[hash] = unchecked((short)strstart);
ins_h = hash;
return match & 0xffff;
}
private void SlideWindow()
{
Array.Copy(window, DeflaterConstants.WSIZE, window, 0, DeflaterConstants.WSIZE);
matchStart -= DeflaterConstants.WSIZE;
strstart -= DeflaterConstants.WSIZE;
blockStart -= DeflaterConstants.WSIZE;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage).
for (int i = 0; i < DeflaterConstants.HASH_SIZE; ++i)
{
int m = head[i] & 0xffff;
head[i] = (short)(m >= DeflaterConstants.WSIZE ? (m - DeflaterConstants.WSIZE) : 0);
}
// Slide the prev table.
for (int i = 0; i < DeflaterConstants.WSIZE; i++)
{
int m = prev[i] & 0xffff;
prev[i] = (short)(m >= DeflaterConstants.WSIZE ? (m - DeflaterConstants.WSIZE) : 0);
}
}
/// <summary>
/// Find the best (longest) string in the window matching the
/// string starting at strstart.
///
/// Preconditions:
/// <code>
/// strstart + DeflaterConstants.MAX_MATCH <= window.length.</code>
/// </summary>
/// <param name="curMatch"></param>
/// <returns>True if a match greater than the minimum length is found</returns>
private bool FindLongestMatch(int curMatch)
{
int match;
int scan = strstart;
// scanMax is the highest position that we can look at
int scanMax = scan + Math.Min(DeflaterConstants.MAX_MATCH, lookahead) - 1;
int limit = Math.Max(scan - DeflaterConstants.MAX_DIST, 0);
byte[] window = this.window;
short[] prev = this.prev;
int chainLength = this.max_chain;
int niceLength = Math.Min(this.niceLength, lookahead);
matchLen = Math.Max(matchLen, DeflaterConstants.MIN_MATCH - 1);
if (scan + matchLen > scanMax) return false;
byte scan_end1 = window[scan + matchLen - 1];
byte scan_end = window[scan + matchLen];
// Do not waste too much time if we already have a good match:
if (matchLen >= this.goodLength) chainLength >>= 2;
do
{
match = curMatch;
scan = strstart;
if (window[match + matchLen] != scan_end
|| window[match + matchLen - 1] != scan_end1
|| window[match] != window[scan]
|| window[++match] != window[++scan])
{
continue;
}
// scan is set to strstart+1 and the comparison passed, so
// scanMax - scan is the maximum number of bytes we can compare.
// below we compare 8 bytes at a time, so first we compare
// (scanMax - scan) % 8 bytes, so the remainder is a multiple of 8
switch ((scanMax - scan) % 8)
{
case 1:
if (window[++scan] == window[++match]) break;
break;
case 2:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 3:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 4:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 5:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 6:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 7:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
}
if (window[scan] == window[match])
{
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart + 258 unless lookahead is
* exhausted first.
*/
do
{
if (scan == scanMax)
{
++scan; // advance to first position not matched
++match;
break;
}
}
while (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]);
}
if (scan - strstart > matchLen)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (ins_h == 0) )
Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart));
#endif
matchStart = curMatch;
matchLen = scan - strstart;
if (matchLen >= niceLength)
break;
scan_end1 = window[scan - 1];
scan_end = window[scan];
}
} while ((curMatch = (prev[curMatch & DeflaterConstants.WMASK] & 0xffff)) > limit && 0 != --chainLength);
return matchLen >= DeflaterConstants.MIN_MATCH;
}
private bool DeflateStored(bool flush, bool finish)
{
if (!flush && (lookahead == 0))
{
return false;
}
strstart += lookahead;
lookahead = 0;
int storedLength = strstart - blockStart;
if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full
(blockStart < DeflaterConstants.WSIZE && storedLength >= DeflaterConstants.MAX_DIST) || // Block may move out of window
flush)
{
bool lastBlock = finish;
if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE)
{
storedLength = DeflaterConstants.MAX_BLOCK_SIZE;
lastBlock = false;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]");
}
#endif
huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock);
blockStart += storedLength;
return !(lastBlock || storedLength == 0);
}
return true;
}
private bool DeflateFast(bool flush, bool finish)
{
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= DeflaterConstants.MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
// We are flushing everything
huffman.FlushBlock(window, blockStart, strstart - blockStart, finish);
blockStart = strstart;
return false;
}
if (strstart > 2 * DeflaterConstants.WSIZE - DeflaterConstants.MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int hashHead;
if (lookahead >= DeflaterConstants.MIN_MATCH &&
(hashHead = InsertString()) != 0 &&
strategy != DeflateStrategy.HuffmanOnly &&
strstart - hashHead <= DeflaterConstants.MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart + i] != window[matchStart + i]) {
throw new SharpZipBaseException("Match failure");
}
}
}
#endif
bool full = huffman.TallyDist(strstart - matchStart, matchLen);
lookahead -= matchLen;
if (matchLen <= max_lazy && lookahead >= DeflaterConstants.MIN_MATCH)
{
while (--matchLen > 0)
{
++strstart;
InsertString();
}
++strstart;
}
else
{
strstart += matchLen;
if (lookahead >= DeflaterConstants.MIN_MATCH - 1)
{
UpdateHash();
}
}
matchLen = DeflaterConstants.MIN_MATCH - 1;
if (!full)
{
continue;
}
}
else
{
// No match found
huffman.TallyLit(window[strstart] & 0xff);
++strstart;
--lookahead;
}
if (huffman.IsFull())
{
bool lastBlock = finish && (lookahead == 0);
huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock);
blockStart = strstart;
return !lastBlock;
}
}
return true;
}
private bool DeflateSlow(bool flush, bool finish)
{
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= DeflaterConstants.MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = false;
// We are flushing everything
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && !flush)
{
throw new SharpZipBaseException("Not flushing, but no lookahead");
}
#endif
huffman.FlushBlock(window, blockStart, strstart - blockStart,
finish);
blockStart = strstart;
return false;
}
if (strstart >= 2 * DeflaterConstants.WSIZE - DeflaterConstants.MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int prevMatch = matchStart;
int prevLen = matchLen;
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
int hashHead = InsertString();
if (strategy != DeflateStrategy.HuffmanOnly &&
hashHead != 0 &&
strstart - hashHead <= DeflaterConstants.MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
// Discard match if too small and too far away
if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == DeflaterConstants.MIN_MATCH && strstart - matchStart > TooFar)))
{
matchLen = DeflaterConstants.MIN_MATCH - 1;
}
}
}
// previous match was better
if ((prevLen >= DeflaterConstants.MIN_MATCH) && (matchLen <= prevLen))
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart-1+i] != window[prevMatch + i])
throw new SharpZipBaseException();
}
}
#endif
huffman.TallyDist(strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
do
{
strstart++;
lookahead--;
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
InsertString();
}
} while (--prevLen > 0);
strstart++;
lookahead--;
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
}
else
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = true;
strstart++;
lookahead--;
}
if (huffman.IsFull())
{
int len = strstart - blockStart;
if (prevAvailable)
{
len--;
}
bool lastBlock = (finish && (lookahead == 0) && !prevAvailable);
huffman.FlushBlock(window, blockStart, len, lastBlock);
blockStart += len;
return !lastBlock;
}
}
return true;
}
#region Instance Fields
// Hash index of string to be inserted
private int ins_h;
/// <summary>
/// Hashtable, hashing three characters to an index for window, so
/// that window[index]..window[index+2] have this hash code.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
private short[] head;
/// <summary>
/// <code>prev[index & WMASK]</code> points to the previous index that has the
/// same hash code as the string starting at index. This way
/// entries with the same hash code are in a linked list.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
private short[] prev;
private int matchStart;
// Length of best match
private int matchLen;
// Set if previous match exists
private bool prevAvailable;
private int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
private int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
private int lookahead;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
private byte[] window;
private DeflateStrategy strategy;
private int max_chain, max_lazy, niceLength, goodLength;
/// <summary>
/// The current compression function.
/// </summary>
private int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
private byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
private long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
private int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
private int inputEnd;
private DeflaterPending pending;
private DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
private Adler32 adler;
#endregion Instance Fields
}
}
| DeflaterEngine |
csharp | files-community__Files | src/Files.App.CsWin32/IStorageProviderStatusUISourceFactory.cs | {
"start": 201,
"end": 531
} | partial struct ____ : IComIID
{
[GeneratedVTableFunction(Index = 6)]
public partial HRESULT GetStatusUISource(nint syncRootId, IStorageProviderStatusUISource** result);
[GuidRVAGen.Guid("12E46B74-4E5A-58D1-A62F-0376E8EE7DD8")]
public static partial ref readonly Guid Guid { get; }
}
}
| IStorageProviderStatusUISourceFactory |
csharp | abpframework__abp | framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/TemplateProjectBuildPipelineBuilder.cs | {
"start": 306,
"end": 2708
} | public static class ____
{
public static ProjectBuildPipeline Build(ProjectBuildContext context)
{
var pipeline = new ProjectBuildPipeline(context);
pipeline.Steps.Add(new FileEntryListReadStep());
if (SemanticVersion.Parse(context.TemplateFile.Version) > new SemanticVersion(4, 3, 99))
{
pipeline.Steps.Add(new CreateAppSettingsSecretsStep());
}
pipeline.Steps.AddRange(context.Template.GetCustomSteps(context));
pipeline.Steps.Add(new ProjectReferenceReplaceStep());
pipeline.Steps.Add(new TemplateCodeDeleteStep());
pipeline.Steps.Add(new SolutionRenameStep());
if (context.Template.IsPro())
{
pipeline.Steps.Add(new LicenseCodeReplaceStep()); // todo: move to custom steps?
}
if (context.Template.Name == AppTemplate.TemplateName ||
context.Template.Name == AppProTemplate.TemplateName)
{
pipeline.Steps.Add(new DatabaseManagementSystemChangeStep(context.Template.As<AppTemplateBase>().HasDbMigrations)); // todo: move to custom steps?
}
if (context.Template.Name == AppNoLayersTemplate.TemplateName ||
context.Template.Name == AppNoLayersProTemplate.TemplateName)
{
pipeline.Steps.Add(new AppNoLayersDatabaseManagementSystemChangeStep()); // todo: move to custom steps?
}
if (context.Template.Name == ModuleTemplate.TemplateName ||
context.Template.Name == ModuleProTemplate.TemplateName)
{
pipeline.Steps.Add(new AppModuleDatabaseManagementSystemChangeStep()); // todo: move to custom steps?
}
if ((context.BuildArgs.UiFramework == UiFramework.Mvc || context.BuildArgs.UiFramework == UiFramework.Blazor || context.BuildArgs.UiFramework == UiFramework.BlazorServer || context.BuildArgs.UiFramework == UiFramework.BlazorWebApp)
&& context.BuildArgs.MobileApp == MobileApp.None && context.Template.Name != MicroserviceProTemplate.TemplateName
&& context.Template.Name != MicroserviceServiceProTemplate.TemplateName)
{
pipeline.Steps.Add(new RemoveRootFolderStep());
}
pipeline.Steps.Add(new CheckRedisPreRequirements());
pipeline.Steps.Add(new CreateProjectResultZipStep());
return pipeline;
}
}
| TemplateProjectBuildPipelineBuilder |
csharp | bitwarden__server | util/PostgresMigrations/Migrations/20240723011507_DropOrganizationFlexibleCollections.Designer.cs | {
"start": 525,
"end": 104027
} | partial class ____
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:CollationDefinition:postgresIndetermanisticCollation", "en-u-ks-primary,en-u-ks-primary,icu,False")
.HasAnnotation("ProductVersion", "8.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("AllowAdminAccessToAllCollectionItems")
.HasColumnType("boolean")
.HasDefaultValue(true);
b.Property<string>("BillingEmail")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("BusinessAddress1")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessAddress2")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessAddress3")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessCountry")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<string>("BusinessName")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("BusinessTaxNumber")
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp with time zone");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<bool>("LimitCollectionCreationDeletion")
.HasColumnType("boolean")
.HasDefaultValue(true);
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("integer");
b.Property<int?>("MaxAutoscaleSmSeats")
.HasColumnType("integer");
b.Property<int?>("MaxAutoscaleSmServiceAccounts")
.HasColumnType("integer");
b.Property<short?>("MaxCollections")
.HasColumnType("smallint");
b.Property<short?>("MaxStorageGb")
.HasColumnType("smallint");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime?>("OwnersNotifiedOfAutoscaling")
.HasColumnType("timestamp with time zone");
b.Property<string>("Plan")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<byte>("PlanType")
.HasColumnType("smallint");
b.Property<string>("PrivateKey")
.HasColumnType("text");
b.Property<string>("PublicKey")
.HasColumnType("text");
b.Property<string>("ReferenceData")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<int?>("Seats")
.HasColumnType("integer");
b.Property<bool>("SelfHost")
.HasColumnType("boolean");
b.Property<int?>("SmSeats")
.HasColumnType("integer");
b.Property<int?>("SmServiceAccounts")
.HasColumnType("integer");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<long?>("Storage")
.HasColumnType("bigint");
b.Property<string>("TwoFactorProviders")
.HasColumnType("text");
b.Property<bool>("Use2fa")
.HasColumnType("boolean");
b.Property<bool>("UseApi")
.HasColumnType("boolean");
b.Property<bool>("UseCustomPermissions")
.HasColumnType("boolean");
b.Property<bool>("UseDirectory")
.HasColumnType("boolean");
b.Property<bool>("UseEvents")
.HasColumnType("boolean");
b.Property<bool>("UseGroups")
.HasColumnType("boolean");
b.Property<bool>("UseKeyConnector")
.HasColumnType("boolean");
b.Property<bool>("UsePasswordManager")
.HasColumnType("boolean");
b.Property<bool>("UsePolicies")
.HasColumnType("boolean");
b.Property<bool>("UseResetPassword")
.HasColumnType("boolean");
b.Property<bool>("UseScim")
.HasColumnType("boolean");
b.Property<bool>("UseSecretsManager")
.HasColumnType("boolean");
b.Property<bool>("UseSso")
.HasColumnType("boolean");
b.Property<bool>("UseTotp")
.HasColumnType("boolean");
b.Property<bool>("UsersGetPremium")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("Id", "Enabled");
NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("Id", "Enabled"), new[] { "UseTotp" });
b.ToTable("Organization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId", "Type")
.IsUnique()
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Policy", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("BillingEmail")
.HasColumnType("text");
b.Property<string>("BillingPhone")
.HasColumnType("text");
b.Property<string>("BusinessAddress1")
.HasColumnType("text");
b.Property<string>("BusinessAddress2")
.HasColumnType("text");
b.Property<string>("BusinessAddress3")
.HasColumnType("text");
b.Property<string>("BusinessCountry")
.HasColumnType("text");
b.Property<string>("BusinessName")
.HasColumnType("text");
b.Property<string>("BusinessTaxNumber")
.HasColumnType("text");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayCustomerId")
.HasColumnType("text");
b.Property<string>("GatewaySubscriptionId")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<bool>("UseEvents")
.HasColumnType("boolean");
b.HasKey("Id");
b.ToTable("Provider", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Settings")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ProviderId");
b.ToTable("ProviderOrganization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasColumnType("text");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("Permissions")
.HasColumnType("text");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.HasIndex("UserId");
b.ToTable("ProviderUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("AccessCode")
.HasMaxLength(25)
.HasColumnType("character varying(25)");
b.Property<bool?>("Approved")
.HasColumnType("boolean");
b.Property<DateTime?>("AuthenticationDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("MasterPasswordHash")
.HasColumnType("text");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("PublicKey")
.HasColumnType("text");
b.Property<string>("RequestDeviceIdentifier")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<byte>("RequestDeviceType")
.HasColumnType("smallint");
b.Property<string>("RequestIpAddress")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime?>("ResponseDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("ResponseDeviceId")
.HasColumnType("uuid");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ResponseDeviceId");
b.HasIndex("UserId");
b.ToTable("AuthRequest", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid?>("GranteeId")
.HasColumnType("uuid");
b.Property<Guid>("GrantorId")
.HasColumnType("uuid");
b.Property<string>("KeyEncrypted")
.HasColumnType("text");
b.Property<DateTime?>("LastNotificationDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("RecoveryInitiatedDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<int>("WaitTimeDays")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("GranteeId");
b.HasIndex("GrantorId");
b.ToTable("EmergencyAccess", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.Grant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("ConsumedDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Data")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Id")
.HasName("PK_Grant")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("ExpirationDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("Key")
.IsUnique();
b.ToTable("Grant", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("SsoConfig", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExternalId")
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId");
b.HasIndex("OrganizationId", "ExternalId")
.IsUnique()
.HasAnnotation("SqlServer:Clustered", false);
NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("OrganizationId", "ExternalId"), new[] { "UserId" });
b.HasIndex("OrganizationId", "UserId")
.IsUnique()
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("SsoUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("AaGuid")
.HasColumnType("uuid");
b.Property<int>("Counter")
.HasColumnType("integer");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("CredentialId")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("EncryptedPrivateKey")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("EncryptedPublicKey")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("EncryptedUserKey")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PublicKey")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("SupportsPrf")
.HasColumnType("boolean");
b.Property<string>("Type")
.HasMaxLength(20)
.HasColumnType("character varying(20)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("WebAuthnCredential", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int>("AssignedSeats")
.HasColumnType("integer");
b.Property<Guid?>("ClientId")
.HasColumnType("uuid");
b.Property<string>("ClientName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime>("Created")
.HasColumnType("timestamp with time zone");
b.Property<string>("InvoiceId")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("InvoiceNumber")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PlanName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<decimal>("Total")
.HasColumnType("numeric");
b.Property<int>("UsedSeats")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.ToTable("ProviderInvoiceItem", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int?>("AllocatedSeats")
.HasColumnType("integer");
b.Property<byte>("PlanType")
.HasColumnType("smallint");
b.Property<Guid>("ProviderId")
.HasColumnType("uuid");
b.Property<int?>("PurchasedSeats")
.HasColumnType("integer");
b.Property<int?>("SeatMinimum")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.HasIndex("Id", "PlanType")
.IsUnique();
b.ToTable("ProviderPlan", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cache", b =>
{
b.Property<string>("Id")
.HasMaxLength(449)
.HasColumnType("character varying(449)");
b.Property<DateTime?>("AbsoluteExpiration")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("ExpiresAtTime")
.HasColumnType("timestamp with time zone");
b.Property<long?>("SlidingExpirationInSeconds")
.HasColumnType("bigint");
b.Property<byte[]>("Value")
.HasColumnType("bytea");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("ExpiresAtTime")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Cache", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Collection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("CipherId")
.HasColumnType("uuid");
b.HasKey("CollectionId", "CipherId");
b.HasIndex("CipherId");
b.ToTable("CollectionCipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<bool>("HidePasswords")
.HasColumnType("boolean");
b.Property<bool>("Manage")
.HasColumnType("boolean");
b.Property<bool>("ReadOnly")
.HasColumnType("boolean");
b.HasKey("CollectionId", "GroupId");
b.HasIndex("GroupId");
b.ToTable("CollectionGroups");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("uuid");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("uuid");
b.Property<bool>("HidePasswords")
.HasColumnType("boolean");
b.Property<bool>("Manage")
.HasColumnType("boolean");
b.Property<bool>("ReadOnly")
.HasColumnType("boolean");
b.HasKey("CollectionId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.ToTable("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("EncryptedPrivateKey")
.HasColumnType("text");
b.Property<string>("EncryptedPublicKey")
.HasColumnType("text");
b.Property<string>("EncryptedUserKey")
.HasColumnType("text");
b.Property<string>("Identifier")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PushToken")
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("Identifier")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId", "Identifier")
.IsUnique()
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Device", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid?>("ActingUserId")
.HasColumnType("uuid");
b.Property<Guid?>("CipherId")
.HasColumnType("uuid");
b.Property<Guid?>("CollectionId")
.HasColumnType("uuid");
b.Property<DateTime>("Date")
.HasColumnType("timestamp with time zone");
b.Property<byte?>("DeviceType")
.HasColumnType("smallint");
b.Property<string>("DomainName")
.HasColumnType("text");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<Guid?>("InstallationId")
.HasColumnType("uuid");
b.Property<string>("IpAddress")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("OrganizationUserId")
.HasColumnType("uuid");
b.Property<Guid?>("PolicyId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderOrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("ProviderUserId")
.HasColumnType("uuid");
b.Property<Guid?>("SecretId")
.HasColumnType("uuid");
b.Property<Guid?>("ServiceAccountId")
.HasColumnType("uuid");
b.Property<byte?>("SystemUser")
.HasColumnType("smallint");
b.Property<int>("Type")
.HasColumnType("integer");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("Date", "OrganizationId", "ActingUserId", "CipherId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Event", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("AccessAll")
.HasColumnType("boolean");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Group", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("uuid");
b.HasKey("GroupId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.ToTable("GroupUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("character varying(150)");
b.HasKey("Id");
b.ToTable("Installation", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("ApiKey")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationApiKey", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Config")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationConnection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("DomainName")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<int>("JobRunCount")
.HasColumnType("integer");
b.Property<DateTime?>("LastCheckedDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("NextRunDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("Txt")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime?>("VerifiedDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationDomain", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("FriendlyName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTime?>("LastSyncDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("OfferedToEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<byte?>("PlanSponsorshipType")
.HasColumnType("smallint");
b.Property<Guid?>("SponsoredOrganizationId")
.HasColumnType("uuid");
b.Property<Guid?>("SponsoringOrganizationId")
.HasColumnType("uuid");
b.Property<Guid>("SponsoringOrganizationUserId")
.HasColumnType("uuid");
b.Property<bool>("ToDelete")
.HasColumnType("boolean");
b.Property<DateTime?>("ValidUntil")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SponsoredOrganizationId");
b.HasIndex("SponsoringOrganizationId");
b.HasIndex("SponsoringOrganizationUserId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("OrganizationSponsorship", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<bool>("AccessAll")
.HasColumnType("boolean");
b.Property<bool>("AccessSecretsManager")
.HasColumnType("boolean");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("Permissions")
.HasColumnType("text");
b.Property<string>("ResetPasswordKey")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<short>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId", "OrganizationId", "Status")
.HasAnnotation("SqlServer:Clustered", false);
NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("UserId", "OrganizationId", "Status"), new[] { "AccessAll" });
b.ToTable("OrganizationUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int>("AccessCount")
.HasColumnType("integer");
b.Property<Guid?>("CipherId")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<DateTime>("DeletionDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("timestamp with time zone");
b.Property<bool?>("HideEmail")
.HasColumnType("boolean");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<int?>("MaxAccessCount")
.HasColumnType("integer");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<string>("Password")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("DeletionDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId");
b.HasIndex("UserId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId", "OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Send", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b =>
{
b.Property<string>("Id")
.HasMaxLength(40)
.HasColumnType("character varying(40)");
b.Property<bool>("Active")
.HasColumnType("boolean");
b.Property<string>("Country")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("PostalCode")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<decimal>("Rate")
.HasColumnType("numeric");
b.Property<string>("State")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.HasKey("Id");
b.ToTable("TaxRate", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Details")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<byte?>("PaymentMethodType")
.HasColumnType("smallint");
b.Property<Guid?>("ProviderId")
.HasColumnType("uuid");
b.Property<bool?>("Refunded")
.HasColumnType("boolean");
b.Property<decimal?>("RefundedAmount")
.HasColumnType("numeric");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ProviderId");
b.HasIndex("UserId")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("UserId", "OrganizationId", "CreationDate")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Transaction", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("AccountRevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ApiKey")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("character varying(30)");
b.Property<string>("AvatarColor")
.HasMaxLength(7)
.HasColumnType("character varying(7)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Culture")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.UseCollation("postgresIndetermanisticCollation");
b.Property<bool>("EmailVerified")
.HasColumnType("boolean");
b.Property<string>("EquivalentDomains")
.HasColumnType("text");
b.Property<string>("ExcludedGlobalEquivalentDomains")
.HasColumnType("text");
b.Property<int>("FailedLoginCount")
.HasColumnType("integer");
b.Property<bool>("ForcePasswordReset")
.HasColumnType("boolean");
b.Property<byte?>("Gateway")
.HasColumnType("smallint");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<byte>("Kdf")
.HasColumnType("smallint");
b.Property<int>("KdfIterations")
.HasColumnType("integer");
b.Property<int?>("KdfMemory")
.HasColumnType("integer");
b.Property<int?>("KdfParallelism")
.HasColumnType("integer");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<DateTime?>("LastEmailChangeDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("LastFailedLoginDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("LastKdfChangeDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("LastKeyRotationDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("LastPasswordChangeDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("MasterPassword")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<string>("MasterPasswordHint")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<short?>("MaxStorageGb")
.HasColumnType("smallint");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<bool>("Premium")
.HasColumnType("boolean");
b.Property<DateTime?>("PremiumExpirationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("PrivateKey")
.HasColumnType("text");
b.Property<string>("PublicKey")
.HasColumnType("text");
b.Property<string>("ReferenceData")
.HasColumnType("text");
b.Property<DateTime?>("RenewalReminderDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<long?>("Storage")
.HasColumnType("bigint");
b.Property<string>("TwoFactorProviders")
.HasColumnType("text");
b.Property<string>("TwoFactorRecoveryCode")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<bool>("UsesKeyConnector")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique()
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("Premium", "PremiumExpirationDate", "RenewalReminderDate")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("User", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Discriminator")
.IsRequired()
.HasMaxLength(34)
.HasColumnType("character varying(34)");
b.Property<bool>("Read")
.HasColumnType("boolean");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Write")
.HasColumnType("boolean");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.ToTable("AccessPolicy", (string)null);
b.HasDiscriminator().HasValue("AccessPolicy");
b.UseTphMappingStrategy();
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("ClientSecretHash")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("EncryptedPayload")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("character varying(4000)");
b.Property<DateTime?>("ExpireAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Scope")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("character varying(4000)");
b.Property<Guid?>("ServiceAccountId")
.HasColumnType("uuid");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("ServiceAccountId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("ApiKey", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("DeletedDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Project", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("Note")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("DeletedDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Secret", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid>("OrganizationId")
.HasColumnType("uuid");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("ServiceAccount", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Attachments")
.HasColumnType("text");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Data")
.HasColumnType("text");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Favorites")
.HasColumnType("text");
b.Property<string>("Folders")
.HasColumnType("text");
b.Property<string>("Key")
.HasColumnType("text");
b.Property<Guid?>("OrganizationId")
.HasColumnType("uuid");
b.Property<byte?>("Reprompt")
.HasColumnType("smallint");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<byte>("Type")
.HasColumnType("smallint");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Cipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Folder", (string)null);
});
modelBuilder.Entity("ProjectSecret", b =>
{
b.Property<Guid>("ProjectsId")
.HasColumnType("uuid");
b.Property<Guid>("SecretsId")
.HasColumnType("uuid");
b.HasKey("ProjectsId", "SecretsId");
b.HasIndex("SecretsId");
b.ToTable("ProjectSecret");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("GroupId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GroupId");
b.HasIndex("GrantedProjectId");
b.HasIndex("GroupId");
b.HasDiscriminator().HasValue("group_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedSecretId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedSecretId");
b.Property<Guid?>("GroupId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GroupId");
b.HasIndex("GrantedSecretId");
b.HasIndex("GroupId");
b.HasDiscriminator().HasValue("group_secret");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedServiceAccountId");
b.Property<Guid?>("GroupId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GroupId");
b.HasIndex("GrantedServiceAccountId");
b.HasIndex("GroupId");
b.HasDiscriminator().HasValue("group_service_account");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("ServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("ServiceAccountId");
b.HasIndex("GrantedProjectId");
b.HasIndex("ServiceAccountId");
b.HasDiscriminator().HasValue("service_account_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedSecretId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedSecretId");
b.Property<Guid?>("ServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("ServiceAccountId");
b.HasIndex("GrantedSecretId");
b.HasIndex("ServiceAccountId");
b.HasDiscriminator().HasValue("service_account_secret");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("OrganizationUserId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("OrganizationUserId");
b.HasIndex("GrantedProjectId");
b.HasIndex("OrganizationUserId");
b.HasDiscriminator().HasValue("user_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedSecretId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedSecretId");
b.Property<Guid?>("OrganizationUserId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("OrganizationUserId");
b.HasIndex("GrantedSecretId");
b.HasIndex("OrganizationUserId");
b.HasDiscriminator().HasValue("user_secret");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("GrantedServiceAccountId");
b.Property<Guid?>("OrganizationUserId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("uuid")
.HasColumnName("OrganizationUserId");
b.HasIndex("GrantedServiceAccountId");
b.HasIndex("OrganizationUserId");
b.HasDiscriminator().HasValue("user_service_account");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Policies")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Provider");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice")
.WithMany()
.HasForeignKey("ResponseDeviceId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("ResponseDevice");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee")
.WithMany()
.HasForeignKey("GranteeId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor")
.WithMany()
.HasForeignKey("GrantorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Grantee");
b.Navigation("Grantor");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("SsoConfigs")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("SsoUsers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("SsoUsers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Collections")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", "Cipher")
.WithMany("CollectionCiphers")
.HasForeignKey("CipherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionCiphers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cipher");
b.Navigation("Collection");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionGroups")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionUsers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("CollectionUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Groups")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany("GroupUsers")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("GroupUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("ApiKeys")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Connections")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Domains")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoredOrganization")
.WithMany()
.HasForeignKey("SponsoredOrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoringOrganization")
.WithMany()
.HasForeignKey("SponsoringOrganizationId");
b.Navigation("SponsoredOrganization");
b.Navigation("SponsoringOrganization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("OrganizationUsers")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("OrganizationUsers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Transactions")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Transactions")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("Provider");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount")
.WithMany()
.HasForeignKey("ServiceAccountId");
b.Navigation("ServiceAccount");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization")
.WithMany("Ciphers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Ciphers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Folders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ProjectSecret", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", null)
.WithMany()
.HasForeignKey("ProjectsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", null)
.WithMany()
.HasForeignKey("SecretsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("GroupAccessPolicies")
.HasForeignKey("GrantedProjectId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("GrantedProject");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret")
.WithMany("GroupAccessPolicies")
.HasForeignKey("GrantedSecretId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("GrantedSecret");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount")
.WithMany("GroupAccessPolicies")
.HasForeignKey("GrantedServiceAccountId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("GrantedServiceAccount");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("ServiceAccountAccessPolicies")
.HasForeignKey("GrantedProjectId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount")
.WithMany()
.HasForeignKey("ServiceAccountId");
b.Navigation("GrantedProject");
b.Navigation("ServiceAccount");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret")
.WithMany("ServiceAccountAccessPolicies")
.HasForeignKey("GrantedSecretId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount")
.WithMany()
.HasForeignKey("ServiceAccountId");
b.Navigation("GrantedSecret");
b.Navigation("ServiceAccount");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("UserAccessPolicies")
.HasForeignKey("GrantedProjectId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId");
b.Navigation("GrantedProject");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret")
.WithMany("UserAccessPolicies")
.HasForeignKey("GrantedSecretId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId");
b.Navigation("GrantedSecret");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount")
.WithMany("UserAccessPolicies")
.HasForeignKey("GrantedServiceAccountId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId");
b.Navigation("GrantedServiceAccount");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Ciphers");
b.Navigation("Collections");
b.Navigation("Connections");
b.Navigation("Domains");
b.Navigation("Groups");
b.Navigation("OrganizationUsers");
b.Navigation("Policies");
b.Navigation("SsoConfigs");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Navigation("CollectionCiphers");
b.Navigation("CollectionGroups");
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Navigation("CollectionUsers");
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Navigation("Ciphers");
b.Navigation("Folders");
b.Navigation("OrganizationUsers");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.Navigation("GroupAccessPolicies");
b.Navigation("ServiceAccountAccessPolicies");
b.Navigation("UserAccessPolicies");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b =>
{
b.Navigation("GroupAccessPolicies");
b.Navigation("ServiceAccountAccessPolicies");
b.Navigation("UserAccessPolicies");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.Navigation("GroupAccessPolicies");
b.Navigation("UserAccessPolicies");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.Navigation("CollectionCiphers");
});
#pragma warning restore 612, 618
}
}
}
| DropOrganizationFlexibleCollections |
csharp | SixLabors__ImageSharp | src/ImageSharp/PixelFormats/PixelBlenders/DefaultPixelBlenders.Generated.cs | {
"start": 49835,
"end": 55295
} | public class ____ : PixelBlender<TPixel>
{
/// <summary>
/// Gets the static instance of this blender.
/// </summary>
public static NormalSrcAtop Instance { get; } = new NormalSrcAtop();
/// <inheritdoc />
public override TPixel Blend(TPixel background, TPixel source, float amount)
{
return TPixel.FromScaledVector4(PorterDuffFunctions.NormalSrcAtop(background.ToScaledVector4(), source.ToScaledVector4(), Numerics.Clamp(amount, 0, 1)));
}
/// <inheritdoc />
protected override void BlendFunction(Span<Vector4> destination, ReadOnlySpan<Vector4> background, ReadOnlySpan<Vector4> source, float amount)
{
amount = Numerics.Clamp(amount, 0, 1);
if (Avx2.IsSupported && destination.Length >= 2)
{
// Divide by 2 as 4 elements per Vector4 and 8 per Vector256<float>
ref Vector256<float> destinationBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(destination));
ref Vector256<float> destinationLast = ref Unsafe.Add(ref destinationBase, (uint)destination.Length / 2u);
ref Vector256<float> backgroundBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(background));
ref Vector256<float> sourceBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(source));
Vector256<float> opacity = Vector256.Create(amount);
while (Unsafe.IsAddressLessThan(ref destinationBase, ref destinationLast))
{
destinationBase = PorterDuffFunctions.NormalSrcAtop(backgroundBase, sourceBase, opacity);
destinationBase = ref Unsafe.Add(ref destinationBase, 1);
backgroundBase = ref Unsafe.Add(ref backgroundBase, 1);
sourceBase = ref Unsafe.Add(ref sourceBase, 1);
}
if (Numerics.Modulo2(destination.Length) != 0)
{
// Vector4 fits neatly in pairs. Any overlap has to be equal to 1.
int i = destination.Length - 1;
destination[i] = PorterDuffFunctions.NormalSrcAtop(background[i], source[i], amount);
}
}
else
{
for (int i = 0; i < destination.Length; i++)
{
destination[i] = PorterDuffFunctions.NormalSrcAtop(background[i], source[i], amount);
}
}
}
/// <inheritdoc />
protected override void BlendFunction(Span<Vector4> destination, ReadOnlySpan<Vector4> background, ReadOnlySpan<Vector4> source, ReadOnlySpan<float> amount)
{
if (Avx2.IsSupported && destination.Length >= 2)
{
// Divide by 2 as 4 elements per Vector4 and 8 per Vector256<float>
ref Vector256<float> destinationBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(destination));
ref Vector256<float> destinationLast = ref Unsafe.Add(ref destinationBase, (uint)destination.Length / 2u);
ref Vector256<float> backgroundBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(background));
ref Vector256<float> sourceBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(source));
ref float amountBase = ref MemoryMarshal.GetReference(amount);
Vector256<float> vOne = Vector256.Create(1F);
while (Unsafe.IsAddressLessThan(ref destinationBase, ref destinationLast))
{
// We need to create a Vector256<float> containing the current and next amount values
// taking up each half of the Vector256<float> and then clamp them.
Vector256<float> opacity = Vector256.Create(
Vector128.Create(amountBase),
Vector128.Create(Unsafe.Add(ref amountBase, 1)));
opacity = Avx.Min(Avx.Max(Vector256<float>.Zero, opacity), vOne);
destinationBase = PorterDuffFunctions.NormalSrcAtop(backgroundBase, sourceBase, opacity);
destinationBase = ref Unsafe.Add(ref destinationBase, 1);
backgroundBase = ref Unsafe.Add(ref backgroundBase, 1);
sourceBase = ref Unsafe.Add(ref sourceBase, 1);
amountBase = ref Unsafe.Add(ref amountBase, 2);
}
if (Numerics.Modulo2(destination.Length) != 0)
{
// Vector4 fits neatly in pairs. Any overlap has to be equal to 1.
int i = destination.Length - 1;
destination[i] = PorterDuffFunctions.NormalSrcAtop(background[i], source[i], Numerics.Clamp(amount[i], 0, 1F));
}
}
else
{
for (int i = 0; i < destination.Length; i++)
{
destination[i] = PorterDuffFunctions.NormalSrcAtop(background[i], source[i], Numerics.Clamp(amount[i], 0, 1F));
}
}
}
}
/// <summary>
/// A pixel blender that implements the "MultiplySrcAtop" composition equation.
/// </summary>
| NormalSrcAtop |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Models/Orders/OrderModel.cs | {
"start": 12846,
"end": 13964
} | public class ____ : BaseModel
{
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchProductName")]
public string SearchProductName { get; set; }
[UIHint("Category")]
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchCategory")]
public string SearchCategoryId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.Brand")]
[UIHint("Brand")]
public string SearchBrandId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchCollection")]
[UIHint("Collection")]
public string SearchCollectionId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchProductType")]
public int SearchProductTypeId { get; set; }
public IList<SelectListItem> AvailableCollections { get; set; }
public IList<SelectListItem> AvailableProductTypes { get; set; } = new List<SelectListItem>();
public string OrderId { get; set; }
public int OrderNumber { get; set; }
#region Nested classes
| AddOrderProductModel |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/RabbitMqAddress_Specs.cs | {
"start": 11403,
"end": 12172
} | public class ____
{
[Test]
public void TheHost()
{
Assert.That(_hostSettings.VirtualHost, Is.EqualTo("/"));
}
[Test]
public void TheQueue()
{
Assert.That(_receiveSettings.QueueName, Is.EqualTo("the_queue"));
}
readonly Uri _uri = new Uri("rabbitmq://some_server/the_queue");
readonly Uri _hostUri = new Uri("rabbitmq://some_server/");
RabbitMqHostSettings _hostSettings;
ReceiveSettings _receiveSettings;
[OneTimeSetUp]
public void WhenParsed()
{
_hostSettings = _hostUri.GetHostSettings();
_receiveSettings = _uri.GetReceiveSettings();
}
}
[TestFixture]
| GivenANonVHostAddress |
csharp | dotnet__maui | src/Controls/src/Core/Cells/SwitchCell.cs | {
"start": 328,
"end": 1946
} | public class ____ : Cell
{
/// <summary>Bindable property for <see cref="On"/>.</summary>
public static readonly BindableProperty OnProperty = BindableProperty.Create(nameof(On), typeof(bool), typeof(SwitchCell), false, propertyChanged: (obj, oldValue, newValue) =>
{
var switchCell = (SwitchCell)obj;
switchCell.OnChanged?.Invoke(obj, new ToggledEventArgs((bool)newValue));
}, defaultBindingMode: BindingMode.TwoWay);
/// <summary>Bindable property for <see cref="Text"/>.</summary>
public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(SwitchCell), default(string));
/// <summary>Bindable property for <see cref="OnColor"/>.</summary>
public static readonly BindableProperty OnColorProperty = BindableProperty.Create(nameof(OnColor), typeof(Color), typeof(SwitchCell), null);
/// <include file="../../../docs/Microsoft.Maui.Controls/SwitchCell.xml" path="//Member[@MemberName='OnColor']/Docs/*" />
public Color OnColor
{
get { return (Color)GetValue(OnColorProperty); }
set { SetValue(OnColorProperty, value); }
}
/// <summary>Gets or sets the state of the switch. This is a bindable property.</summary>
public bool On
{
get { return (bool)GetValue(OnProperty); }
set { SetValue(OnProperty, value); }
}
/// <summary>Gets or sets the text displayed next to the switch. This is a bindable property.</summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public event EventHandler<ToggledEventArgs> OnChanged;
}
} | SwitchCell |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Language/test/Language.SyntaxTree.Tests/Utilities/SchemaSyntaxPrinterTests.cs | {
"start": 8977,
"end": 9378
} | interface ____ implements X & Y & Z "
+ "{ bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_InterfaceTypeExtensionDef_InOutShouldBeTheSame()
{
// arrange
const string schema = "extend | Foo |
csharp | dotnet__aspire | src/Aspire.AppHost.Sdk/Aspire.RuntimeIdentifier.Tool/NuGetUtils.cs | {
"start": 573,
"end": 2143
} | internal static class ____
{
public static string? GetBestMatchingRid(RuntimeGraph runtimeGraph, string runtimeIdentifier,
IEnumerable<string> availableRuntimeIdentifiers, out bool wasInGraph)
{
return GetBestMatchingRidWithExclusion(runtimeGraph, runtimeIdentifier,
runtimeIdentifiersToExclude: null,
availableRuntimeIdentifiers, out wasInGraph);
}
public static string? GetBestMatchingRidWithExclusion(RuntimeGraph runtimeGraph, string runtimeIdentifier,
IEnumerable<string>? runtimeIdentifiersToExclude,
IEnumerable<string> availableRuntimeIdentifiers, out bool wasInGraph)
{
wasInGraph = runtimeGraph.Runtimes.ContainsKey(runtimeIdentifier);
string? bestMatch = null;
HashSet<string> availableRids = new(availableRuntimeIdentifiers, StringComparer.Ordinal);
HashSet<string>? excludedRids = runtimeIdentifiersToExclude switch { null => null, _ => new HashSet<string>(runtimeIdentifiersToExclude, StringComparer.Ordinal) };
foreach (var candidateRuntimeIdentifier in runtimeGraph.ExpandRuntime(runtimeIdentifier))
{
if (bestMatch == null && availableRids.Contains(candidateRuntimeIdentifier))
{
bestMatch = candidateRuntimeIdentifier;
}
if (excludedRids != null && excludedRids.Contains(candidateRuntimeIdentifier))
{
// Don't treat this as a match
return null;
}
}
return bestMatch;
}
}
| NuGetUtils |
csharp | dotnet__efcore | src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs | {
"start": 58216,
"end": 64163
} | private sealed class ____(IDiagnosticsLogger<DbLoggerCategory.Query> logger)
: ExpressionVisitor
{
protected override Expression VisitBinary(BinaryExpression binaryExpression)
=> binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual
&& TryRemoveNavigationComparison(
binaryExpression.NodeType, binaryExpression.Left, binaryExpression.Right, out var result)
? result
: base.VisitBinary(binaryExpression);
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var method = methodCallExpression.Method;
if (method.Name == nameof(object.Equals)
&& methodCallExpression is { Object: not null, Arguments.Count: 1 }
&& TryRemoveNavigationComparison(
ExpressionType.Equal, methodCallExpression.Object, methodCallExpression.Arguments[0], out var result))
{
return result;
}
if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object == null
&& methodCallExpression.Arguments.Count == 2
&& TryRemoveNavigationComparison(
ExpressionType.Equal, methodCallExpression.Arguments[0], methodCallExpression.Arguments[1], out result))
{
return result;
}
return base.VisitMethodCall(methodCallExpression);
}
private bool TryRemoveNavigationComparison(
ExpressionType nodeType,
Expression left,
Expression right,
[NotNullWhen(true)] out Expression? result)
{
result = null;
var leftNavigationData = ProcessNavigationPath(left) as NavigationDataExpression;
var rightNavigationData = ProcessNavigationPath(right) as NavigationDataExpression;
if (leftNavigationData == null
&& rightNavigationData == null)
{
return false;
}
if (left.IsNullConstantExpression()
|| right.IsNullConstantExpression())
{
var nonNullNavigationData = left.IsNullConstantExpression()
? rightNavigationData!
: leftNavigationData!;
if (nonNullNavigationData.Navigation?.IsCollection == true)
{
logger.PossibleUnintendedCollectionNavigationNullComparisonWarning(nonNullNavigationData.Navigation);
// Inner would be non-null when navigation is non-null
result = Expression.MakeBinary(
nodeType, nonNullNavigationData.Inner!.Current, Expression.Constant(null, nonNullNavigationData.Inner.Type));
return true;
}
}
else if (leftNavigationData != null
&& rightNavigationData != null)
{
if (leftNavigationData.Navigation?.IsCollection == true)
{
if (leftNavigationData.Navigation == rightNavigationData.Navigation)
{
logger.PossibleUnintendedReferenceComparisonWarning(leftNavigationData.Current, rightNavigationData.Current);
// Inner would be non-null when navigation is non-null
result = Expression.MakeBinary(nodeType, leftNavigationData.Inner!.Current, rightNavigationData.Inner!.Current);
}
else
{
result = Expression.Constant(nodeType == ExpressionType.NotEqual);
}
return true;
}
}
return false;
}
private static Expression ProcessNavigationPath(Expression expression)
{
switch (expression)
{
case MemberExpression { Expression: not null } memberExpression:
var innerExpression = ProcessNavigationPath(memberExpression.Expression);
if (innerExpression is NavigationDataExpression { EntityType: not null } navigationDataExpression)
{
var navigation = navigationDataExpression.EntityType.FindNavigation(memberExpression.Member);
if (navigation != null)
{
return new NavigationDataExpression(expression, navigationDataExpression, navigation);
}
}
return expression;
case MethodCallExpression methodCallExpression
when methodCallExpression.TryGetEFPropertyArguments(out _, out _):
return expression;
default:
var convertlessExpression = expression.UnwrapTypeConversion(out var convertedType);
if (UnwrapEntityReference(convertlessExpression) is { } entityReference)
{
var entityType = entityReference.EntityType;
if (convertedType != null)
{
entityType = entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive())
.FirstOrDefault(et => et.ClrType == convertedType);
if (entityType == null)
{
return expression;
}
}
return new NavigationDataExpression(expression, entityType);
}
return expression;
}
}
| RemoveRedundantNavigationComparisonExpressionVisitor |
csharp | FoundatioFx__Foundatio | src/Foundatio/Utility/IHaveLogger.cs | {
"start": 262,
"end": 702
} | public static class ____
{
public static ILogger GetLogger(this object target)
{
return target is IHaveLogger accessor ? accessor.Logger ?? NullLogger.Instance : NullLogger.Instance;
}
public static ILoggerFactory GetLoggerFactory(this object target)
{
return target is IHaveLoggerFactory accessor ? accessor.LoggerFactory ?? NullLoggerFactory.Instance : NullLoggerFactory.Instance;
}
}
| LoggerExtensions |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Text/TextTransformationExtensionsTests.cs | {
"start": 1522,
"end": 2309
} | public sealed class ____
{
[Fact]
public void Should_Register_The_Provided_Tokens_With_The_Template()
{
// Given
var context = Substitute.For<ICakeContext>();
var transformation = TextTransformationAliases.TransformText(
context, "<%greeting%> World and <%name%>!");
// When
var tokens = new Dictionary<string, object>
{
{ "greeting", "Hello" },
{ "name", "Tim" }
};
transformation.WithTokens(tokens);
// Then
Assert.Equal("Hello World and Tim!", transformation.ToString());
}
}
}
} | TheWithTokensMethod |
csharp | abpframework__abp | framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestBase.cs | {
"start": 183,
"end": 435
} | public abstract class ____ : AbpIntegratedTest<AbpJsonSystemTextJsonTestModule>
{
protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options)
{
options.UseAutofac();
}
}
| AbpJsonSystemTextJsonTestBase |
csharp | getsentry__sentry-dotnet | test/Sentry.AspNetCore.Grpc.Tests/FakeSentryGrpcServer.cs | {
"start": 451,
"end": 1191
} | class
____ TResponse : class
{
var builder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddGrpc(options =>
{
options.Interceptors.Add<SentryGrpcTestInterceptor>();
});
foreach (var handler in handlers)
{
services.AddSingleton(handler);
}
})
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<TService>();
});
});
return new TestServer(builder);
}
}
| where |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.