language stringclasses 1 value | repo stringclasses 133 values | path stringlengths 13 229 | class_span dict | source stringlengths 14 2.92M | target stringlengths 1 153 |
|---|---|---|---|---|---|
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs | {
"start": 415,
"end": 974
} | public class ____
{
private static readonly DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1000_HtmlHelperPartialShouldBeAvoided;
[Fact]
public Task NoDiagnosticsAreReturned_ForNonUseOfHtmlPartial()
{
var source = @"
namespace AspNetCore
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
| AvoidHtmlPartialAnalyzerTest |
csharp | unoplatform__uno | src/Uno.UI.Runtime.Skia.Wpf/UI/Xaml/Window/UnoWpfWindowHost.cs | {
"start": 627,
"end": 5392
} | internal class ____ : WpfControl, IWpfWindowHost
{
private const string NativeOverlayLayerHost = "NativeOverlayLayerHost";
private const string RenderLayerHost = "RenderLayerHost";
private readonly Style _style = (Style)XamlReader.Parse(
"""
<Style
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Uno.UI.Runtime.Skia.Wpf.UI.Controls;assembly=Uno.UI.Runtime.Skia.Wpf"
TargetType="{x:Type controls:UnoWpfWindowHost}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:UnoWpfWindowHost}">
<Grid>
<Border
Background="{x:Null}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter x:Name="RenderLayerHost" />
</Border>
<Border
Background="{x:Null}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter x:Name="NativeOverlayLayerHost" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
""");
private readonly UnoWpfWindow _wpfWindow;
private readonly MUX.Window _winUIWindow;
private readonly WpfCanvas _nativeOverlayLayer;
private readonly RenderingLayerHost _renderLayer;
private readonly SerialDisposable _backgroundDisposable = new();
private bool _invalidateRenderEnqueued;
public UnoWpfWindowHost(UnoWpfWindow wpfWindow, MUX.Window winUIWindow)
{
_wpfWindow = wpfWindow;
_winUIWindow = winUIWindow;
Style = _style;
// We need to set the content here because the RenderingLayerHost needs to call Window.GetWindow
wpfWindow.Content = this;
FocusVisualStyle = null;
_nativeOverlayLayer = new WpfCanvas();
// Transparency doesn't work with the OpenGL renderer, so we have to use the software renderer for the top layer
_renderLayer = new RenderingLayerHost(WpfRendererProvider.CreateForHost(this));
Loaded += WpfHost_Loaded;
Unloaded += (_, _) => _backgroundDisposable.Dispose();
UpdateRendererBackground();
_backgroundDisposable.Disposable = _winUIWindow.RegisterBackgroundChangedEvent((_, _) => UpdateRendererBackground());
}
public WpfWindow Window => _wpfWindow;
public WpfControl RenderLayer => _renderLayer;
public WpfControl BottomLayer => _renderLayer;
internal void InitializeRenderer()
{
_renderLayer.Renderer = WpfRendererProvider.CreateForHost(this);
UpdateRendererBackground();
}
private void WpfHost_Loaded(object _, System.Windows.RoutedEventArgs __)
{
// Avoid dotted border on focus.
if (Parent is WpfControl control)
{
control.FocusVisualStyle = null;
_renderLayer.FocusVisualStyle = null;
}
}
void UpdateRendererBackground()
{
if (_renderLayer.Renderer is null)
{
return;
}
// the flyout layer always has a transparent background so that elements underneath can be seen.
_renderLayer.Renderer.BackgroundColor = SKColors.Transparent;
if (_winUIWindow.Background is MUX.Media.SolidColorBrush brush)
{
_wpfWindow.Background = new System.Windows.Media.SolidColorBrush(brush.Color.ToWpfColor());
}
else if (_winUIWindow.Background is not null)
{
if (this.Log().IsEnabled(LogLevel.Warning))
{
this.Log().Warn($"This platform only supports SolidColorBrush for the Window background");
}
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (GetTemplateChild(NativeOverlayLayerHost) is WpfContentPresenter nativeOverlayLayerHost)
{
nativeOverlayLayerHost.Content = _nativeOverlayLayer;
}
if (GetTemplateChild(RenderLayerHost) is WpfContentPresenter renderLayerHost)
{
renderLayerHost.Content = _renderLayer;
}
}
MUX.UIElement? IXamlRootHost.RootElement => _winUIWindow.RootElement;
void IXamlRootHost.InvalidateRender()
{
if (!Interlocked.Exchange(ref _invalidateRenderEnqueued, true))
{
// We schedule on Idle here because if you invalidate directly, it can cause a hang if
// the rendering is continuously invalidated (e.g. animations). Try Given_SKCanvasElement to confirm.
NativeDispatcher.Main.Enqueue(() =>
{
Interlocked.Exchange(ref _invalidateRenderEnqueued, false);
_winUIWindow.RootElement?.XamlRoot?.InvalidateOverlays();
_renderLayer.InvalidateVisual();
InvalidateVisual();
}, NativeDispatcherPriority.Idle);
}
}
WpfCanvas IWpfXamlRootHost.NativeOverlayLayer => _nativeOverlayLayer;
bool IWpfXamlRootHost.IgnorePixelScaling => WpfHost.Current?.IgnorePixelScaling ?? false;
RenderSurfaceType? IWpfXamlRootHost.RenderSurfaceType => WpfHost.Current?.RenderSurfaceType ?? null;
| UnoWpfWindowHost |
csharp | dotnetcore__FreeSql | FreeSql/Extensions/AdoNetExtensions.cs | {
"start": 23091,
"end": 23451
} | class ____ T8 : class =>
Select<T1>(that).From<T2, T3, T4, T5, T6, T7, T8>((s, b, c, d, e, f, g, h) => s);
/// <summary>
/// 多表查询
/// </summary>
/// <returns></returns>
public static ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> Select<T1, T2, T3, T4, T5, T6, T7, T8, T9>(this IDbTransaction that) where T1 : | where |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Http/BasicAuthentication/basic_authentication.cs | {
"start": 1962,
"end": 2766
} | class ____<TLogFormat, TStreamId> : with_admin_user<TLogFormat, TStreamId> {
protected override async Task Given() {
var response = await MakeJsonPost(
"/users/", new { LoginName = "test1", FullName = "User Full Name", Password = "Pa55w0rd!" }, _admin);
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}
protected override async Task When() {
await GetJson<JObject>("/test1", credentials: new NetworkCredential("test1", "Pa55w0rd!"));
}
[Test]
public void returns_ok_status_code() {
Assert.AreEqual(HttpStatusCode.OK, _lastResponse.StatusCode);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
| when_requesting_a_protected_resource_with_credentials_provided |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/Localization/Utils/LocalizedUrlHelper.cs | {
"start": 176,
"end": 3396
} | public class ____
{
private readonly string _pathBase;
private string _path;
private string? _cultureCode;
public LocalizedUrlHelper(HttpRequest httpRequest)
: this(httpRequest.PathBase.Value!, httpRequest.Path.Value!)
{
Guard.NotNull(httpRequest);
}
public LocalizedUrlHelper(string pathBase, string path)
{
Guard.NotNull(pathBase);
Guard.NotNull(path);
_pathBase = pathBase;
_path = path.TrimStart('/');
}
public string PathBase
{
get => _pathBase;
}
public string Path
{
get => _path;
private set
{
_path = value;
_cultureCode = null;
}
}
/// <summary>
/// Full path: PathBase + Path
/// </summary>
/// <returns></returns>
public string FullPath
{
get
{
var absPath = PathBase.EnsureEndsWith('/') + Path;
if (absPath.Length > 1 && absPath[0] != '/')
{
absPath = "/" + absPath;
}
return absPath;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsLocalizedUrl()
=> IsLocalizedUrl(out _);
public bool IsLocalizedUrl([MaybeNullWhen(false)] out string? cultureCode)
{
cultureCode = _cultureCode;
if (cultureCode != null)
{
return true;
}
var firstPart = _path;
if (firstPart.IsEmpty())
{
return false;
}
int firstSlash = firstPart.IndexOf('/');
if (firstSlash > 0)
{
firstPart = firstPart[..firstSlash];
}
if (CultureHelper.IsValidCultureCode(firstPart))
{
cultureCode = _cultureCode = firstPart;
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string StripCultureCode()
=> StripCultureCode(out _);
public string StripCultureCode(out string? cultureCode)
{
if (IsLocalizedUrl(out cultureCode))
{
Path = Path[cultureCode!.Length..].TrimStart('/');
}
return Path;
}
public string PrependCultureCode(string cultureCode, bool safe = false)
{
Guard.NotEmpty(cultureCode);
if (safe)
{
if (IsLocalizedUrl(out var currentCultureCode))
{
if (cultureCode == currentCultureCode)
{
return Path;
}
else
{
StripCultureCode(out _);
}
}
}
Path = (cultureCode + '/' + Path).TrimEnd('/');
return Path;
}
}
} | LocalizedUrlHelper |
csharp | MonoGame__MonoGame | MonoGame.Framework.Content.Pipeline/Graphics/VertexContent.cs | {
"start": 776,
"end": 11750
} | public sealed class ____
{
VertexChannelCollection channels;
VertexChannel<int> positionIndices;
IndirectPositionCollection positions;
/// <summary>
/// Gets the list of named vertex data channels in the VertexContent.
/// </summary>
/// <value>Collection of vertex data channels.</value>
public VertexChannelCollection Channels { get { return channels; } }
/// <summary>
/// Gets the list of position indices.
/// </summary>
/// <value>Position of the position index being retrieved.</value>
/// <remarks>This list adds a level of indirection between the actual triangle indices and the Positions member of the parent. This indirection preserves the topological vertex identity in cases where a single vertex position is used by triangles that straddle a discontinuity in some other data channel.
/// For example, the following code gets the position of the first vertex of the first triangle in a GeometryContent object:
/// parent.Positions[Vertices.PositionIndices[Indices[0]]]</remarks>
public VertexChannel<int> PositionIndices { get { return positionIndices; } }
/// <summary>
/// Gets position data from the parent mesh object.
/// </summary>
/// <value>Collection of vertex positions for the mesh.</value>
/// <remarks>The collection returned from this call provides a virtualized view of the vertex positions for this batch. The collection uses the contents of the PositionIndices property to index into the parent Positions. This collection is read-only. If you need to modify any contained values, edit the PositionIndices or Positions members directly.</remarks>
public IndirectPositionCollection Positions { get { return positions; } }
/// <summary>
/// Number of vertices for the content.
/// </summary>
/// <value>Number of vertices.</value>
public int VertexCount { get { return positionIndices.Count; } }
/// <summary>
/// Constructs a VertexContent instance.
/// </summary>
internal VertexContent(GeometryContent geom)
{
positionIndices = new VertexChannel<int>("PositionIndices");
positions = new IndirectPositionCollection(geom, positionIndices);
channels = new VertexChannelCollection(this);
}
/// <summary>
/// Appends a new vertex index to the end of the PositionIndices collection.
/// Other vertex channels will automatically be extended and the new indices populated with default values.
/// </summary>
/// <param name="positionIndex">Index into the MeshContent.Positions member of the parent.</param>
/// <returns>Index of the new entry. This can be added to the Indices member of the parent.</returns>
public int Add(int positionIndex)
{
return positionIndices.Items.Add(positionIndex);
}
/// <summary>
/// Appends multiple vertex indices to the end of the PositionIndices collection.
/// Other vertex channels will automatically be extended and the new indices populated with default values.
/// </summary>
/// <param name="positionIndexCollection">Index into the Positions member of the parent.</param>
public void AddRange(IEnumerable<int> positionIndexCollection)
{
positionIndices.InsertRange(positionIndices.Items.Count, positionIndexCollection);
}
/// <summary>
/// Converts design-time vertex position and channel data into a vertex buffer format that a graphics device can recognize.
/// </summary>
/// <returns>A packed vertex buffer.</returns>
/// <exception cref="InvalidContentException">One or more of the vertex channel types are invalid or an unrecognized name was passed to VertexElementUsage.</exception>
public VertexBufferContent CreateVertexBuffer()
{
var vertexBuffer = new VertexBufferContent(positions.Count);
var stride = SetupVertexDeclaration(vertexBuffer);
// TODO: Verify enough elements in channels to match positions?
// Write out data in an interleaved fashion each channel at a time, for example:
// |------------------------------------------------------------|
// |POSITION[0] | NORMAL[0] |TEX0[0] | POSITION[1]| NORMAL[1] |
// |-----------------------------------------------|------------|
// #0 |111111111111|____________|________|111111111111|____________|
// #1 |111111111111|111111111111|________|111111111111|111111111111|
// #2 |111111111111|111111111111|11111111|111111111111|111111111111|
// #0: Write position vertices using stride to skip over the other channels:
vertexBuffer.Write(0, stride, positions);
var channelOffset = VertexBufferContent.SizeOf(typeof(Vector3));
foreach (var channel in Channels)
{
// #N: Fill in the channel within each vertex
var channelType = channel.ElementType;
vertexBuffer.Write(channelOffset, stride, channelType, channel);
channelOffset += VertexBufferContent.SizeOf(channelType);
}
return vertexBuffer;
}
private int SetupVertexDeclaration(VertexBufferContent result)
{
var offset = 0;
// We always have a position channel
result.VertexDeclaration.VertexElements.Add(new VertexElement(offset, VertexElementFormat.Vector3,
VertexElementUsage.Position, 0));
offset += VertexElementFormat.Vector3.GetSize();
// Optional channels
foreach (var channel in Channels)
{
VertexElementFormat format;
VertexElementUsage usage;
// Try to determine the vertex format
if (channel.ElementType == typeof(Single))
format = VertexElementFormat.Single;
else if (channel.ElementType == typeof(Vector2))
format = VertexElementFormat.Vector2;
else if (channel.ElementType == typeof(Vector3))
format = VertexElementFormat.Vector3;
else if (channel.ElementType == typeof(Vector4))
format = VertexElementFormat.Vector4;
else if (channel.ElementType == typeof(Color))
format = VertexElementFormat.Color;
else if (channel.ElementType == typeof(Byte4))
format = VertexElementFormat.Byte4;
else if (channel.ElementType == typeof(Short2))
format = VertexElementFormat.Short2;
else if (channel.ElementType == typeof(Short4))
format = VertexElementFormat.Short4;
else if (channel.ElementType == typeof(NormalizedShort2))
format = VertexElementFormat.NormalizedShort2;
else if (channel.ElementType == typeof(NormalizedShort4))
format = VertexElementFormat.NormalizedShort4;
else if (channel.ElementType == typeof(HalfVector2))
format = VertexElementFormat.HalfVector2;
else if (channel.ElementType == typeof(HalfVector4))
format = VertexElementFormat.HalfVector4;
else
throw new InvalidContentException(string.Format("Unrecognized vertex content type: '{0}'", channel.ElementType));
// Try to determine the vertex usage
if (!VertexChannelNames.TryDecodeUsage(channel.Name, out usage))
throw new InvalidContentException(string.Format("Unknown vertex element usage for channel '{0}'", channel.Name));
// Try getting the usage index
var usageIndex = VertexChannelNames.DecodeUsageIndex(channel.Name);
result.VertexDeclaration.VertexElements.Add(new VertexElement(offset, format, usage, usageIndex));
offset += format.GetSize();
}
result.VertexDeclaration.VertexStride = offset;
return offset;
}
/// <summary>
/// Inserts a new vertex index to the PositionIndices collection.
/// Other vertex channels will automatically be extended and the new indices populated with default values.
/// </summary>
/// <param name="index">Vertex index to be inserted.</param>
/// <param name="positionIndex">Position of new vertex index in the collection.</param>
public void Insert(int index, int positionIndex)
{
positionIndices.Items.Insert(index, positionIndex);
}
/// <summary>
/// Inserts multiple vertex indices to the PositionIndices collection.
/// Other vertex channels will automatically be extended and the new indices populated with default values.
/// </summary>
/// <param name="index">Vertex index to be inserted.</param>
/// <param name="positionIndexCollection">Position of the first element of the inserted range in the collection.</param>
public void InsertRange(int index, IEnumerable<int> positionIndexCollection)
{
positionIndices.InsertRange(index, positionIndexCollection);
}
/// <summary>
/// Removes a vertex index from the specified location in both PositionIndices and VertexChannel<T>.
/// </summary>
/// <param name="index">Index of the vertex to be removed.</param>
public void RemoveAt(int index)
{
if (index < 0 || index >= VertexCount)
throw new ArgumentOutOfRangeException("index");
positionIndices.Items.RemoveAt(index);
foreach (var channel in channels)
channel.Items.RemoveAt(index);
}
/// <summary>
/// Removes a range of vertex indices from the specified location in both PositionIndices and VertexChannel<T>.
/// </summary>
/// <param name="index">Index of the first vertex index to be removed.</param>
/// <param name="count">Number of indices to remove.</param>
public void RemoveRange(int index, int count)
{
if (index < 0 || index >= VertexCount)
throw new ArgumentOutOfRangeException("index");
if (count < 0 || (index+count) > VertexCount)
throw new ArgumentOutOfRangeException("count");
positionIndices.RemoveRange(index, count);
foreach (var channel in channels)
channel.RemoveRange(index, count);
}
}
}
| VertexContent |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Demo/Views/Components/Themes/Shared/Demos/CarouselDemo/CarouselDemoViewComponent.cs | {
"start": 379,
"end": 638
} | public class ____ : AbpViewComponent
{
public const string ViewPath = "/Views/Components/Themes/Shared/Demos/CarouselDemo/Default.cshtml";
public virtual IViewComponentResult Invoke()
{
return View(ViewPath);
}
}
| CarouselDemoViewComponent |
csharp | icsharpcode__ILSpy | ICSharpCode.ILSpyX/MermaidDiagrammer/Factory.Relationships.cs | {
"start": 1341,
"end": 5673
} | partial class ____
{
private IProperty[] GetHasOneRelations(IProperty[] properties) => properties.Where(property => {
IType type = property.ReturnType;
if (type.TryGetNullableType(out var typeArg))
type = typeArg;
return selectedTypes!.Contains(type);
}).ToArray();
private (IProperty property, IType elementType)[] GetManyRelations(IProperty[] properties)
=> properties.Select(property => {
IType elementType = property.ReturnType.GetElementTypeFromIEnumerable(property.Compilation, true, out bool? isGeneric);
if (isGeneric == false && elementType.IsObject())
{
IProperty[] indexers = property.ReturnType.GetProperties(
p => p.IsIndexer && !p.ReturnType.IsObject(),
GetMemberOptions.IgnoreInheritedMembers).ToArray(); // TODO mayb order by declaring type instead of filtering
if (indexers.Length > 0)
elementType = indexers[0].ReturnType;
}
return isGeneric == true && selectedTypes!.Contains(elementType) ? (property, elementType) : default;
}).Where(pair => pair != default).ToArray();
/// <summary>Returns the relevant direct super type the <paramref name="type"/> inherits from
/// in a format matching <see cref="CD.Type.BaseType"/>.</summary>
private Dictionary<string, string?>? GetBaseType(IType type)
{
IType? relevantBaseType = type.DirectBaseTypes.SingleOrDefault(t => !t.IsInterface() && !t.IsObject());
return relevantBaseType == null ? default : new[] { BuildRelationship(relevantBaseType) }.ToDictionary(r => r.to, r => r.label);
}
/// <summary>Returns the direct interfaces implemented by <paramref name="type"/>
/// in a format matching <see cref="CD.Type.Interfaces"/>.</summary>
private Dictionary<string, string?[]>? GetInterfaces(ITypeDefinition type)
{
var interfaces = type.DirectBaseTypes.Where(t => t.IsInterface()).ToArray();
return interfaces.Length == 0 ? null
: interfaces.Select(i => BuildRelationship(i)).GroupBy(r => r.to)
.ToDictionary(g => g.Key, g => g.Select(r => r.label).ToArray());
}
/// <summary>Returns the one-to-one relations from <paramref name="type"/> to other <see cref="CD.Type"/>s
/// in a format matching <see cref="CD.Relationships.HasOne"/>.</summary>
private Dictionary<string, string>? MapHasOneRelations(Dictionary<IType, IProperty[]> hasOneRelationsByType, IType type)
=> hasOneRelationsByType.GetValue(type)?.Select(p => {
IType type = p.ReturnType;
string label = p.Name;
if (p.IsIndexer)
label += $"[{p.Parameters.Single().Type.Name} {p.Parameters.Single().Name}]";
if (type.TryGetNullableType(out var typeArg))
{
type = typeArg;
label += " ?";
}
return BuildRelationship(type, label);
}).ToDictionary(r => r.label!, r => r.to);
/// <summary>Returns the one-to-many relations from <paramref name="type"/> to other <see cref="CD.Type"/>s
/// in a format matching <see cref="CD.Relationships.HasMany"/>.</summary>
private Dictionary<string, string>? MapHasManyRelations(Dictionary<IType, (IProperty property, IType elementType)[]> hasManyRelationsByType, IType type)
=> hasManyRelationsByType.GetValue(type)?.Select(relation => {
(IProperty property, IType elementType) = relation;
return BuildRelationship(elementType, property.Name);
}).ToDictionary(r => r.label!, r => r.to);
/// <summary>Builds references to super types and (one/many) relations,
/// recording outside references on the way and applying labels if required.</summary>
/// <param name="type">The type to reference.</param>
/// <param name="propertyName">Used only for property one/many relations.</param>
private (string to, string? label) BuildRelationship(IType type, string? propertyName = null)
{
(string id, IType? openGeneric) = GetIdAndOpenGeneric(type);
AddOutsideReference(id, openGeneric ?? type);
// label the relation with the property name if provided or the closed generic type for super types
string? label = propertyName ?? (openGeneric == null ? null : GetName(type));
return (to: id, label);
}
private void AddOutsideReference(string typeId, IType type)
{
if (!selectedTypes!.Contains(type) && outsideReferences?.ContainsKey(typeId) == false)
outsideReferences.Add(typeId, type.Namespace + '.' + GetName(type));
}
}
} | ClassDiagrammerFactory |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.NetFramework/SmartThreadPool/WorkItemsGroupBase.cs | {
"start": 93,
"end": 17869
} | public abstract class ____ : IWorkItemsGroup
{
#region Private Fields
/// <summary>
/// Contains the name of this instance of SmartThreadPool.
/// Can be changed by the user.
/// </summary>
private string _name = "WorkItemsGroupBase";
public WorkItemsGroupBase()
{
IsIdle = true;
}
#endregion
#region IWorkItemsGroup Members
#region Public Methods
/// <summary>
/// Get/Set the name of the SmartThreadPool/WorkItemsGroup instance
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
#endregion
#region Abstract Methods
public abstract int Concurrency { get; set; }
public abstract int WaitingCallbacks { get; }
public abstract object[] GetStates();
public abstract WIGStartInfo WIGStartInfo { get; }
public abstract void Start();
public abstract void Cancel(bool abortExecution);
public abstract bool WaitForIdle(int millisecondsTimeout);
public abstract event WorkItemsGroupIdleHandler OnIdle;
internal abstract void Enqueue(WorkItem workItem);
internal virtual void PreQueueWorkItem() { }
#endregion
#region Common Base Methods
/// <summary>
/// Cancel all the work items.
/// Same as Cancel(false)
/// </summary>
public virtual void Cancel()
{
Cancel(false);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public void WaitForIdle()
{
WaitForIdle(Timeout.Infinite);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public bool WaitForIdle(TimeSpan timeout)
{
return WaitForIdle((int)timeout.TotalMilliseconds);
}
/// <summary>
/// IsIdle is true when there are no work items running or queued.
/// </summary>
public bool IsIdle { get; protected set; }
#endregion
#region QueueWorkItem
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item info</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion
#region QueueWorkItem(Action<...>)
public IWorkItemResult QueueWorkItem(Action action, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
delegate
{
action.Invoke ();
return null;
}, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2, arg3);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4> (
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2, arg3, arg4);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
#endregion
#region QueueWorkItem(Func<...>)
public IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke();
}, priority);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null,
priority);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null,
priority);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(
Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null,
priority);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(
Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3, arg4);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null,
priority);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
#endregion
#endregion
}
}
#endif
| WorkItemsGroupBase |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/Bundling/StandardBundles.cs | {
"start": 97,
"end": 189
} | public static class ____
{
public static string Global = "Global";
}
| Styles |
csharp | dotnetcore__Util | src/Util.FileStorage.Aliyun/IAliyunOssConfigProvider.cs | {
"start": 83,
"end": 246
} | public interface ____ : ITransientDependency {
/// <summary>
/// 获取配置
/// </summary>
Task<AliyunOssOptions> GetConfigAsync();
} | IAliyunOssConfigProvider |
csharp | DapperLib__Dapper | tests/Dapper.Tests/AsyncTests.cs | {
"start": 22316,
"end": 33902
} | private class ____
{
public string? Value { get; set; }
}
[Fact]
public async Task TypeBasedViaTypeAsync()
{
Type type = Common.GetSomeType();
dynamic actual = (await MarsConnection.QueryAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false)).FirstOrDefault()!;
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
[Fact]
public async Task TypeBasedViaTypeAsyncFirstOrDefault()
{
Type type = Common.GetSomeType();
dynamic actual = (await MarsConnection.QueryFirstOrDefaultAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false))!;
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
[Fact]
public async Task Issue22_ExecuteScalarAsync()
{
int i = await connection.ExecuteScalarAsync<int>("select 123").ConfigureAwait(false);
Assert.Equal(123, i);
i = await connection.ExecuteScalarAsync<int>("select cast(123 as bigint)").ConfigureAwait(false);
Assert.Equal(123, i);
long j = await connection.ExecuteScalarAsync<long>("select 123").ConfigureAwait(false);
Assert.Equal(123L, j);
j = await connection.ExecuteScalarAsync<long>("select cast(123 as bigint)").ConfigureAwait(false);
Assert.Equal(123L, j);
int? k = await connection.ExecuteScalarAsync<int?>("select @i", new { i = default(int?) }).ConfigureAwait(false);
Assert.Null(k);
}
[Fact]
public async Task Issue346_QueryAsyncConvert()
{
int i = (await connection.QueryAsync<int>("Select Cast(123 as bigint)").ConfigureAwait(false)).First();
Assert.Equal(123, i);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressionsAsync()
{
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2, Index = new Index() } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
p.Output(bob, b => b.Address!.Index!.Id);
await connection.ExecuteAsync(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
SET @AddressIndexId = '01088'", p).ConfigureAwait(false);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal("01088", bob.Address.Index.Id);
}
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_ScalarAsync()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
var result = (int)(await connection.ExecuteScalarAsync(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
select 42", p).ConfigureAwait(false))!;
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_Query_Default()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
var result = (await connection.QueryAsync<int>(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
select 42", p).ConfigureAwait(false)).Single();
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_QueryFirst()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
var result = (await connection.QueryFirstAsync<int>(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
select 42", p).ConfigureAwait(false));
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_Query_BufferedAsync()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
var result = (await connection.QueryAsync<int>(new CommandDefinition(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
select 42", p, flags: CommandFlags.Buffered)).ConfigureAwait(false)).Single();
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_Query_NonBufferedAsync()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
var result = (await connection.QueryAsync<int>(new CommandDefinition(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId
select 42", p, flags: CommandFlags.None)).ConfigureAwait(false)).Single();
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
public async Task TestSupportForDynamicParametersOutputExpressions_QueryMultipleAsync()
{
var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } };
var p = new DynamicParameters(bob);
p.Output(bob, b => b.PersonId);
p.Output(bob, b => b.Occupation);
p.Output(bob, b => b.NumberOfLegs);
p.Output(bob, b => b.Address!.Name);
p.Output(bob, b => b.Address!.PersonId);
int x, y;
using (var multi = await connection.QueryMultipleAsync(@"
SET @Occupation = 'grillmaster'
SET @PersonId = @PersonId + 1
SET @NumberOfLegs = @NumberOfLegs - 1
SET @AddressName = 'bobs burgers'
select 42
select 17
SET @AddressPersonId = @PersonId", p).ConfigureAwait(false))
{
x = multi.ReadAsync<int>().Result.Single();
y = multi.ReadAsync<int>().Result.Single();
}
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, x);
Assert.Equal(17, y);
}
[Fact]
public async Task TestSubsequentQueriesSuccessAsync()
{
var data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList();
Assert.Empty(data0);
var data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList();
Assert.Empty(data1);
var data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList();
Assert.Empty(data2);
data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList();
Assert.Empty(data0);
data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList();
Assert.Empty(data1);
data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList();
Assert.Empty(data2);
}
| BasicType |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/RequestManagement/WriteStreamMgr/when_write_stream_gets_stream_deleted.cs | {
"start": 544,
"end": 1545
} | public class ____ : RequestManagerSpecification<WriteEvents> {
protected override WriteEvents OnManager(FakePublisher publisher) {
return WriteEvents.ForSingleStream(
publisher,
CommitTimeout,
Envelope,
InternalCorrId,
ClientCorrId,
"test123",
ExpectedVersion.Any,
new(DummyEvent()),
CommitSource);
}
protected override IEnumerable<Message> WithInitialMessages() {
yield break;
}
protected override Message When() {
return new StorageMessage.StreamDeleted(InternalCorrId, 0, 0);
}
[Test]
public void failed_request_message_is_published() {
Assert.That(Produced.ContainsSingle<StorageMessage.RequestCompleted>(
x => x.CorrelationId == InternalCorrId && x.Success == false));
}
[Test]
public void the_envelope_is_replied_to_with_failure() {
Assert.That(Envelope.Replies.ContainsSingle<ClientMessage.WriteEventsCompleted>(
x => x.CorrelationId == ClientCorrId && x.Result == OperationResult.StreamDeleted));
}
}
| when_write_stream_gets_stream_deleted |
csharp | atata-framework__atata | test/Atata.IntegrationTests/DataProvision/DirectorySubjectTests.cs | {
"start": 50,
"end": 921
} | public sealed class ____
{
[Test]
public void Ctor_WithNullAsString() =>
Assert.Throws<ArgumentNullException>(() =>
new DirectorySubject((null as string)!));
[Test]
public void Ctor_WithNullAsDirectoryInfo() =>
Assert.Throws<ArgumentNullException>(() =>
new DirectorySubject((null as DirectoryInfo)!));
[Test]
public void Ctor_WithEmptyString() =>
Assert.Throws<ArgumentException>(() =>
new DirectorySubject(string.Empty));
[Test]
public void Name() =>
new DirectorySubject(Path.Combine("Parent", "Dir"))
.Name.Should.Be("Dir");
[Test]
public void FullName() =>
new DirectorySubject(Path.Combine("Parent", "Dir"))
.FullName.Should.Be(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Parent", "Dir"));
| DirectorySubjectTests |
csharp | louthy__language-ext | LanguageExt.Core/Concurrency/STM/CommuteRef.cs | {
"start": 483,
"end": 1207
} | struct ____<A>
{
internal CommuteRef(Ref<A> r) => Ref = r;
internal readonly Ref<A> Ref;
public A Value
{
get => Ref.Value;
set => Ref.Value = value;
}
public static implicit operator A(CommuteRef<A> r) => r.Value;
public override string ToString() => Value?.ToString() ?? "[null]";
public override int GetHashCode() => Value?.GetHashCode() ?? 0;
public override bool Equals(object? obj) => obj is A val && Equals(val);
public bool Equals(A other) => EqDefault<A>.Equals(other, Value);
public A Swap(Func<A, A> f) => Ref.Swap(f);
public IO<A> SwapIO(Func<A, A> f) => Ref.SwapIO(f);
public CommuteRef<A> Commute(Func<A, A> f) => Ref.Commute(f);
}
| CommuteRef |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/AudioTrackSupportInfo.cs | {
"start": 293,
"end": 3363
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal AudioTrackSupportInfo()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Media.Core.MediaDecoderStatus DecoderStatus
{
get
{
throw new global::System.NotImplementedException("The member MediaDecoderStatus AudioTrackSupportInfo.DecoderStatus is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=MediaDecoderStatus%20AudioTrackSupportInfo.DecoderStatus");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Media.Core.AudioDecoderDegradation Degradation
{
get
{
throw new global::System.NotImplementedException("The member AudioDecoderDegradation AudioTrackSupportInfo.Degradation is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AudioDecoderDegradation%20AudioTrackSupportInfo.Degradation");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Media.Core.AudioDecoderDegradationReason DegradationReason
{
get
{
throw new global::System.NotImplementedException("The member AudioDecoderDegradationReason AudioTrackSupportInfo.DegradationReason is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AudioDecoderDegradationReason%20AudioTrackSupportInfo.DegradationReason");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Media.Core.MediaSourceStatus MediaSourceStatus
{
get
{
throw new global::System.NotImplementedException("The member MediaSourceStatus AudioTrackSupportInfo.MediaSourceStatus is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=MediaSourceStatus%20AudioTrackSupportInfo.MediaSourceStatus");
}
}
#endif
// Forced skipping of method Windows.Media.Core.AudioTrackSupportInfo.DecoderStatus.get
// Forced skipping of method Windows.Media.Core.AudioTrackSupportInfo.Degradation.get
// Forced skipping of method Windows.Media.Core.AudioTrackSupportInfo.DegradationReason.get
// Forced skipping of method Windows.Media.Core.AudioTrackSupportInfo.MediaSourceStatus.get
}
}
| AudioTrackSupportInfo |
csharp | mysql-net__MySqlConnector | src/MySqlConnector/Core/ILoadBalancer.cs | {
"start": 32,
"end": 329
} | internal interface ____
{
/// <summary>
/// Returns an <see cref="IEnumerable{String}"/> containing <paramref name="hosts"/> in the order they
/// should be tried to satisfy the load balancing policy.
/// </summary>
IReadOnlyList<string> LoadBalance(IReadOnlyList<string> hosts);
}
| ILoadBalancer |
csharp | unoplatform__uno | src/Uno.UI.Composition/Generated/3.0.0.0/Microsoft.UI.Composition/CompositionPath.cs | {
"start": 259,
"end": 559
} | public partial class ____
{
// Skipping already declared method Microsoft.UI.Composition.CompositionPath.CompositionPath(Windows.Graphics.IGeometrySource2D)
// Forced skipping of method Microsoft.UI.Composition.CompositionPath.CompositionPath(Windows.Graphics.IGeometrySource2D)
}
}
| CompositionPath |
csharp | ardalis__Specification | tests/Ardalis.Specification.Tests/Builders/Builder_OrderThenBy.cs | {
"start": 67,
"end": 5273
} | public record ____(int Id, string FirstName, string LastName, string Email);
[Fact]
public void DoesNothing_GivenThenByWithFalseCondition()
{
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName, false);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName, false);
spec1.OrderExpressions.Should().ContainSingle();
spec1.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy));
spec2.OrderExpressions.Should().ContainSingle();
spec2.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy));
}
[Fact]
public void DoesNothing_GivenThenByWithDiscardedTopChain()
{
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName, false)
.ThenBy(x => x.LastName);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName, false)
.ThenBy(x => x.LastName);
spec1.OrderExpressions.Should().BeEmpty();
spec2.OrderExpressions.Should().BeEmpty();
}
[Fact]
public void DoesNothing_GivenThenByWithDiscardedNestedChain()
{
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName, false)
.ThenBy(x => x.Email);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName, false)
.ThenBy(x => x.Email);
spec1.OrderExpressions.Should().ContainSingle();
spec1.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy));
spec2.OrderExpressions.Should().ContainSingle();
spec2.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy));
}
[Fact]
public void AddsThenBy_GivenThenBy()
{
Expression<Func<Customer, object?>> expr = x => x.LastName;
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName)
.ThenBy(expr);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName)
.ThenBy(expr);
spec1.OrderExpressions.Should().HaveCount(2);
spec1.OrderExpressions.Last().KeySelector.Should().BeSameAs(expr);
spec1.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec1.OrderExpressions.Last().OrderType.Should().Be(OrderTypeEnum.ThenBy);
spec2.OrderExpressions.Should().HaveCount(2);
spec2.OrderExpressions.Last().KeySelector.Should().BeSameAs(expr);
spec2.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec2.OrderExpressions.Last().OrderType.Should().Be(OrderTypeEnum.ThenBy);
}
[Fact]
public void AddsThenBy_GivenMultipleThenBy()
{
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ThenBy(x => x.Email);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ThenBy(x => x.Email);
spec1.OrderExpressions.Should().HaveCount(3);
spec1.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec1.OrderExpressions.Skip(1).Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.ThenBy));
spec2.OrderExpressions.Should().HaveCount(3);
spec2.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec2.OrderExpressions.Skip(1).Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.ThenBy));
}
[Fact]
public void AddsThenBy_GivenThenByThenByDescending()
{
var spec1 = new Specification<Customer>();
spec1.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ThenByDescending(x => x.Email);
var spec2 = new Specification<Customer, string>();
spec2.Query
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ThenByDescending(x => x.Email);
spec1.OrderExpressions.Should().HaveCount(3);
spec1.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec1.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.ThenBy);
spec1.OrderExpressions.Last().OrderType.Should().Be(OrderTypeEnum.ThenByDescending);
spec2.OrderExpressions.Should().HaveCount(3);
spec2.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy);
spec2.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.ThenBy);
spec2.OrderExpressions.Last().OrderType.Should().Be(OrderTypeEnum.ThenByDescending);
}
}
| Customer |
csharp | microsoft__semantic-kernel | dotnet/src/Experimental/Process.IntegrationTests.Resources/ProcessCycleTestResources.cs | {
"start": 7245,
"end": 8305
} | public sealed class ____ : KernelProcessStep<StepState>
{
private StepState? _state;
public override ValueTask ActivateAsync(KernelProcessStepState<StepState> state)
{
this._state = state.State;
return default;
}
[KernelFunction]
public async Task EmitCombinedMessageAsync(KernelProcessStepContext context, string firstInput, string secondInput)
{
var output = $"{firstInput}-{secondInput}";
Console.WriteLine($"[EMIT_COMBINED] {output}");
this._state!.LastMessage = output;
await context.EmitEventAsync(new()
{
Id = ProcessTestsEvents.OutputReadyInternal,
Data = output,
Visibility = KernelProcessEventVisibility.Internal
});
await context.EmitEventAsync(new()
{
Id = ProcessTestsEvents.OutputReadyPublic,
Data = output,
Visibility = KernelProcessEventVisibility.Public
});
}
}
/// <summary>
/// A step that conditionally throws an exception.
/// </summary>
| FanInStep |
csharp | FastEndpoints__FastEndpoints | Tests/IntegrationTests/FastEndpoints/MessagingTests/CommandBusTests.cs | {
"start": 2050,
"end": 2374
} | public class ____ : ICommandHandler<VoidCommand>
{
public static string FullName = default!;
public Task ExecuteAsync(VoidCommand command, CancellationToken ct)
{
FullName = command.FirstName + " " + command.LastName + " z";
return Task.CompletedTask;
}
}
[DontRegister]
| TestVoidCommandHandler |
csharp | nunit__nunit | src/NUnitFramework/framework/Constraints/CollectionItemsEqualConstraint.cs | {
"start": 284,
"end": 431
} | class ____ all
/// collection constraints that apply some notion of item equality
/// as a part of their operation.
/// </summary>
| for |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/PublishFaultObserver_Specs.cs | {
"start": 1602,
"end": 1685
} | public interface ____
{
int Index { get; }
}
| Test |
csharp | CommunityToolkit__dotnet | src/CommunityToolkit.HighPerformance/Helpers/ParallelHelper.ForEach.IInAction.cs | {
"start": 7086,
"end": 7323
} | public interface ____<T>
{
/// <summary>
/// Executes the action on a specified <typeparamref name="T"/> item.
/// </summary>
/// <param name="item">The current item to process.</param>
void Invoke(in T item);
}
| IInAction |
csharp | dotnet__efcore | test/EFCore.Relational.Specification.Tests/Scaffolding/CompiledModelRelationalTestBase.cs | {
"start": 350,
"end": 53459
} | public abstract class ____(NonSharedFixture fixture) : CompiledModelTestBase(fixture)
{
[ConditionalFact]
public virtual Task BigModel_with_JSON_columns()
=> Test(
modelBuilder => BuildBigModel(modelBuilder, jsonColumns: true),
model => AssertBigModel(model, jsonColumns: true),
context => UseBigModel(context, jsonColumns: true),
options: new CompiledModelCodeGenerationOptions { UseNullableReferenceTypes = true, ForNativeAot = true });
protected override void BuildBigModel(ModelBuilder modelBuilder, bool jsonColumns)
{
base.BuildBigModel(modelBuilder, jsonColumns);
modelBuilder.Entity<PrincipalBase>(eb =>
{
if (!jsonColumns)
{
eb.Property(e => e.Id)
.Metadata.SetColumnName("DerivedId", StoreObjectIdentifier.Table("PrincipalDerived"));
}
eb.HasIndex(e => new { e.AlternateId, e.Id });
eb.HasKey(e => new { e.Id, e.AlternateId })
.HasName("PK");
eb.OwnsOne(
e => e.Owned, ob =>
{
ob.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotificationsWithOriginalValues);
ob.UsePropertyAccessMode(PropertyAccessMode.Field);
if (jsonColumns)
{
ob.ToJson();
}
else
{
ob.ToTable(
"PrincipalBase", "mySchema",
t => t.Property("PrincipalBaseId"));
ob.SplitToTable("Details", s => s.Property(e => e.Details));
}
});
if (!jsonColumns)
{
eb.ToTable("PrincipalBase", "mySchema");
}
});
modelBuilder.Entity<PrincipalDerived<DependentBase<byte?>>>(eb =>
{
eb.OwnsMany(
typeof(OwnedType).FullName!, "ManyOwned", ob =>
{
if (jsonColumns)
{
ob.ToJson();
}
else
{
ob.ToTable("ManyOwned");
}
});
eb.HasMany(e => e.Principals).WithMany(e => (ICollection<PrincipalDerived<DependentBase<byte?>>>)e.Deriveds)
.UsingEntity(jb =>
{
jb.ToTable(tb =>
{
tb.HasComment("Join table");
tb.ExcludeFromMigrations();
});
jb.Property<byte[]>("rowid")
.IsRowVersion()
.HasComment("RowVersion")
.HasColumnOrder(1);
});
if (!jsonColumns)
{
eb.ToTable("PrincipalDerived");
}
});
modelBuilder.Entity<DependentDerived<byte?>>(eb =>
{
eb.Property<string>("Data")
.IsFixedLength();
});
modelBuilder.Entity<ManyTypes>(b =>
{
b.Ignore(e => e.BoolNestedCollection);
b.Ignore(e => e.UInt8NestedCollection);
b.Ignore(e => e.Int8NestedCollection);
b.Ignore(e => e.Int32NestedCollection);
b.Ignore(e => e.Int64NestedCollection);
b.Ignore(e => e.CharNestedCollection);
b.Ignore(e => e.GuidNestedCollection);
b.Ignore(e => e.StringNestedCollection);
b.Ignore(e => e.BytesNestedCollection);
b.Ignore(e => e.NullableUInt8NestedCollection);
b.Ignore(e => e.NullableInt32NestedCollection);
b.Ignore(e => e.NullableInt64NestedCollection);
b.Ignore(e => e.NullableGuidNestedCollection);
b.Ignore(e => e.NullableStringNestedCollection);
b.Ignore(e => e.NullableBytesNestedCollection);
b.Ignore(e => e.NullablePhysicalAddressNestedCollection);
b.Ignore(e => e.Enum8NestedCollection);
b.Ignore(e => e.Enum32NestedCollection);
b.Ignore(e => e.EnumU64NestedCollection);
b.Ignore(e => e.NullableEnum8NestedCollection);
b.Ignore(e => e.NullableEnum32NestedCollection);
b.Ignore(e => e.NullableEnumU64NestedCollection);
});
}
protected override void AssertBigModel(IModel model, bool jsonColumns)
{
base.AssertBigModel(model, jsonColumns);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(model.GetCollation).Message);
var manyTypesType = model.FindEntityType(typeof(ManyTypes))!;
Assert.Equal("ManyTypes", manyTypesType.GetTableName());
Assert.Null(manyTypesType.GetSchema());
var ipAddressCollection = manyTypesType.FindProperty(nameof(ManyTypes.IPAddressReadOnlyCollection))!;
var ipAddressElementType = ipAddressCollection.GetElementType();
Assert.NotNull(ipAddressCollection.GetColumnType());
var principalBase = model.FindEntityType(typeof(PrincipalBase))!;
Assert.Equal("PrincipalBase", principalBase.GetTableName());
var principalId = principalBase.FindProperty(nameof(PrincipalBase.Id))!;
var discriminatorProperty = principalBase.FindDiscriminatorProperty();
if (jsonColumns)
{
Assert.Null(principalBase.GetSchema());
Assert.Equal("Id", principalId.GetColumnName(StoreObjectIdentifier.Table("PrincipalBase")));
Assert.Null(principalId.GetColumnName(StoreObjectIdentifier.Table("PrincipalDerived")));
Assert.Equal("Discriminator", discriminatorProperty!.Name);
Assert.Equal(typeof(string), discriminatorProperty.ClrType);
}
else
{
Assert.Equal("mySchema", principalBase.GetSchema());
Assert.Equal("Id", principalId.GetColumnName(StoreObjectIdentifier.Table("PrincipalBase", "mySchema")));
Assert.Equal("DerivedId", principalId.GetColumnName(StoreObjectIdentifier.Table("PrincipalDerived")));
Assert.Null(discriminatorProperty);
}
Assert.Equal("Id", principalId.GetColumnName());
var principalAlternateId = principalBase.FindProperty(nameof(PrincipalBase.AlternateId))!;
Assert.Equal(PropertyAccessMode.FieldDuringConstruction, principalAlternateId.GetPropertyAccessMode());
var compositeIndex = principalBase.GetIndexes().Single();
Assert.Empty(compositeIndex.GetAnnotations());
Assert.Equal([principalAlternateId, principalId], compositeIndex.Properties);
Assert.False(compositeIndex.IsUnique);
Assert.Null(compositeIndex.Name);
Assert.Equal([compositeIndex], principalAlternateId.GetContainingIndexes());
Assert.Equal("IX_PrincipalBase_AlternateId_Id", compositeIndex.GetDatabaseName());
Assert.Equal(2, principalBase.GetKeys().Count());
var principalAlternateKey = principalBase.GetKeys().First();
Assert.Equal("AK_PrincipalBase_Id", principalAlternateKey.GetName());
var principalKey = principalBase.GetKeys().Last();
Assert.Equal(
[RelationalAnnotationNames.Name],
principalKey.GetAnnotations().Select(a => a.Name));
Assert.Equal("PK", principalKey.GetName());
Assert.Equal([principalAlternateKey, principalKey], principalId.GetContainingKeys());
Assert.Equal("PrincipalBase", principalBase.GetTableName());
if (jsonColumns)
{
Assert.Null(principalBase.GetSchema());
}
else
{
Assert.Equal("mySchema", principalBase.GetSchema());
}
var principalDerived = model.FindEntityType(typeof(PrincipalDerived<DependentBase<byte?>>))!;
Assert.Equal("PrincipalDerived<DependentBase<byte?>>", principalDerived.GetDiscriminatorValue());
var dependentNavigation = principalDerived.GetDeclaredNavigations().First();
var dependentForeignKey = dependentNavigation.ForeignKey;
var referenceOwnedNavigation = principalBase.GetNavigations().Single();
var referenceOwnedType = referenceOwnedNavigation.TargetEntityType;
var principalTable = StoreObjectIdentifier.Create(referenceOwnedType, StoreObjectType.Table)!.Value;
var ownedId = referenceOwnedType.FindProperty("PrincipalBaseId")!;
Assert.True(ownedId.IsPrimaryKey());
var detailsProperty = referenceOwnedType.FindProperty(nameof(OwnedType.Details))!;
Assert.Null(detailsProperty[RelationalAnnotationNames.Collation]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(detailsProperty.GetCollation).Message);
if (jsonColumns)
{
Assert.Empty(referenceOwnedType.GetMappingFragments());
}
else
{
var ownedFragment = referenceOwnedType.GetMappingFragments().Single();
Assert.Equal(nameof(OwnedType.Details), detailsProperty.GetColumnName(ownedFragment.StoreObject));
}
Assert.Null(detailsProperty.GetColumnName(principalTable));
var referenceOwnership = referenceOwnedNavigation.ForeignKey;
var ownedCollectionNavigation = principalDerived.GetDeclaredNavigations().Last();
var collectionOwnership = ownedCollectionNavigation.ForeignKey;
var tptForeignKey = principalDerived.GetForeignKeys().SingleOrDefault();
if (jsonColumns)
{
Assert.Null(tptForeignKey);
}
else
{
Assert.False(tptForeignKey!.IsOwnership);
Assert.True(tptForeignKey.IsRequired);
Assert.False(tptForeignKey.IsRequiredDependent);
Assert.True(tptForeignKey.IsUnique);
Assert.Null(tptForeignKey.DependentToPrincipal);
Assert.Null(tptForeignKey.PrincipalToDependent);
Assert.Equal(DeleteBehavior.Cascade, tptForeignKey.DeleteBehavior);
Assert.Equal(principalKey.Properties, tptForeignKey.Properties);
Assert.Same(principalKey, tptForeignKey.PrincipalKey);
}
var derivedSkipNavigation = principalDerived.GetDeclaredSkipNavigations().Single();
Assert.Same(derivedSkipNavigation, derivedSkipNavigation.ForeignKey.GetReferencingSkipNavigations().Single());
Assert.Same(
derivedSkipNavigation.Inverse, derivedSkipNavigation.Inverse.ForeignKey.GetReferencingSkipNavigations().Single());
Assert.Equal([derivedSkipNavigation.Inverse, derivedSkipNavigation], principalDerived.GetSkipNavigations());
var joinType = derivedSkipNavigation.JoinEntityType;
Assert.Null(joinType[RelationalAnnotationNames.Comment]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(joinType.GetComment).Message);
Assert.Empty(joinType.GetDeclaredQueryFilters());
Assert.Null(joinType[RelationalAnnotationNames.IsTableExcludedFromMigrations]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(() => joinType.IsTableExcludedFromMigrations()).Message);
var rowid = joinType.GetProperties().Single(p => !p.IsForeignKey());
Assert.True(rowid.IsConcurrencyToken);
Assert.Equal(ValueGenerated.OnAddOrUpdate, rowid.ValueGenerated);
Assert.Equal("rowid", rowid.GetColumnName());
Assert.Null(rowid[RelationalAnnotationNames.Comment]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(rowid.GetComment).Message);
Assert.Null(rowid[RelationalAnnotationNames.ColumnOrder]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(() => rowid.GetColumnOrder()).Message);
var dependentBase = dependentNavigation.TargetEntityType;
var dependentDerived = dependentBase.GetDerivedTypes().Single();
var dependentData = dependentDerived.GetDeclaredProperties().First();
Assert.Equal("Data", dependentData.GetColumnName());
Assert.True(dependentData.IsFixedLength());
var dependentBaseForeignKey = dependentBase.GetForeignKeys().Single(fk => fk != dependentForeignKey);
var joinTable = joinType.GetTableMappings().Single().Table;
Assert.Null(joinTable[RelationalAnnotationNames.Comment]);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(() => joinTable.Comment).Message);
var dependentMoney = dependentDerived.GetDeclaredProperties().Last();
Assert.Equal("Money", dependentMoney.GetColumnName());
Assert.Null(dependentMoney.IsFixedLength());
if (jsonColumns)
{
Assert.Equal(
[
derivedSkipNavigation.ForeignKey,
referenceOwnership,
collectionOwnership,
dependentForeignKey,
derivedSkipNavigation.Inverse.ForeignKey
],
principalKey.GetReferencingForeignKeys());
Assert.Equal(
[dependentBaseForeignKey, referenceOwnership, derivedSkipNavigation.Inverse.ForeignKey],
principalBase.GetReferencingForeignKeys());
}
else
{
Assert.Equal(
[
derivedSkipNavigation.ForeignKey,
tptForeignKey,
referenceOwnership,
collectionOwnership,
dependentForeignKey,
derivedSkipNavigation.Inverse.ForeignKey
],
principalKey.GetReferencingForeignKeys());
Assert.Equal(
[dependentBaseForeignKey, tptForeignKey, referenceOwnership, derivedSkipNavigation.Inverse.ForeignKey],
principalBase.GetReferencingForeignKeys());
}
}
protected override void BuildComplexTypesModel(ModelBuilder modelBuilder)
{
base.BuildComplexTypesModel(modelBuilder);
modelBuilder.Entity<PrincipalBase>(eb =>
{
eb.Property("FlagsEnum2");
eb.ComplexProperty(
e => e.Owned, eb =>
{
eb.Property(c => c.Details)
.IsRowVersion()
.HasColumnName("Deets")
.HasColumnOrder(1)
.HasColumnType("varchar")
.HasComment("Dt");
});
eb.ToTable("PrincipalBase");
eb.ToView("PrincipalBaseView");
eb.ToSqlQuery("select * from PrincipalBase");
eb.ToFunction("PrincipalBaseTvf");
eb.InsertUsingStoredProcedure(s => s
.HasParameter("PrincipalBaseId")
.HasParameter("Enum1")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasParameter("Discriminator")
.HasParameter(p => p.Id, p => p.IsOutput()));
eb.UpdateUsingStoredProcedure(s => s
.HasParameter("PrincipalBaseId")
.HasParameter("Enum1")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasOriginalValueParameter(p => p.Id));
eb.DeleteUsingStoredProcedure(s => s.HasRowsAffectedParameter()
.HasOriginalValueParameter(p => p.Id));
});
modelBuilder.Entity<PrincipalDerived<DependentBase<byte?>>>(eb =>
{
eb.ToTable("PrincipalBase");
eb.ToFunction((string?)null);
});
modelBuilder.Entity<PrincipalDerived<DependentBase<byte?>>>(eb =>
{
eb.ComplexCollection<IList<OwnedType>, OwnedType>(
"ManyOwned", "OwnedCollection", eb => eb.ToJson());
});
}
[ConditionalFact]
public override Task ComplexTypes()
=> Test(
BuildComplexTypesModel,
AssertComplexTypes,
c =>
{
// Sprocs not supported with complex types, see #31235
//c.Set<PrincipalDerived<DependentBase<byte?>>>().Add(
// new PrincipalDerived<DependentBase<byte?>>
// {
// Id = 1,
// AlternateId = new Guid(),
// Dependent = new DependentBase<byte?>(1),
// Owned = new OwnedType(c) { Principal = new PrincipalBase() }
// });
//c.SaveChanges();
return Task.CompletedTask;
},
options: new CompiledModelCodeGenerationOptions { UseNullableReferenceTypes = true, ForNativeAot = true });
protected override void AssertComplexTypes(IModel model)
{
base.AssertComplexTypes(model);
var principalBase = model.FindEntityType(typeof(PrincipalBase))!;
var complexProperty = principalBase.GetComplexProperties().Single();
var complexType = complexProperty.ComplexType;
Assert.Equal(
[
RelationalAnnotationNames.FunctionName,
RelationalAnnotationNames.Schema,
RelationalAnnotationNames.SqlQuery,
RelationalAnnotationNames.TableName,
RelationalAnnotationNames.ViewName,
RelationalAnnotationNames.ViewSchema,
"go"
],
complexType.GetAnnotations().Select(a => a.Name));
var detailsProperty = complexType.FindProperty(nameof(OwnedType.Details))!;
Assert.True(detailsProperty.IsConcurrencyToken);
Assert.Equal(ValueGenerated.OnAddOrUpdate, detailsProperty.ValueGenerated);
Assert.Equal(PropertySaveBehavior.Ignore, detailsProperty.GetAfterSaveBehavior());
Assert.Equal(PropertySaveBehavior.Ignore, detailsProperty.GetBeforeSaveBehavior());
Assert.Equal("Deets", detailsProperty.GetColumnName());
Assert.Equal("varchar(64)", detailsProperty.GetColumnType());
Assert.Null(detailsProperty.IsFixedLength());
Assert.Null(detailsProperty.GetDefaultValueSql());
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(detailsProperty.GetCollation).Message);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(detailsProperty.GetComment).Message);
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(() => detailsProperty.GetColumnOrder()).Message);
var principalTableId = StoreObjectIdentifier.Create(complexType, StoreObjectType.Table)!.Value;
Assert.Equal("Deets", detailsProperty.GetColumnName(principalTableId));
var principalTable = principalBase.GetTableMappings().Single().Table;
Assert.False(principalTable.IsOptional(complexType));
var dbFunction = model.FindDbFunction("PrincipalBaseTvf")!;
Assert.False(dbFunction.IsNullable);
Assert.False(dbFunction.IsScalar);
Assert.False(dbFunction.IsBuiltIn);
Assert.False(dbFunction.IsAggregate);
Assert.Null(dbFunction.Translation);
Assert.Null(dbFunction.TypeMapping);
Assert.Equal(typeof(IQueryable<PrincipalBase>), dbFunction.ReturnType);
Assert.Null(dbFunction.MethodInfo);
Assert.Empty(dbFunction.GetAnnotations());
Assert.Empty(dbFunction.GetRuntimeAnnotations());
Assert.Equal("PrincipalBaseTvf", dbFunction.StoreFunction.Name);
Assert.False(dbFunction.StoreFunction.IsShared);
Assert.NotNull(dbFunction.ToString());
Assert.Empty(dbFunction.Parameters);
var principalBaseFunctionMapping = principalBase.GetFunctionMappings().Single(m => m.IsDefaultFunctionMapping);
Assert.True(principalBaseFunctionMapping.IncludesDerivedTypes);
Assert.Null(principalBaseFunctionMapping.IsSharedTablePrincipal);
Assert.Null(principalBaseFunctionMapping.IsSplitEntityTypePrincipal);
Assert.Same(dbFunction, principalBaseFunctionMapping.DbFunction);
}
[ConditionalFact]
public virtual Task Tpc_Sprocs()
=> Test(
BuildTpcSprocsModel,
AssertTpcSprocs,
options: new CompiledModelCodeGenerationOptions { UseNullableReferenceTypes = true, ForNativeAot = true });
protected virtual void BuildTpcSprocsModel(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("TPC");
modelBuilder.Entity<PrincipalBase>(eb =>
{
eb.Ignore(e => e.Owned);
eb.Property("FlagsEnum2");
eb.UseTpcMappingStrategy();
eb.ToTable("PrincipalBase");
eb.ToView("PrincipalBaseView", tb => tb.Property(e => e.Id).HasAnnotation("foo", "bar2"));
eb.Property(p => p.Id).ValueGeneratedNever();
eb.Property(p => p.Enum1).HasDefaultValue(AnEnum.A).HasSentinel(AnEnum.A);
eb.InsertUsingStoredProcedure(s => s
.HasParameter(p => p.Id)
.HasParameter("PrincipalBaseId")
.HasParameter("PrincipalDerivedId")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasParameter(p => p.Enum1, pb => pb.HasName("BaseEnum").IsOutput().HasAnnotation("foo", "bar"))
.HasAnnotation("foo", "bar1"));
eb.UpdateUsingStoredProcedure(s => s
.HasParameter("PrincipalBaseId")
.HasParameter("PrincipalDerivedId")
.HasParameter("Enum1")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasOriginalValueParameter(p => p.Id));
eb.DeleteUsingStoredProcedure(s =>
{
s.HasOriginalValueParameter(p => p.Id);
if (UseSprocReturnValue)
{
s.HasRowsAffectedReturnValue();
}
else
{
s.HasRowsAffectedParameter(p => p.HasName("RowsAffected"));
}
});
eb.HasIndex(["PrincipalBaseId"], "PrincipalIndex")
.IsUnique()
.HasDatabaseName("PIX")
.HasFilter("AlternateId <> NULL");
});
modelBuilder.Entity<PrincipalDerived<DependentBase<byte?>>>(eb =>
{
eb.HasOne(e => e.Dependent).WithOne(e => e.Principal)
.HasForeignKey<DependentBase<byte?>>()
.OnDelete(DeleteBehavior.ClientCascade);
eb.Navigation(e => e.Dependent).IsRequired();
eb.ToTable("PrincipalDerived");
eb.ToView("PrincipalDerivedView");
eb.Property(p => p.Id).ValueGeneratedNever();
eb.Property(p => p.Enum1).HasDefaultValue(AnEnum.A).HasSentinel(AnEnum.A);
eb.InsertUsingStoredProcedure(
"Derived_Insert", s => s
.HasParameter(p => p.Id)
.HasParameter("PrincipalBaseId")
.HasParameter("PrincipalDerivedId")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasResultColumn(p => p.Enum1, pb => pb.HasName("DerivedEnum").HasAnnotation("foo", "bar3")));
eb.UpdateUsingStoredProcedure(
"Derived_Update", "Derived", s => s
.HasParameter("PrincipalBaseId")
.HasParameter("PrincipalDerivedId")
.HasParameter("Enum1")
.HasParameter("Enum2")
.HasParameter("FlagsEnum1")
.HasParameter("FlagsEnum2")
.HasParameter("ValueTypeList")
.HasParameter("ValueTypeIList")
.HasParameter("ValueTypeArray")
.HasParameter("ValueTypeEnumerable")
.HasParameter("RefTypeList")
.HasParameter("RefTypeIList")
.HasParameter("RefTypeArray")
.HasParameter("RefTypeEnumerable")
.HasOriginalValueParameter(p => p.Id));
eb.DeleteUsingStoredProcedure(
"Derived_Delete", s => s
.HasOriginalValueParameter(p => p.Id));
});
modelBuilder.Entity<DependentBase<byte?>>(eb =>
{
eb.Property<byte?>("Id");
});
}
protected virtual bool UseSprocReturnValue
=> false;
protected virtual void AssertTpcSprocs(IModel model)
{
Assert.Equal("TPC", model.GetDefaultSchema());
var principalBase = model.FindEntityType(typeof(PrincipalBase))!;
var id = principalBase.FindProperty(nameof(PrincipalBase.Id))!;
Assert.Equal("Id", id.GetColumnName());
Assert.Equal("PrincipalBase", principalBase.GetTableName());
Assert.Equal("TPC", principalBase.GetSchema());
Assert.Equal("Id", id.GetColumnName(StoreObjectIdentifier.Create(principalBase, StoreObjectType.Table)!.Value));
Assert.Null(id.FindOverrides(StoreObjectIdentifier.Create(principalBase, StoreObjectType.Table)!.Value));
Assert.Equal("PrincipalBaseView", principalBase.GetViewName());
Assert.Equal("TPC", principalBase.GetViewSchema());
Assert.Equal("Id", id.GetColumnName(StoreObjectIdentifier.Create(principalBase, StoreObjectType.View)!.Value));
Assert.Equal(
"bar2",
id.FindOverrides(StoreObjectIdentifier.Create(principalBase, StoreObjectType.View)!.Value)!["foo"]);
var enum1 = principalBase.FindProperty(nameof(PrincipalBase.Enum1))!;
Assert.Equal(AnEnum.A, enum1.GetDefaultValue());
var principalBaseId = principalBase.FindProperty("PrincipalBaseId")!;
var alternateIndex = principalBase.GetIndexes().Last();
Assert.Same(principalBaseId, alternateIndex.Properties.Single());
Assert.True(alternateIndex.IsUnique);
Assert.Equal("PrincipalIndex", alternateIndex.Name);
Assert.Equal("PIX", alternateIndex.GetDatabaseName());
Assert.Equal("AlternateId <> NULL", alternateIndex.GetFilter());
Assert.Equal([alternateIndex], principalBaseId.GetContainingIndexes());
var insertSproc = principalBase.GetInsertStoredProcedure()!;
Assert.Equal("PrincipalBase_Insert", insertSproc.Name);
Assert.Equal("TPC", insertSproc.Schema);
Assert.Equal(
[
"Id",
"PrincipalBaseId",
"PrincipalDerivedId",
"Enum2",
"FlagsEnum1",
"FlagsEnum2",
"ValueTypeList",
"ValueTypeIList",
"ValueTypeArray",
"ValueTypeEnumerable",
"RefTypeList",
"RefTypeIList",
"RefTypeArray",
"RefTypeEnumerable",
"Enum1"
],
insertSproc.Parameters.Select(p => p.PropertyName));
Assert.Empty(insertSproc.ResultColumns);
Assert.False(insertSproc.IsRowsAffectedReturned);
Assert.Equal("bar1", insertSproc["foo"]);
Assert.Same(principalBase, insertSproc.EntityType);
Assert.Equal("BaseEnum", insertSproc.Parameters.Last().Name);
Assert.Equal("bar", insertSproc.Parameters.Last()["foo"]);
Assert.Null(enum1.FindOverrides(StoreObjectIdentifier.Create(principalBase, StoreObjectType.InsertStoredProcedure)!.Value));
Assert.Equal(
"Enum1",
enum1.GetColumnName(StoreObjectIdentifier.Create(principalBase, StoreObjectType.InsertStoredProcedure)!.Value));
var updateSproc = principalBase.GetUpdateStoredProcedure()!;
Assert.Equal("PrincipalBase_Update", updateSproc.Name);
Assert.Equal("TPC", updateSproc.Schema);
Assert.Equal(
[
"PrincipalBaseId",
"PrincipalDerivedId",
"Enum1",
"Enum2",
"FlagsEnum1",
"FlagsEnum2",
"ValueTypeList",
"ValueTypeIList",
"ValueTypeArray",
"ValueTypeEnumerable",
"RefTypeList",
"RefTypeIList",
"RefTypeArray",
"RefTypeEnumerable",
"Id"
],
updateSproc.Parameters.Select(p => p.PropertyName));
Assert.Empty(updateSproc.ResultColumns);
Assert.False(updateSproc.IsRowsAffectedReturned);
Assert.Empty(updateSproc.GetAnnotations());
Assert.Same(principalBase, updateSproc.EntityType);
Assert.Equal("Id_Original", updateSproc.Parameters.Last().Name);
Assert.Null(enum1.FindOverrides(StoreObjectIdentifier.Create(principalBase, StoreObjectType.UpdateStoredProcedure)!.Value));
var deleteSproc = principalBase.GetDeleteStoredProcedure()!;
Assert.Equal("PrincipalBase_Delete", deleteSproc.Name);
Assert.Equal("TPC", deleteSproc.Schema);
if (UseSprocReturnValue)
{
Assert.Equal(["Id_Original"], deleteSproc.Parameters.Select(p => p.Name));
}
else
{
Assert.Equal(["Id_Original", "RowsAffected"], deleteSproc.Parameters.Select(p => p.Name));
}
Assert.Empty(deleteSproc.ResultColumns);
Assert.Equal(UseSprocReturnValue, deleteSproc.IsRowsAffectedReturned);
Assert.Same(principalBase, deleteSproc.EntityType);
Assert.Null(id.FindOverrides(StoreObjectIdentifier.Create(principalBase, StoreObjectType.DeleteStoredProcedure)!.Value));
Assert.Equal("PrincipalBase", principalBase.GetDiscriminatorValue());
Assert.Null(principalBase.FindDiscriminatorProperty());
Assert.Equal("TPC", principalBase.GetMappingStrategy());
var selfRefNavigation = principalBase.GetDeclaredNavigations().Last();
Assert.Equal("Deriveds", selfRefNavigation.Name);
Assert.True(selfRefNavigation.IsCollection);
Assert.False(selfRefNavigation.IsOnDependent);
Assert.Equal(principalBase, selfRefNavigation.TargetEntityType);
Assert.Null(selfRefNavigation.Inverse);
var principalDerived = model.FindEntityType(typeof(PrincipalDerived<DependentBase<byte?>>))!;
Assert.Equal(principalBase, principalDerived.BaseType);
Assert.Equal("PrincipalDerived", principalDerived.GetTableName());
Assert.Equal("TPC", principalDerived.GetSchema());
Assert.Equal("PrincipalDerivedView", principalDerived.GetViewName());
Assert.Equal("TPC", principalBase.GetViewSchema());
insertSproc = principalDerived.GetInsertStoredProcedure()!;
Assert.Equal("Derived_Insert", insertSproc.Name);
Assert.Equal("TPC", insertSproc.Schema);
Assert.Equal(
[
"Id",
"PrincipalBaseId",
"PrincipalDerivedId",
"Enum2",
"FlagsEnum1",
"FlagsEnum2",
"ValueTypeList",
"ValueTypeIList",
"ValueTypeArray",
"ValueTypeEnumerable",
"RefTypeList",
"RefTypeIList",
"RefTypeArray",
"RefTypeEnumerable"
],
insertSproc.Parameters.Select(p => p.PropertyName));
Assert.Equal(["Enum1"], insertSproc.ResultColumns.Select(p => p.PropertyName));
Assert.Null(insertSproc["foo"]);
Assert.Same(principalDerived, insertSproc.EntityType);
Assert.Equal("DerivedEnum", insertSproc.ResultColumns.Last().Name);
Assert.Equal(
"DerivedEnum",
enum1.GetColumnName(StoreObjectIdentifier.Create(principalDerived, StoreObjectType.InsertStoredProcedure)!.Value));
Assert.Equal("bar3", insertSproc.ResultColumns.Last()["foo"]);
Assert.Null(
enum1.FindOverrides(
StoreObjectIdentifier.Create(principalDerived, StoreObjectType.InsertStoredProcedure)!.Value)!["foo"]);
updateSproc = principalDerived.GetUpdateStoredProcedure()!;
Assert.Equal("Derived_Update", updateSproc.Name);
Assert.Equal("Derived", updateSproc.Schema);
Assert.Equal(
[
"PrincipalBaseId",
"PrincipalDerivedId",
"Enum1",
"Enum2",
"FlagsEnum1",
"FlagsEnum2",
"ValueTypeList",
"ValueTypeIList",
"ValueTypeArray",
"ValueTypeEnumerable",
"RefTypeList",
"RefTypeIList",
"RefTypeArray",
"RefTypeEnumerable",
"Id"
],
updateSproc.Parameters.Select(p => p.PropertyName));
Assert.Empty(updateSproc.ResultColumns);
Assert.Empty(updateSproc.GetAnnotations());
Assert.Same(principalDerived, updateSproc.EntityType);
Assert.Equal("Id_Original", updateSproc.Parameters.Last().Name);
Assert.Null(
id.FindOverrides(StoreObjectIdentifier.Create(principalDerived, StoreObjectType.UpdateStoredProcedure)!.Value));
deleteSproc = principalDerived.GetDeleteStoredProcedure()!;
Assert.Equal("Derived_Delete", deleteSproc.Name);
Assert.Equal("TPC", deleteSproc.Schema);
Assert.Equal(["Id"], deleteSproc.Parameters.Select(p => p.PropertyName));
Assert.Empty(deleteSproc.ResultColumns);
Assert.Same(principalDerived, deleteSproc.EntityType);
Assert.Equal("Id_Original", deleteSproc.Parameters.Last().Name);
Assert.Null(
id.FindOverrides(StoreObjectIdentifier.Create(principalDerived, StoreObjectType.DeleteStoredProcedure)!.Value));
Assert.Equal("PrincipalDerived<DependentBase<byte?>>", principalDerived.GetDiscriminatorValue());
Assert.Null(principalDerived.FindDiscriminatorProperty());
Assert.Equal("TPC", principalDerived.GetMappingStrategy());
Assert.Equal(2, principalDerived.GetDeclaredNavigations().Count());
var derivedNavigation = principalDerived.GetDeclaredNavigations().Last();
Assert.Equal("Principals", derivedNavigation.Name);
Assert.True(derivedNavigation.IsCollection);
Assert.False(derivedNavigation.IsOnDependent);
Assert.Equal(principalBase, derivedNavigation.TargetEntityType);
Assert.Null(derivedNavigation.Inverse);
var dependentNavigation = principalDerived.GetDeclaredNavigations().First();
Assert.Equal("Dependent", dependentNavigation.Name);
Assert.Equal("Dependent", dependentNavigation.PropertyInfo!.Name);
Assert.Equal("<Dependent>k__BackingField", dependentNavigation.FieldInfo!.Name);
Assert.False(dependentNavigation.IsCollection);
Assert.False(dependentNavigation.IsEagerLoaded);
Assert.True(dependentNavigation.LazyLoadingEnabled);
Assert.False(dependentNavigation.IsOnDependent);
Assert.Equal(principalDerived, dependentNavigation.DeclaringEntityType);
Assert.Equal("Principal", dependentNavigation.Inverse!.Name);
var dependentForeignKey = dependentNavigation.ForeignKey;
Assert.False(dependentForeignKey.IsOwnership);
Assert.False(dependentForeignKey.IsRequired);
Assert.True(dependentForeignKey.IsRequiredDependent);
Assert.True(dependentForeignKey.IsUnique);
Assert.Same(principalDerived, dependentForeignKey.PrincipalEntityType);
Assert.Same(dependentNavigation.Inverse, dependentForeignKey.DependentToPrincipal);
Assert.Same(dependentNavigation, dependentForeignKey.PrincipalToDependent);
Assert.Equal(DeleteBehavior.ClientCascade, dependentForeignKey.DeleteBehavior);
Assert.Equal(["PrincipalId"], dependentForeignKey.Properties.Select(p => p.Name));
var dependentBase = dependentNavigation.TargetEntityType;
Assert.True(dependentBase.GetIsDiscriminatorMappingComplete());
Assert.Null(dependentBase.FindDiscriminatorProperty());
Assert.Same(dependentForeignKey, dependentBase.GetForeignKeys().Single());
Assert.Equal(
[dependentBase, principalBase, principalDerived],
model.GetEntityTypes());
}
[ConditionalFact]
public virtual Task Sequences()
=> Test(
modelBuilder =>
modelBuilder.HasSequence<long>("Long")
.HasMin(-2)
.HasMax(2)
.IsCyclic()
.IncrementsBy(2)
.StartsAt(-4),
model =>
{
Assert.Single(model.GetSequences());
var longSequence = model.FindSequence("Long")!;
Assert.Same(model, longSequence.Model);
Assert.Equal(typeof(long), longSequence.Type);
Assert.True(longSequence.IsCyclic);
Assert.Equal(-4, longSequence.StartValue);
Assert.Equal(-2, longSequence.MinValue);
Assert.Equal(2, longSequence.MaxValue);
Assert.Equal(2, longSequence.IncrementBy);
Assert.NotNull(longSequence.ToString());
});
[ConditionalFact]
public virtual Task CheckConstraints()
=> Test(
modelBuilder => modelBuilder.Entity<Data>(eb =>
{
eb.Property<int>("Id");
eb.HasKey("Id");
eb.ToTable(tb => tb.HasCheckConstraint("idConstraint", "Id <> 0"));
eb.ToTable(tb => tb.HasCheckConstraint("anotherConstraint", "Id <> -1"));
}),
model =>
{
var dataEntity = model.GetEntityTypes().Single();
Assert.Equal(
CoreStrings.RuntimeModelMissingData,
Assert.Throws<InvalidOperationException>(() => dataEntity.GetCheckConstraints()).Message);
});
[ConditionalFact]
public virtual Task Triggers()
=> Test(
modelBuilder => modelBuilder.Entity<Data>(eb =>
{
eb.Property<int>("Id");
eb.HasKey("Id");
eb.ToTable(tb =>
{
tb.HasTrigger("Trigger1");
tb.HasTrigger("Trigger2");
});
}),
model =>
{
var dataEntity = model.GetEntityTypes().Single();
Assert.Equal(2, dataEntity.GetDeclaredTriggers().Count());
});
[ConditionalFact]
public virtual Task DbFunctions()
=> Test<DbFunctionContext>(
assertModel: model =>
{
Assert.Equal(5, model.GetDbFunctions().Count());
var getCount = model.FindDbFunction(
typeof(DbFunctionContext)
.GetMethod("GetCount", BindingFlags.NonPublic | BindingFlags.Instance)!)!;
Assert.Equal("CustomerOrderCount", getCount.Name);
Assert.Same(model, getCount.Model);
Assert.Same(model, ((IReadOnlyDbFunction)getCount).Model);
Assert.Equal(typeof(DbFunctionContext).FullName + ".GetCount(System.Guid?,string)", getCount.ModelName);
Assert.Equal("dbf", getCount.Schema);
Assert.False(getCount.IsNullable);
Assert.True(getCount.IsScalar);
Assert.False(getCount.IsBuiltIn);
Assert.False(getCount.IsAggregate);
Assert.Null(getCount.Translation);
Assert.NotNull(getCount.TypeMapping?.StoreType);
Assert.Equal(typeof(int), getCount.ReturnType);
Assert.Equal("GetCount", getCount.MethodInfo!.Name);
Assert.Empty(getCount.GetAnnotations());
Assert.Empty(getCount.GetRuntimeAnnotations());
Assert.Equal("CustomerOrderCount", getCount.StoreFunction.Name);
Assert.False(getCount.StoreFunction.IsShared);
Assert.NotNull(getCount.ToString());
Assert.Equal(getCount.Parameters, ((IReadOnlyDbFunction)getCount).Parameters);
Assert.Equal(2, getCount.Parameters.Count);
var getCountParameter1 = getCount.Parameters[0];
Assert.Same(getCount, getCountParameter1.Function);
Assert.Same(getCount, ((IReadOnlyDbFunctionParameter)getCountParameter1).Function);
Assert.Equal("id", getCountParameter1.Name);
Assert.NotNull(getCountParameter1.StoreType);
Assert.Equal(getCountParameter1.StoreType, ((IReadOnlyDbFunctionParameter)getCountParameter1).StoreType);
Assert.True(getCountParameter1.PropagatesNullability);
Assert.Equal(typeof(Guid?), getCountParameter1.ClrType);
Assert.Equal(getCountParameter1.StoreType, getCountParameter1.TypeMapping!.StoreType);
Assert.Single(getCountParameter1.GetAnnotations());
Assert.Equal(new[] { 1L }, getCountParameter1["MyAnnotation"]);
Assert.Equal("id", getCountParameter1.StoreFunctionParameter.Name);
Assert.Equal(getCountParameter1.StoreType, getCountParameter1.StoreFunctionParameter.StoreType);
Assert.NotNull(getCountParameter1.ToString());
var getCountParameter2 = getCount.Parameters[1];
Assert.Same(getCount, getCountParameter2.Function);
Assert.Equal("condition", getCountParameter2.Name);
Assert.NotNull(getCountParameter2.StoreType);
Assert.False(getCountParameter2.PropagatesNullability);
Assert.Equal(typeof(string), getCountParameter2.ClrType);
Assert.Equal(getCountParameter2.StoreType, getCountParameter2.TypeMapping!.StoreType);
Assert.Equal("condition", getCountParameter2.StoreFunctionParameter.Name);
Assert.Equal(getCountParameter2.StoreType, getCountParameter2.StoreFunctionParameter.StoreType);
Assert.NotNull(getCountParameter2.ToString());
var isDate = model.FindDbFunction(typeof(DbFunctionContext).GetMethod("IsDateStatic")!)!;
Assert.Equal("IsDate", isDate.Name);
Assert.Null(isDate.Schema);
Assert.Equal(typeof(DbFunctionContext).FullName + ".IsDateStatic(string)", isDate.ModelName);
Assert.True(isDate.IsNullable);
Assert.True(isDate.IsScalar);
Assert.True(isDate.IsBuiltIn);
Assert.False(isDate.IsAggregate);
Assert.Null(isDate.Translation);
Assert.Equal(typeof(bool), isDate.ReturnType);
Assert.Equal("IsDateStatic", isDate.MethodInfo!.Name);
Assert.Single(isDate.GetAnnotations());
Assert.Equal(new Guid(), isDate["MyGuid"]);
Assert.Empty(isDate.GetRuntimeAnnotations());
Assert.NotNull(isDate.StoreFunction.ReturnType);
Assert.Empty(isDate.StoreFunction.EntityTypeMappings);
Assert.Single(isDate.Parameters);
var isDateParameter = isDate.Parameters[0];
Assert.Same(isDate, isDateParameter.Function);
Assert.Equal("date", isDateParameter.Name);
Assert.NotNull(isDateParameter.StoreType);
Assert.False(isDateParameter.PropagatesNullability);
Assert.Equal(typeof(string), isDateParameter.ClrType);
Assert.Equal(isDateParameter.StoreType, isDateParameter.TypeMapping!.StoreType);
Assert.Equal("date", isDateParameter.StoreFunctionParameter.Name);
Assert.Equal(isDateParameter.StoreType, isDateParameter.StoreFunctionParameter.StoreType);
var getData = model.FindDbFunction(
typeof(DbFunctionContext)
.GetMethod("GetData", [typeof(int)])!)!;
Assert.Equal("GetData", getData.Name);
//Assert.Equal("dbo", getData.Schema);
Assert.Equal(typeof(DbFunctionContext).FullName + ".GetData(int)", getData.ModelName);
Assert.False(getData.IsNullable);
Assert.False(getData.IsScalar);
Assert.False(getData.IsBuiltIn);
Assert.False(getData.IsAggregate);
Assert.Null(getData.Translation);
Assert.Equal(typeof(IQueryable<Data>), getData.ReturnType);
Assert.Equal("GetData", getData.MethodInfo!.Name);
Assert.Empty(getData.GetAnnotations());
Assert.Empty(getData.GetRuntimeAnnotations());
Assert.Null(getData.TypeMapping?.StoreType);
Assert.Null(getData.StoreFunction.ReturnType);
Assert.Equal(typeof(Data), getData.StoreFunction.EntityTypeMappings.Single().TypeBase.ClrType);
Assert.Single(getData.Parameters);
var getDataParameter = getData.Parameters[0];
Assert.Same(getData, getDataParameter.Function);
Assert.Equal("id", getDataParameter.Name);
Assert.NotNull(getDataParameter.StoreType);
Assert.False(getDataParameter.PropagatesNullability);
Assert.Equal(typeof(int), getDataParameter.ClrType);
Assert.Equal(getDataParameter.StoreType, getDataParameter.TypeMapping!.StoreType);
Assert.Equal("id", getDataParameter.StoreFunctionParameter.Name);
Assert.Equal(getDataParameter.StoreType, getDataParameter.StoreFunctionParameter.StoreType);
var getDataParameterless = model.FindDbFunction(
typeof(DbFunctionContext).GetMethod("GetData", [])!)!;
Assert.Equal("GetAllData", getDataParameterless.Name);
//Assert.Equal("dbo", getDataParameterless.Schema);
Assert.Equal(typeof(DbFunctionContext).FullName + ".GetData()", getDataParameterless.ModelName);
Assert.False(getDataParameterless.IsNullable);
Assert.False(getDataParameterless.IsScalar);
Assert.False(getDataParameterless.IsBuiltIn);
Assert.False(getDataParameterless.IsAggregate);
Assert.Null(getDataParameterless.Translation);
Assert.Equal(typeof(IQueryable<Data>), getDataParameterless.ReturnType);
Assert.Equal("GetData", getDataParameterless.MethodInfo!.Name);
Assert.Empty(getDataParameterless.GetAnnotations());
Assert.Empty(getDataParameterless.GetRuntimeAnnotations());
Assert.False(getDataParameterless.StoreFunction.IsBuiltIn);
Assert.Equal(typeof(Data), getDataParameterless.StoreFunction.EntityTypeMappings.Single().TypeBase.ClrType);
Assert.Equal(0, getDataParameterless.Parameters.Count);
Assert.Equal(2, model.GetEntityTypes().Count());
var dataEntity = model.FindEntityType(typeof(Data))!;
Assert.Null(dataEntity.FindPrimaryKey());
var dataEntityFunctionMapping = dataEntity.GetFunctionMappings().Single(m => m.IsDefaultFunctionMapping);
Assert.Null(dataEntityFunctionMapping.IncludesDerivedTypes);
Assert.Null(dataEntityFunctionMapping.IsSharedTablePrincipal);
Assert.Null(dataEntityFunctionMapping.IsSplitEntityTypePrincipal);
Assert.Same(getDataParameterless, dataEntityFunctionMapping.DbFunction);
var getDataStoreFunction = dataEntityFunctionMapping.StoreFunction;
Assert.Same(getDataParameterless, getDataStoreFunction.DbFunctions.Single());
Assert.False(getDataStoreFunction.IsOptional(dataEntity));
var dataEntityOtherFunctionMapping = dataEntity.GetFunctionMappings().Single(m => !m.IsDefaultFunctionMapping);
Assert.Null(dataEntityOtherFunctionMapping.IncludesDerivedTypes);
Assert.Null(dataEntityOtherFunctionMapping.IsSharedTablePrincipal);
Assert.Null(dataEntityOtherFunctionMapping.IsSplitEntityTypePrincipal);
Assert.Same(getData, dataEntityOtherFunctionMapping.DbFunction);
var getDataOtherStoreFunction = dataEntityOtherFunctionMapping.StoreFunction;
Assert.Same(getData, getDataOtherStoreFunction.DbFunctions.Single());
Assert.False(getDataOtherStoreFunction.IsOptional(dataEntity));
var getBlobs = model.FindDbFunction("GetBlobs()")!;
//Assert.Equal("dbo", getBlobs.Schema);
Assert.False(getBlobs.IsNullable);
Assert.False(getBlobs.IsScalar);
Assert.False(getBlobs.IsBuiltIn);
Assert.False(getBlobs.IsAggregate);
Assert.Null(getBlobs.Translation);
Assert.Null(getBlobs.TypeMapping);
Assert.Equal(typeof(IQueryable<object>), getBlobs.ReturnType);
Assert.Null(getBlobs.MethodInfo);
Assert.Empty(getBlobs.GetAnnotations());
Assert.Empty(getBlobs.GetRuntimeAnnotations());
Assert.Equal("GetBlobs", getBlobs.StoreFunction.Name);
Assert.False(getBlobs.StoreFunction.IsShared);
Assert.NotNull(getBlobs.ToString());
Assert.Empty(getBlobs.Parameters);
var objectEntity = model.FindEntityType(typeof(object))!;
Assert.Null(objectEntity.FindPrimaryKey());
var objectEntityFunctionMapping = objectEntity.GetFunctionMappings().Single(m => m.IsDefaultFunctionMapping);
Assert.Null(objectEntityFunctionMapping.IncludesDerivedTypes);
Assert.Null(objectEntityFunctionMapping.IsSharedTablePrincipal);
Assert.Null(objectEntityFunctionMapping.IsSplitEntityTypePrincipal);
Assert.Same(getBlobs, objectEntityFunctionMapping.DbFunction);
});
| CompiledModelRelationalTestBase |
csharp | abpframework__abp | framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Templates/Microservice/UpdateDockerImagesStep.cs | {
"start": 209,
"end": 831
} | public class ____ : ProjectBuildPipelineStep
{
private readonly string _ymlFilePath;
public UpdateDockerImagesStep(string ymlFilePath)
{
_ymlFilePath = ymlFilePath;
}
public override void Execute(ProjectBuildContext context)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && RuntimeInformation.OSArchitecture == Architecture.Arm64)
{
var file = context.Files.FirstOrDefault(f => f.Name == _ymlFilePath);
file?.ReplaceText("mcr.microsoft.com/mssql/server:2019-latest", "mcr.microsoft.com/azure-sql-edge");
}
}
}
| UpdateDockerImagesStep |
csharp | Cysharp__ZLogger | sandbox/GeneratorSandbox/GeneratedMock.cs | {
"start": 263,
"end": 1636
} | partial class ____
{
// [ZLoggerMessage(Information, "Could not open socket to {hostName} {ipAddress}.")]
public static void CouldNotOpenSocket(this ILogger<FooBarBaz> logger, string hostName, int ipAddress)
{
if (!logger.IsEnabled(LogLevel.Information)) return;
logger.Log(LogLevel.Information, -1, new CouldNotOpenSocketState(hostName, ipAddress), null, (state, ex) => state.ToString());
}
public static void CouldNotOpenSocket2(this ILogger<FooBarBaz> logger, string hostName, int ipAddress, Exception exception)
{
if (!logger.IsEnabled(LogLevel.Information)) return;
logger.Log(LogLevel.Information, -1, new CouldNotOpenSocketState(hostName, ipAddress), exception, (state, ex) => state.ToString());
}
public static void CouldNotOpenSocketWithCaller(this ILogger<FooBarBaz> logger, string hostName, int ipAddress, [CallerLineNumber] int lineNumber = 0)
{
if (!logger.IsEnabled(LogLevel.Information)) return;
logger.Log(LogLevel.Information, -1, new CouldNotOpenSocketState(hostName, ipAddress, lineNumber), null, (state, ex) => state.ToString());
}
[ZLoggerMessage(LogLevel.Information, "Could not open socket to {hostName} {ipAddress}.")]
public static partial void CouldNotOpenSocket3(this ILogger<FooBarBaz> logger, string hostName, int ipAddress);
}
file readonly | Log22 |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryCrudModels.cs | {
"start": 12556,
"end": 13136
} | public class ____ : ICreateDb<RockstarAuto>, IReturn<RockstarWithIdAndResultResponse>
{
public string FirstName { get; set; }
public string LastName { get; set; }
[AutoDefault(Value = 21)]
public int? Age { get; set; }
[AutoDefault(Expression = "date(2001,1,1)")]
public DateTime DateOfBirth { get; set; }
[AutoDefault(Eval = "utcNow")]
public DateTime? DateDied { get; set; }
[AutoDefault(Value = global::ServiceStack.WebHost.Endpoints.Tests.LivingStatus.Dead)]
public LivingStatus? LivingStatus { get; set; }
}
| CreateRockstarAdhocNonDefaults |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/Configuration/Extensions/IOutputCacheInvalidationObserverSettingExtensions.cs | {
"start": 434,
"end": 684
} | class ____ be observed by the framework. If any setting property
/// of <typeparamref name="TSetting"/> changes, the framework will purge the cache.
/// </summary>
/// <typeparam name="TSetting">The type of the concrete setting | to |
csharp | microsoft__semantic-kernel | dotnet/src/Agents/Orchestration/Handoff/HandoffMessages.cs | {
"start": 1260,
"end": 1964
} | public sealed class ____
{
/// <summary>
/// The chat response message.
/// </summary>
public ChatMessageContent Message { get; init; } = Empty;
}
/// <summary>
/// Extension method to convert a <see cref="ChatMessageContent"/> to a <see cref="Result"/>.
/// </summary>
public static InputTask AsInputTaskMessage(this IEnumerable<ChatMessageContent> messages) => new() { Messages = [.. messages] };
/// <summary>
/// Extension method to convert a <see cref="ChatMessageContent"/> to a <see cref="Result"/>.
/// </summary>
public static Result AsResultMessage(this ChatMessageContent message) => new() { Message = message };
}
| Response |
csharp | dotnet__aspnetcore | src/Security/Authentication/Google/src/GoogleExtensions.cs | {
"start": 378,
"end": 4081
} | public static class ____
{
/// <summary>
/// Adds Google OAuth-based authentication to <see cref="AuthenticationBuilder"/> using the default scheme.
/// The default scheme is specified by <see cref="GoogleDefaults.AuthenticationScheme"/>.
/// <para>
/// Google authentication allows application users to sign in with their Google account.
/// </para>
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddGoogle(this AuthenticationBuilder builder)
=> builder.AddGoogle(GoogleDefaults.AuthenticationScheme, _ => { });
/// <summary>
/// Adds Google OAuth-based authentication to <see cref="AuthenticationBuilder"/> using the default scheme.
/// The default scheme is specified by <see cref="GoogleDefaults.AuthenticationScheme"/>.
/// <para>
/// Google authentication allows application users to sign in with their Google account.
/// </para>
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="configureOptions">A delegate to configure <see cref="GoogleOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddGoogle(this AuthenticationBuilder builder, Action<GoogleOptions> configureOptions)
=> builder.AddGoogle(GoogleDefaults.AuthenticationScheme, configureOptions);
/// <summary>
/// Adds Google OAuth-based authentication to <see cref="AuthenticationBuilder"/> using the default scheme.
/// The default scheme is specified by <see cref="GoogleDefaults.AuthenticationScheme"/>.
/// <para>
/// Google authentication allows application users to sign in with their Google account.
/// </para>
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="authenticationScheme">The authentication scheme.</param>
/// <param name="configureOptions">A delegate to configure <see cref="GoogleOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddGoogle(this AuthenticationBuilder builder, string authenticationScheme, Action<GoogleOptions> configureOptions)
=> builder.AddGoogle(authenticationScheme, GoogleDefaults.DisplayName, configureOptions);
/// <summary>
/// Adds Google OAuth-based authentication to <see cref="AuthenticationBuilder"/> using the default scheme.
/// The default scheme is specified by <see cref="GoogleDefaults.AuthenticationScheme"/>.
/// <para>
/// Google authentication allows application users to sign in with their Google account.
/// </para>
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="authenticationScheme">The authentication scheme.</param>
/// <param name="displayName">A display name for the authentication handler.</param>
/// <param name="configureOptions">A delegate to configure <see cref="GoogleOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddGoogle(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<GoogleOptions> configureOptions)
=> builder.AddOAuth<GoogleOptions, GoogleHandler>(authenticationScheme, displayName, configureOptions);
}
| GoogleExtensions |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/UserManagementService/user_management_service.cs | {
"start": 5503,
"end": 6684
} | public class ____<TLogFormat, TStreamId> : TestFixtureWithUserManagementService<TLogFormat, TStreamId> {
protected override IEnumerable<WhenStep> When() {
yield return
new UserManagementMessage.Create(
Envelope, _ordinaryUser, "user1", "John Doe", new[] { "admin", "other" }, "Johny123!");
}
[Test]
public void replies_unauthorized() {
var updateResults = HandledMessages.OfType<UserManagementMessage.UpdateResult>().ToList();
Assert.AreEqual(1, updateResults.Count);
Assert.IsFalse(updateResults[0].Success);
Assert.AreEqual(UserManagementMessage.Error.Unauthorized, updateResults[0].Error);
}
[Test]
public void does_not_create_a_user_account() {
_users.Handle(new UserManagementMessage.Get(Envelope, SystemAccounts.System, "user1"));
_queue.Process();
var user = HandledMessages.OfType<UserManagementMessage.UserDetailsResult>().SingleOrDefault();
Assert.NotNull(user);
Assert.IsFalse(user.Success);
Assert.AreEqual(UserManagementMessage.Error.NotFound, user.Error);
}
}
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
| when_ordinary_user_attempts_to_create_a_user |
csharp | smartstore__Smartstore | src/Smartstore.Web.Common/TagHelpers/Shared/Media/CoverImageTagHelper.cs | {
"start": 1304,
"end": 6680
} | public class ____ : ImageTagHelper
{
const string PositionAttributeName = "sm-position";
const string EditUrlAttributeName = "sm-edit-url";
/// <summary>
/// Specifies the position of the image inside its content box. Empty by default (image is centered).
/// See "object-position" CSS for valid values.
/// </summary>
[HtmlAttributeName(PositionAttributeName)]
public string ImagePosition { get; set; }
/// <summary>
/// Specifies the URL that will be used to save the updated image position.
/// </summary>
[HtmlAttributeName(EditUrlAttributeName)]
public string EditUrl { get; set; }
protected override void ProcessMedia(TagHelperContext context, TagHelperOutput output)
{
if (Src.IsEmpty())
{
output.SuppressOutput();
return;
}
var workContext = ViewContext.HttpContext.GetServiceScope().Resolve<IWorkContext>();
var customer = workContext.CurrentCustomer;
base.ProcessMedia(context, output);
// Image.
output.TagName = "img";
output.RemoveClass("file-img", HtmlEncoder.Default);
// Only images with horizontal orientation supported yet (100% width, fixed height).
output.AppendCssClass("img-fluid horizontal-image media-edit-object");
if (ImagePosition.HasValue())
{
output.AddCssStyle("object-position", ImagePosition);
}
// Image container.
var figure = new TagBuilder("figure");
figure.AddCssClass("cover-image-container");
if (EditUrl.HasValue() && customer.IsAdmin())
{
var id = "media-edit-" + CommonHelper.GenerateRandomDigitCode(8);
figure.Attributes["id"] = id;
var widgetProvider = ViewContext.HttpContext.RequestServices.GetRequiredService<IWidgetProvider>();
var dropdown = CreateDropdown(id);
widgetProvider.RegisterHtml("admin_actions", dropdown);
}
var caption = Alt ?? Title;
if (caption.HasValue())
{
var figCaption = new TagBuilder("figcaption");
figCaption.Attributes["class"] = "sr-only";
figCaption.InnerHtml.AppendHtml(caption);
figure.InnerHtml.AppendHtml(figCaption);
}
// Order: First the image then the dropdown.
output.WrapElementWith(InnerHtmlPosition.Append, figure);
}
protected virtual TagBuilder CreateDropdown(string id)
{
var toggle = new TagBuilder("a");
toggle.Attributes["href"] = "javascript:;";
toggle.Attributes["class"] = "btn btn-sm btn-secondary btn-icon rounded-circle no-chevron dropdown-toggle cover-image-dropdown";
toggle.Attributes["title"] = T("Admin.Media.Editing.Align");
toggle.Attributes["data-toggle"] = "dropdown";
toggle.Attributes["data-placement"] = "top";
var icon = new HtmlString("<i class=\"fa fa-arrow-down-up-across-line\"></i>");
toggle.InnerHtml.AppendHtml(icon);
var dropdownUl = new TagBuilder("ul");
dropdownUl.Attributes["class"] = "dropdown-menu dropdown-menu-check dropdown-menu-right media-edit-dropdown";
dropdownUl.InnerHtml.AppendHtml(CreateDropdownItem("center top", "Admin.Media.Editing.AlignTop", "fa-long-arrow-up"));
dropdownUl.InnerHtml.AppendHtml(CreateDropdownItem(string.Empty, "Admin.Media.Editing.AlignMiddle", "fa-arrows-v"));
dropdownUl.InnerHtml.AppendHtml(CreateDropdownItem("center bottom", "Admin.Media.Editing.AlignBottom", "fa-long-arrow-down"));
var rootDiv = new TagBuilder("div");
rootDiv.Attributes["data-media-edit-url"] = EditUrl;
rootDiv.Attributes["data-media-edit-id"] = id;
rootDiv.Attributes["class"] = "cover-image-dropdown-root";
rootDiv.InnerHtml.AppendHtml(toggle);
rootDiv.InnerHtml.AppendHtml(dropdownUl);
return rootDiv;
}
protected virtual TagBuilder CreateDropdownItem(string position, string resourceKey, string iconName = null)
{
var model = new MediaEditModel
{
Commands =
[
new() { Name = "object-position", Value = position }
]
};
var a = new TagBuilder("a");
a.Attributes["href"] = "#";
a.Attributes["class"] = "dropdown-item media-edit-command";
a.Attributes["role"] = "button";
a.Attributes["data-media-edit"] = model.ToJson();
if (position.EqualsNoCase(ImagePosition))
{
a.AppendCssClass("checked");
a.Attributes["aria-pressed"] = "true";
}
a.InnerHtml.AppendHtml(iconName.HasValue()
? $"<i class=\"fa fa-fw {iconName}\"></i><span>{T(resourceKey)}</span>"
: T(resourceKey).Value);
var li = new TagBuilder("li");
li.InnerHtml.AppendHtml(a);
return li;
}
}
}
| CoverImageTagHelper |
csharp | restsharp__RestSharp | test/RestSharp.Tests.Serializers.Xml/SampleClasses/ListSamples.cs | {
"start": 665,
"end": 764
} | public class ____ {
public string Src { get; set; }
public string Value { get; set; }
}
| Image |
csharp | dotnet__maui | src/TestUtils/src/UITest.Appium/AppiumQuery.cs | {
"start": 137,
"end": 5812
} | public class ____ : IQuery
{
const string ClassToken = "class";
const string IdToken = "id";
const string NameToken = "name";
const string AccessibilityToken = "accessibilityid";
const string XPathToken = "xpath";
const string QuerySeparatorToken = "&";
const string IdQuery = IdToken + "={0}";
const string NameQuery = NameToken + "={0}";
const string AccessibilityQuery = AccessibilityToken + "={0}";
const string ClassQuery = ClassToken + "={0}";
const string XPathQuery = XPathToken + "={0}";
readonly string _queryStr;
public AppiumQuery(string queryStr)
{
_queryStr = queryStr;
}
public AppiumQuery(AppiumQuery query, string queryStr)
{
_queryStr = string.Join(query._queryStr, QuerySeparatorToken, queryStr);
}
IQuery IQuery.ByClass(string classQuery)
{
return new AppiumQuery(this, string.Format(ClassQuery, classQuery));
}
IQuery IQuery.ById(string id)
{
return new AppiumQuery(this, string.Format(IdQuery, id));
}
IQuery IQuery.ByAccessibilityId(string id)
{
return new AppiumQuery(this, string.Format(AccessibilityQuery, id));
}
IQuery IQuery.ByName(string nameQuery)
{
return new AppiumQuery(this, string.Format(NameQuery, nameQuery));
}
IQuery IQuery.ByXPath(string xpath)
{
return new AppiumQuery(this, string.Format(XPathQuery, Uri.EscapeDataString(xpath)));
}
public static AppiumQuery ById(string id)
{
return new AppiumQuery(string.Format(IdQuery, id));
}
public static AppiumQuery ByName(string nameQuery)
{
return new AppiumQuery(string.Format(NameQuery, nameQuery));
}
public static AppiumQuery ByAccessibilityId(string id)
{
return new AppiumQuery(string.Format(AccessibilityQuery, id));
}
public static AppiumQuery ByClass(string classQuery)
{
return new AppiumQuery(string.Format(ClassQuery, classQuery));
}
public static AppiumQuery ByXPath(string xpath)
{
return new AppiumQuery(string.Format(XPathQuery, Uri.EscapeDataString(xpath)));
}
#nullable disable
public IUIElement FindElement(AppiumApp appiumApp)
{
// e.g. class=button&id=MyButton
string[] querySplit = _queryStr.Split(QuerySeparatorToken);
string queryStr = querySplit[0];
string[] argSplit = queryStr.Split('=');
if (argSplit.Length != 2)
{
throw new ArgumentException("Invalid Query");
}
var queryBy = GetQueryBy(argSplit[0], argSplit[1]);
var foundElement = appiumApp.Driver.FindElements(queryBy).FirstOrDefault();
if (foundElement == null)
{
return null;
}
for (int i = 1; i < querySplit.Length; i++)
{
foundElement = FindElement(foundElement, querySplit[i]);
}
return new AppiumDriverElement(foundElement, appiumApp);
}
public IReadOnlyCollection<IUIElement> FindElements(AppiumApp appiumApp)
{
// e.g. class=button&id=MyButton
string[] querySplit = _queryStr.Split(QuerySeparatorToken);
string queryStr = querySplit[0];
string[] argSplit = queryStr.Split('=');
if (argSplit.Length != 2)
{
throw new ArgumentException("Invalid Query");
}
var queryBy = GetQueryBy(argSplit[0], argSplit[1]);
var foundElements = appiumApp.Driver.FindElements(queryBy);
// TODO: What is the expected way to handle multiple queries when multiple elements are returned?
//for(int i = 1; i < querySplit.Length; i++)
//{
// foundElement = FindElement(foundElement, querySplit[i]);
//}
return foundElements.Select(e => new AppiumDriverElement(e, appiumApp)).ToList();
}
#nullable enable
public IReadOnlyCollection<IUIElement> FindElements(AppiumElement element, AppiumApp appiumApp)
{
string[] querySplit = _queryStr.Split(QuerySeparatorToken);
AppiumElement appiumElement = element;
string queryStr = querySplit[0];
string[] argSplit = queryStr.Split('=');
var queryBy = GetQueryBy(argSplit[0], argSplit[1]);
var foundElements = element.FindElements(queryBy);
//for (int i = 0; i < querySplit.Length; i++)
//{
// appiumElement = FindElement(appiumElement, querySplit[i]);
//}
return foundElements.Select(e => new AppiumDriverElement((AppiumElement)e, appiumApp)).ToList();
}
public IUIElement FindElement(AppiumElement element, AppiumApp appiumApp)
{
string[] querySplit = _queryStr.Split(QuerySeparatorToken);
AppiumElement appiumElement = element;
for (int i = 0; i < querySplit.Length; i++)
{
appiumElement = FindElement(appiumElement, querySplit[i]);
}
return new AppiumDriverElement(appiumElement, appiumApp);
}
private static IReadOnlyCollection<AppiumElement> FindElements(AppiumElement element, string query)
{
var argSplit = query.Split('=');
if (argSplit.Length != 2)
{
throw new ArgumentException("Invalid Query");
}
var queryBy = GetQueryBy(argSplit[0], argSplit[1]);
return element.FindElements(queryBy).Select(e => (AppiumElement)e).ToList();
}
private static AppiumElement FindElement(AppiumElement element, string query)
{
var argSplit = query.Split('=');
if (argSplit.Length != 2)
{
throw new ArgumentException("Invalid Query");
}
var queryBy = GetQueryBy(argSplit[0], argSplit[1]);
return (AppiumElement)element.FindElement(queryBy);
}
private static By GetQueryBy(string token, string value)
{
return token.ToLowerInvariant() switch
{
ClassToken => MobileBy.ClassName(value),
NameToken => MobileBy.Name(value),
AccessibilityToken => MobileBy.AccessibilityId(value),
IdToken => MobileBy.Id(value),
XPathToken => MobileBy.XPath(Uri.UnescapeDataString(value)),
_ => throw new ArgumentException("Unknown query type"),
};
}
}
}
| AppiumQuery |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/SwipeControlTests/SwipeControl_ScrollViewer.xaml.cs | {
"start": 557,
"end": 1293
} | partial class ____ : Page
{
public SwipeControl_ScrollViewer()
{
this.InitializeComponent();
TheSecondSUT.ItemsSource = new[]
{
"#FFFF0018",
"#FFFFA52C",
"#FFFFFF41",
"#FF008018",
"#FF0000F9",
"#FF86007D",
"#CCFF0018",
"#CCFFA52C",
"#CCFFFF41",
"#CC008018",
"#CC0000F9",
"#CC86007D",
"#66FF0018",
"#66FFA52C",
"#66FFFF41",
"#66008018",
"#660000F9",
"#6686007D",
"#33FF0018",
"#33FFA52C",
"#33FFFF41",
"#33008018",
"#330000F9",
"#3386007D"
};
}
private void ItemInvoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
{
Output.Text = args.SwipeControl.DataContext?.ToString();
}
}
}
| SwipeControl_ScrollViewer |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/Metadata/ReferenceLoadInfo.cs | {
"start": 1225,
"end": 2960
} | public class ____
{
readonly Dictionary<string, UnresolvedAssemblyNameReference> loadedAssemblyReferences = new Dictionary<string, UnresolvedAssemblyNameReference>();
public void AddMessage(string fullName, MessageKind kind, string message)
{
lock (loadedAssemblyReferences)
{
if (!loadedAssemblyReferences.TryGetValue(fullName, out var referenceInfo))
{
referenceInfo = new UnresolvedAssemblyNameReference(fullName);
loadedAssemblyReferences.Add(fullName, referenceInfo);
}
referenceInfo.Messages.Add((kind, message));
}
}
public void AddMessageOnce(string fullName, MessageKind kind, string message)
{
lock (loadedAssemblyReferences)
{
if (!loadedAssemblyReferences.TryGetValue(fullName, out var referenceInfo))
{
referenceInfo = new UnresolvedAssemblyNameReference(fullName);
loadedAssemblyReferences.Add(fullName, referenceInfo);
referenceInfo.Messages.Add((kind, message));
}
else
{
var lastMsg = referenceInfo.Messages.LastOrDefault();
if (kind != lastMsg.Item1 && message != lastMsg.Item2)
referenceInfo.Messages.Add((kind, message));
}
}
}
public bool TryGetInfo(string fullName, out UnresolvedAssemblyNameReference info)
{
lock (loadedAssemblyReferences)
{
return loadedAssemblyReferences.TryGetValue(fullName, out info);
}
}
public IReadOnlyList<UnresolvedAssemblyNameReference> Entries {
get {
lock (loadedAssemblyReferences)
{
return loadedAssemblyReferences.Values.ToList();
}
}
}
public bool HasErrors {
get {
lock (loadedAssemblyReferences)
{
return loadedAssemblyReferences.Any(i => i.Value.HasErrors);
}
}
}
}
}
| ReferenceLoadInfo |
csharp | unoplatform__uno | src/Uno.UI.Tests/DependencyProperty/Given_DependencyProperty.ManualPropagation.cs | {
"start": 8598,
"end": 9451
} | public partial class ____ : DependencyObject
{
public MyObject()
{
}
#region SubObject DependencyProperty
public SubObject SubObject
{
get { return (SubObject)GetValue(SubObjectProperty); }
set { SetValue(SubObjectProperty, value); }
}
// Using a DependencyProperty as the backing store for SubObject. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SubObjectProperty =
DependencyProperty.Register(
"SubObject",
typeof(SubObject),
typeof(MyObject),
new FrameworkPropertyMetadata(
defaultValue: null,
options: FrameworkPropertyMetadataOptions.LogicalChild,
propertyChangedCallback: (s, e) => ((MyObject)s)?.OnSubObjectChanged(e)
)
);
private void OnSubObjectChanged(DependencyPropertyChangedEventArgs e)
{
}
#endregion
}
| MyObject |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bundling/Volo/Abp/AspNetCore/Mvc/UI/Bundling/TagHelpers/IBundleItemTagHelper.cs | {
"start": 60,
"end": 174
} | public interface ____ : IBundleTagHelper
{
BundleTagHelperItem CreateBundleTagHelperItem();
}
| IBundleItemTagHelper |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Tests/Types/Validation/InterfaceHasAtLeastOneImplementationRuleTests.cs | {
"start": 311,
"end": 553
} | interface ____ {string: String}
");
}
[Fact]
public void AcceptInterfaceWithOneImplementor()
{
ExpectValid(@"
type Query { stub: Foo }
type Bar implements Foo { string: String }
| Foo |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/IContentFieldHandler.cs | {
"start": 164,
"end": 2454
} | public interface ____
{
Task ActivatedAsync(ActivatedContentFieldContext context, ContentField field);
Task ActivatingAsync(ActivatingContentFieldContext context, ContentField field);
Task InitializingAsync(InitializingContentFieldContext context, ContentField field);
Task InitializedAsync(InitializingContentFieldContext context, ContentField field);
Task CreatingAsync(CreateContentFieldContext context, ContentField field);
Task CreatedAsync(CreateContentFieldContext context, ContentField field);
Task LoadingAsync(LoadContentFieldContext context, ContentField field);
Task LoadedAsync(LoadContentFieldContext context, ContentField field);
Task ImportingAsync(ImportContentFieldContext context, ContentField field);
Task ImportedAsync(ImportContentFieldContext context, ContentField field);
Task UpdatingAsync(UpdateContentFieldContext context, ContentField field);
Task UpdatedAsync(UpdateContentFieldContext context, ContentField field);
Task ValidatingAsync(ValidateContentFieldContext context, ContentField field);
Task ValidatedAsync(ValidateContentFieldContext context, ContentField field);
Task VersioningAsync(VersionContentFieldContext context, ContentField existing, ContentField building);
Task VersionedAsync(VersionContentFieldContext context, ContentField existing, ContentField building);
Task DraftSavingAsync(SaveDraftContentFieldContext context, ContentField field);
Task DraftSavedAsync(SaveDraftContentFieldContext context, ContentField field);
Task PublishingAsync(PublishContentFieldContext context, ContentField field);
Task PublishedAsync(PublishContentFieldContext context, ContentField field);
Task UnpublishingAsync(PublishContentFieldContext context, ContentField field);
Task UnpublishedAsync(PublishContentFieldContext context, ContentField field);
Task RemovingAsync(RemoveContentFieldContext context, ContentField field);
Task RemovedAsync(RemoveContentFieldContext context, ContentField field);
Task GetContentItemAspectAsync(ContentItemAspectContext context, ContentField field);
Task CloningAsync(CloneContentFieldContext context, ContentField field);
Task ClonedAsync(CloneContentFieldContext context, ContentField field);
}
| IContentFieldHandler |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ScriptTests/SharpPagesIntegrationTests.cs | {
"start": 1727,
"end": 1879
} | public class ____ : SharpCodePage
{
string render() => @"<h1>Shadowed Index Code Page</h1>";
}
[Page("rockstar")]
| ShadowedIndexPage |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/CommandBar/CommandBarElementCollection.Partial.h.cs | {
"start": 362,
"end": 549
} | internal partial class ____ : IObservableVector<ICommandBarElement>, IVector<ICommandBarElement>
{
bool m_notifyCollectionChanging;
CommandBar? m_parent;
}
}
| CommandBarElementCollection |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition/CompositionScopedBatch.cs | {
"start": 297,
"end": 4464
} | public partial class ____ : global::Windows.UI.Composition.CompositionObject
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal CompositionScopedBatch()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsActive
{
get
{
throw new global::System.NotImplementedException("The member bool CompositionScopedBatch.IsActive is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20CompositionScopedBatch.IsActive");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsEnded
{
get
{
throw new global::System.NotImplementedException("The member bool CompositionScopedBatch.IsEnded is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20CompositionScopedBatch.IsEnded");
}
}
#endif
// Forced skipping of method Windows.UI.Composition.CompositionScopedBatch.IsActive.get
// Forced skipping of method Windows.UI.Composition.CompositionScopedBatch.IsEnded.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void End()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionScopedBatch", "void CompositionScopedBatch.End()");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void Resume()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionScopedBatch", "void CompositionScopedBatch.Resume()");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void Suspend()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionScopedBatch", "void CompositionScopedBatch.Suspend()");
}
#endif
// Forced skipping of method Windows.UI.Composition.CompositionScopedBatch.Completed.add
// Forced skipping of method Windows.UI.Composition.CompositionScopedBatch.Completed.remove
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Composition.CompositionBatchCompletedEventArgs> Completed
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionScopedBatch", "event TypedEventHandler<object, CompositionBatchCompletedEventArgs> CompositionScopedBatch.Completed");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionScopedBatch", "event TypedEventHandler<object, CompositionBatchCompletedEventArgs> CompositionScopedBatch.Completed");
}
}
#endif
}
}
| CompositionScopedBatch |
csharp | abpframework__abp | framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Version/PackageVersionCheckerService.cs | {
"start": 9757,
"end": 9917
} | public class ____
{
public int TotalHits { get; set; }
public NuGetSearchResultPackagesDto[] Data { get; set; }
}
| NuGetSearchResultDto |
csharp | dotnet__aspnetcore | src/Analyzers/Microsoft.AspNetCore.Analyzer.Testing/src/DiagnosticVerifier.cs | {
"start": 733,
"end": 7584
} | public abstract class ____
{
private readonly ITestOutputHelper _testOutputHelper;
/// <inheritdoc />
protected DiagnosticVerifier() : this(null)
{
}
/// <inheritdoc />
protected DiagnosticVerifier(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
/// <summary>
/// File name prefix used to generate Documents instances from source.
/// </summary>
protected static string DefaultFilePathPrefix = "Test";
/// <summary>
/// Project name of
/// </summary>
protected static string TestProjectName = "TestProject";
protected Solution Solution { get; set; }
/// <summary>
/// Given classes in the form of strings, and an IDiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <param name="analyzer">The analyzer to be run on the sources</param>
/// <param name="additionalEnabledDiagnostics">Additional diagnostics to enable at Info level</param>
/// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
protected Task<Diagnostic[]> GetDiagnosticsAsync(string[] sources, DiagnosticAnalyzer analyzer, string[] additionalEnabledDiagnostics)
{
return GetDiagnosticsAsync(GetDocuments(sources), analyzer, additionalEnabledDiagnostics);
}
/// <summary>
/// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
/// The returned diagnostics are then ordered by location in the source document.
/// </summary>
/// <param name="documents">The Documents that the analyzer will be run on</param>
/// <param name="analyzer">The analyzer to run on the documents</param>
/// <param name="additionalEnabledDiagnostics">Additional diagnostics to enable at Info level</param>
/// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
protected async Task<Diagnostic[]> GetDiagnosticsAsync(Document[] documents, DiagnosticAnalyzer analyzer, string[] additionalEnabledDiagnostics)
{
var projects = new HashSet<Project>();
foreach (var document in documents)
{
projects.Add(document.Project);
}
var diagnostics = new List<Diagnostic>();
foreach (var project in projects)
{
var compilation = await project.GetCompilationAsync();
// Enable any additional diagnostics
var options = compilation.Options;
if (additionalEnabledDiagnostics.Length > 0)
{
options = compilation.Options
.WithSpecificDiagnosticOptions(
additionalEnabledDiagnostics.ToDictionary(s => s, s => ReportDiagnostic.Info));
}
var compilationWithAnalyzers = compilation
.WithOptions(options)
.WithAnalyzers(ImmutableArray.Create(analyzer));
var diags = await compilationWithAnalyzers.GetAllDiagnosticsAsync();
foreach (var diag in diags)
{
_testOutputHelper?.WriteLine("Diagnostics: " + diag);
}
Assert.DoesNotContain(diags, d => d.Id == "AD0001");
// Filter out non-error diagnostics not produced by our analyzer
// We want to KEEP errors because we might have written bad code. But sometimes we leave warnings in to make the
// test code more convenient
diags = diags.Where(d => d.Severity == DiagnosticSeverity.Error || analyzer.SupportedDiagnostics.Any(s => s.Id.Equals(d.Id))).ToImmutableArray();
foreach (var diag in diags)
{
if (diag.Location == Location.None || diag.Location.IsInMetadata)
{
diagnostics.Add(diag);
}
else
{
foreach (var document in documents)
{
var tree = await document.GetSyntaxTreeAsync();
if (tree == diag.Location.SourceTree)
{
diagnostics.Add(diag);
}
}
}
}
}
return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
}
/// <summary>
/// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <returns>An array of Documents produced from the sources.</returns>
private Document[] GetDocuments(string[] sources)
{
var project = CreateProject(sources);
var documents = project.Documents.ToArray();
Debug.Assert(sources.Length == documents.Length);
return documents;
}
/// <summary>
/// Create a project using the inputted strings as sources.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <returns>A Project created out of the Documents created from the source strings</returns>
protected Project CreateProject(params string[] sources)
{
var fileNamePrefix = DefaultFilePathPrefix;
var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
Solution = Solution ?? new AdhocWorkspace().CurrentSolution;
Solution = Solution.AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
foreach (var defaultCompileLibrary in DependencyContext.Load(GetType().Assembly).CompileLibraries)
{
foreach (var resolveReferencePath in defaultCompileLibrary.ResolveReferencePaths(new AppLocalResolver()))
{
Solution = Solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(resolveReferencePath));
}
}
var count = 0;
foreach (var source in sources)
{
var newFileName = fileNamePrefix + count;
_testOutputHelper?.WriteLine("Adding file: " + newFileName + Environment.NewLine + source);
var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
Solution = Solution.AddDocument(documentId, newFileName, SourceText.From(source));
count++;
}
return Solution.GetProject(projectId);
}
// Required to resolve compilation assemblies inside unit tests
| DiagnosticVerifier |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Concurrency/LocalScheduler.TimerQueue.cs | {
"start": 20457,
"end": 22337
} | private abstract class ____ : IComparable<WorkItem>, IDisposable
{
public readonly LocalScheduler Scheduler;
public readonly DateTimeOffset DueTime;
private SingleAssignmentDisposableValue _disposable;
private int _hasRun;
protected WorkItem(LocalScheduler scheduler, DateTimeOffset dueTime)
{
Scheduler = scheduler;
DueTime = dueTime;
_hasRun = 0;
}
public void Invoke(IScheduler scheduler)
{
//
// Protect against possible maltreatment of the scheduler queues or races in
// execution of a work item that got relocated across system clock changes.
// Under no circumstance whatsoever we should run work twice. The monitor's
// ref count should also be subject to this policy.
//
if (Interlocked.Exchange(ref _hasRun, 1) == 0)
{
try
{
if (!_disposable.IsDisposed)
{
_disposable.Disposable = InvokeCore(scheduler);
}
}
finally
{
SystemClock.Release();
}
}
}
protected abstract IDisposable InvokeCore(IScheduler scheduler);
public int CompareTo(WorkItem? other) => DueTime.CompareTo(other!.DueTime);
public void Dispose() => _disposable.Dispose();
}
/// <summary>
/// Represents a work item that closes over scheduler invocation state. Subtyping is
/// used to have a common type for the scheduler queues.
/// </summary>
| WorkItem |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.PaymentMomo/MomoSecurityHelper.cs | {
"start": 154,
"end": 734
} | public static class ____
{
public static string HashSHA256(string message, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyBytes))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
string hex = BitConverter.ToString(hashMessage);
hex = hex.Replace("-", "").ToLower();
return hex;
}
}
}
}
| MomoSecurityHelper |
csharp | SixLabors__Fonts | tests/SixLabors.Fonts.Tests/WriterExtensions.cs | {
"start": 350,
"end": 36546
} | internal static class ____
{
public static void WriteTableHeader(this BigEndianBinaryWriter writer, string tag, uint checksum, uint? offset, uint length)
{
// table header
// Record Type | Name | Description
// ------------|----------|---------------------------------------------------
// uint32 | tag | 4 - byte identifier.
// uint32 | checkSum | CheckSum for this table.
// Offset32 | offset | Offset from beginning of TrueType font file.
// uint32 | length | Length of this table.
writer.WriteUInt32(tag);
writer.WriteUInt32(checksum);
writer.WriteOffset32(offset);
writer.WriteUInt32(length);
}
public static void WriteTrueTypeFileHeader(
this BigEndianBinaryWriter writer,
ushort tableCount,
ushort searchRange,
ushort entrySelector,
ushort rangeShift)
// uint32 | sfntVersion 0x00010000 or 0x4F54544F('OTTO') — see below.
=> writer.WriteFileHeader(0x00010000, tableCount, searchRange, entrySelector, rangeShift);
public static void WriteTrueTypeFileHeader(this BigEndianBinaryWriter writer, params TableHeader[] headers)
// uint32 | sfntVersion 0x00010000 or 0x4F54544F('OTTO') — see below.
=> writer.WriteFileHeader(0x00010000, headers);
public static void WriteCffFileHeader(
this BigEndianBinaryWriter writer,
ushort tableCount,
ushort searchRange,
ushort entrySelector,
ushort rangeShift)
// uint32 | sfntVersion 0x00010000 or 0x4F54544F('OTTO') — see below.
=> writer.WriteFileHeader(0x4F54544F, tableCount, searchRange, entrySelector, rangeShift);
private static void WriteFileHeader(this BigEndianBinaryWriter writer, uint version, params TableHeader[] headers)
{
// file header
// Type Name | name | Description
// ----------|---------------|------------------------------
// uint32 | sfntVersion | 0x00010000 or 0x4F54544F('OTTO') — see below.
// uint16 | numTables | Number of tables.
// uint16 | searchRange | (Maximum power of 2 <= numTables) x 16.
// uint16 | entrySelector | Log2(maximum power of 2 <= numTables).
// uint16 | rangeShift | NumTables x 16 - searchRange.
writer.WriteUInt32(version);
writer.WriteUInt16((ushort)headers.Length);
writer.WriteUInt16(0);
writer.WriteUInt16(0);
writer.WriteUInt16(0);
int offset = 12;
offset += headers.Length * 16;
foreach (TableHeader h in headers)
{
writer.WriteTableHeader(h.Tag, h.CheckSum, (uint)offset, h.Length);
offset += (int)h.Length;
}
}
private static void WriteFileHeader(this BigEndianBinaryWriter writer, uint version, ushort tableCount, ushort searchRange, ushort entrySelector, ushort rangeShift)
{
// file header
// Type Name | name | Description
// ----------|---------------|------------------------------
// uint32 | sfntVersion | 0x00010000 or 0x4F54544F('OTTO') — see below.
// uint16 | numTables | Number of tables.
// uint16 | searchRange | (Maximum power of 2 <= numTables) x 16.
// uint16 | entrySelector | Log2(maximum power of 2 <= numTables).
// uint16 | rangeShift | NumTables x 16 - searchRange.
writer.WriteUInt32(version);
writer.WriteUInt16(tableCount);
writer.WriteUInt16(searchRange);
writer.WriteUInt16(entrySelector);
writer.WriteUInt16(rangeShift);
}
public static void WriteNameTable(this BigEndianBinaryWriter writer, Dictionary<KnownNameIds, string> names, List<string> languages = null)
=> writer.WriteNameTable(names.Select(x => (x.Key, x.Value, CultureInfo.InvariantCulture)).ToList(), languages);
public static void WriteNameTable(this BigEndianBinaryWriter writer, params (KnownNameIds NameId, string Value, CultureInfo Culture)[] names)
=> writer.WriteNameTable(names.ToList());
public static void WriteNameTable(this BigEndianBinaryWriter writer, List<(KnownNameIds NameId, string Value, CultureInfo Culture)> names, List<string> languages = null)
{
// Type | Name | Description
// --------------|-----------------------------|--------------------------------------------------------
// uint16 | format | Format selector
// uint16 | count | Number of name records.
// Offset16 | stringOffset | Offset to start of string storage (from start of table).
// NameRecord | nameRecord[count] | The name records where count is the number of records.
// additionally if format = 1
// uint16 | langTagCount | Number of language-tag records.
// LangTagRecord | langTagRecord[langTagCount] | The language-tag records where langTagCount is the number of records.
writer.WriteUInt16((ushort)(languages == null ? 0 : 1));
writer.WriteUInt16((ushort)names.Count);
int sizeOfHeader = 6;
if (languages != null)
{
const int langRecordSize = 4;
// format 1
sizeOfHeader += 2;
sizeOfHeader += langRecordSize * languages.Count;
}
const int nameRecordSize = 12;
sizeOfHeader += nameRecordSize * names.Count;
writer.WriteOffset16((ushort)sizeOfHeader);
// write name records
// Type | Name | Description
// ---------|------------|----------------------------------------------------
// uint16 | platformID | Platform ID.
// uint16 | encodingID | Platform - specific encoding ID.
// uint16 | languageID | Language ID.
// uint16 | nameID | Name ID.
// uint16 | length | String length (in bytes).
// Offset16 | offset | String offset from start of storage area(in bytes).
Encoding encoding = Encoding.BigEndianUnicode; // this is Unicode2
int stringOffset = 0;
var offsets = new List<int>();
foreach ((KnownNameIds name, string value, CultureInfo culture) in names)
{
writer.WriteUInt16((ushort)PlatformIDs.Windows); // hard code platform
writer.WriteUInt16((ushort)EncodingIDs.Unicode2); // hard code encoding
writer.WriteUInt16((ushort)culture.LCID); // hard code language
writer.WriteUInt16((ushort)name);
int length = Encoding.BigEndianUnicode.GetBytes(value).Length;
writer.WriteUInt16((ushort)length);
writer.WriteOffset16((ushort)stringOffset);
offsets.Add(stringOffset);
stringOffset += length;
}
if (languages != null)
{
writer.WriteUInt16((ushort)languages.Count);
// language record
// uint16 | length | String length (in bytes).
// Offset16 | offset | String offset from start of storage area(in bytes).
foreach (string n in languages)
{
int length = Encoding.BigEndianUnicode.GetBytes(n).Length;
writer.WriteUInt16((ushort)length);
writer.WriteOffset16((ushort)stringOffset);
offsets.Add(stringOffset);
stringOffset += length;
}
}
int currentItem = 0;
foreach ((KnownNameIds name, string value, CultureInfo culture) in names)
{
int expectedPosition = offsets[currentItem];
currentItem++;
writer.WriteNoLength(value, Encoding.BigEndianUnicode);
}
if (languages != null)
{
foreach (string n in languages)
{
int expectedPosition = offsets[currentItem];
currentItem++;
writer.WriteNoLength(n, Encoding.BigEndianUnicode);
}
}
}
public static void WriteCMapTable(this BigEndianBinaryWriter writer, IEnumerable<CMapSubTable> subtables)
{
// 'cmap' Header:
// Type | Name | Description
// ---------------|----------------------------|------------------------------------
// uint16 | version |Table version number(0).
// uint16 | numTables |Number of encoding tables that follow.
// EncodingRecord | encodingRecords[numTables] |
writer.WriteUInt16(0);
writer.WriteUInt16((ushort)subtables.Count());
int offset = 4; // for for the cmap header
offset += 8 * subtables.Count(); // 8 bytes per encoding header
foreach (CMapSubTable table in subtables)
{
// EncodingRecord:
// Type | Name | Description
// ---------|------------|-----------------------------------------------
// uint16 | platformID | Platform ID.
// uint16 | encodingID | Platform - specific encoding ID.
// Offset32 | offset | Byte offset from beginning of table to the subtable for this encoding.
writer.WriteUInt16((ushort)table.Platform);
writer.WriteUInt16(table.Encoding);
writer.WriteUInt32((uint)offset);
offset += table.DataLength();
// calculate the size of each format
}
foreach (CMapSubTable table in subtables)
{
writer.WriteCMapSubTable(table);
}
}
public static void WriteCMapSubTable(this BigEndianBinaryWriter writer, CMapSubTable subtable)
{
writer.WriteCMapSubTable(subtable as Format0SubTable);
writer.WriteCMapSubTable(subtable as Format4SubTable);
}
public static void WriteCMapSubTable(this BigEndianBinaryWriter writer, Format0SubTable subtable)
{
if (subtable == null)
{
return;
}
// Format 0 SubTable
// Type |Name | Description
// ---------|------------------|--------------------------------------------------------------------------
// uint16 |format | Format number is set to 0.
// uint16 |length | This is the length in bytes of the subtable.
// uint16 |language | Please see “Note on the language field in 'cmap' subtables“ in this document.
// uint8 |glyphIdArray[glyphcount] | An array that maps character codes to glyph index values.
writer.WriteUInt16(0);
writer.WriteUInt16((ushort)subtable.DataLength());
writer.WriteUInt16(subtable.Language);
foreach (byte c in subtable.GlyphIds)
{
writer.WriteUInt8(c);
}
}
public static void WriteCMapSubTable(this BigEndianBinaryWriter writer, Format4SubTable subtable)
{
if (subtable == null)
{
return;
}
// 'cmap' Subtable Format 4:
// Type | Name | Description
// -------|----------------------------|------------------------------------------------------------------------
// uint16 | format | Format number is set to 4.
// uint16 | length | This is the length in bytes of the subtable.
// uint16 | language | Please see “Note on the language field in 'cmap' subtables“ in this document.
// uint16 | segCountX2 | 2 x segCount.
// uint16 | searchRange | 2 x (2**floor(log2(segCount)))
// uint16 | entrySelector | log2(searchRange/2)
// uint16 | rangeShift | 2 x segCount - searchRange
// uint16 | endCount[segCount] | End characterCode for each segment, last=0xFFFF.
// uint16 | reservedPad | Set to 0.
// uint16 | startCount[segCount] | Start character code for each segment.
// int16 | idDelta[segCount] | Delta for all character codes in segment.
// uint16 | idRangeOffset[segCount] | Offsets into glyphIdArray or 0
// uint16 | glyphIdArray[ ] | Glyph index array (arbitrary length)
writer.WriteUInt16(4);
writer.WriteUInt16((ushort)subtable.DataLength());
writer.WriteUInt16(subtable.Language);
int segCount = subtable.Segments.Length;
writer.WriteUInt16((ushort)(subtable.Segments.Length * 2));
double searchRange = Math.Pow(2, Math.Floor(Math.Log(segCount, 2)));
writer.WriteUInt16((ushort)searchRange);
double entrySelector = Math.Log(searchRange / 2, 2F);
writer.WriteUInt16((ushort)entrySelector);
double rangeShift = (2 * segCount) - searchRange;
writer.WriteUInt16((ushort)rangeShift);
foreach (Format4SubTable.Segment seg in subtable.Segments)
{
writer.WriteUInt16(seg.End);
}
writer.WriteUInt16(0);
foreach (Format4SubTable.Segment seg in subtable.Segments)
{
writer.WriteUInt16(seg.Start);
}
foreach (Format4SubTable.Segment seg in subtable.Segments)
{
writer.WriteInt16(seg.Delta);
}
foreach (Format4SubTable.Segment seg in subtable.Segments)
{
writer.WriteUInt16(seg.Offset);
}
foreach (ushort c in subtable.GlyphIds)
{
writer.WriteUInt16(c);
}
}
public static void WritePostTable(this BigEndianBinaryWriter writer, PostTable postTable)
{
// HEADER
// Type | Name | Description
// ----------------|---------------------|---------------------------------------------------------------
// Version16Dot16 | version | 0x00010000 for version 1.0, 0x00020000 for version 2.0, 0x00025000 for version 2.5 (deprecated), 0x00030000 for version 3.0
// Fixed | italicAngle | Italic angle in counter-clockwise degrees from the vertical. Zero for upright text, negative for text that leans to the right (forward).
// FWORD | underlinePosition | This is the suggested distance of the top of the underline from the baseline (negative values indicate below baseline). The PostScript definition of this FontInfo dictionary key (the y coordinate of the center of the stroke) is not used for historical reasons. The value of the PostScript key may be calculated by subtracting half the underlineThickness from the value of this field.
// FWORD | underlineThickness | Suggested values for the underline thickness. In general, the underline thickness should match the thickness of the underscore character (U+005F LOW LINE), and should also match the strikeout thickness, which is specified in the OS/2 table.
// uint32 | isFixedPitch | Set to 0 if the font is proportionally spaced, non-zero if the font is not proportionally spaced (i.e. monospaced).
// uint32 | minMemType42 | Minimum memory usage when an OpenType font is downloaded.
// uint32 | maxMemType42 | Maximum memory usage when an OpenType font is downloaded.
// uint32 | minMemType1 | Minimum memory usage when an OpenType font is downloaded as a Type 1 font.
// uint32 | maxMemType1 | Maximum memory usage when an OpenType font is downloaded as a Type 1 font.
writer.WriteUInt16(postTable.FormatMajor);
writer.WriteUInt16(postTable.FormatMinor);
writer.WriteFWORD(postTable.UnderlinePosition);
writer.WriteFWORD(postTable.UnderlineThickness);
writer.WriteUInt32(postTable.IsFixedPitch);
writer.WriteUInt32(postTable.MinMemType42);
writer.WriteUInt32(postTable.MaxMemType42);
writer.WriteUInt32(postTable.MinMemType1);
writer.WriteUInt32(postTable.MaxMemType1);
// FORMAT 2.0
// Type | Name | Description
// --------|-----------------------------|--------------------------------------------------------------
// uint16 | numGlyphs | Number of glyphs (this should be the same as numGlyphs in 'maxp' table).
// uint16 | glyphNameIndex[numGlyphs] | Array of indices into the string data. See below for details.
// uint8 | stringData[variable] | Storage for the string data.
writer.WriteUInt16((ushort)postTable.PostRecords.Length);
// Write the array of glyph name indices
foreach (PostNameRecord postRecord in postTable.PostRecords)
{
writer.WriteUInt16(postRecord.NameIndex);
}
// Write the actual name string data
foreach (PostNameRecord postRecord in postTable.PostRecords)
{
writer.WriteString(postRecord.Name, Encoding.ASCII);
}
}
private static int DataLength(this CMapSubTable subtable)
{
if (subtable is Format0SubTable table)
{
return 6 + table.GlyphIds.Length;
}
if (subtable is Format4SubTable format4Table)
{
Format4SubTable.Segment[] segs = format4Table.Segments;
ushort[] glyphs = format4Table.GlyphIds;
return 16 + (segs.Length * 8) + (glyphs.Length * 2);
}
return 0;
}
public static void WriteHorizontalHeadTable(this BigEndianBinaryWriter writer, HorizontalHeadTable table)
{
// Type | Name | Description
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// uint16 | majorVersion | Major version number of the horizontal header table — set to 1.
// uint16 | minorVersion | Minor version number of the horizontal header table — set to 0.
// FWORD | Ascender | Typographic ascent (Distance from baseline of highest ascender).
// FWORD | Descender | Typographic descent (Distance from baseline of lowest descender).
// FWORD | LineGap | Typographic line gap. - Negative LineGap values are treated as zero in Windows 3.1, and in Mac OS System 6 and System 7.
// UFWORD | advanceWidthMax | Maximum advance width value in 'hmtx' table.
// FWORD | minLeftSideBearing | Minimum left sidebearing value in 'hmtx' table.
// FWORD | minRightSideBearing | Minimum right sidebearing value; calculated as Min(aw - lsb - (xMax - xMin)).
// FWORD | xMaxExtent | Max(lsb + (xMax - xMin)).
// int16 | caretSlopeRise | Used to calculate the slope of the cursor (rise/run); 1 for vertical.
// int16 | caretSlopeRun | 0 for vertical.
// int16 | caretOffset | The amount by which a slanted highlight on a glyph needs to be shifted to produce the best appearance. Set to 0 for non-slanted fonts
// int16 | (reserved) | set to 0
// int16 | (reserved) | set to 0
// int16 | (reserved) | set to 0
// int16 | (reserved) | set to 0
// int16 | metricDataFormat | 0 for current format.
// uint16 | numberOfHMetrics | Number of hMetric entries in 'hmtx' table
writer.WriteUInt16(1);
writer.WriteUInt16(1);
writer.WriteFWORD(table.Ascender);
writer.WriteFWORD(table.Descender);
writer.WriteFWORD(table.LineGap);
writer.WriteUFWORD(table.AdvanceWidthMax);
writer.WriteFWORD(table.MinLeftSideBearing);
writer.WriteFWORD(table.MinRightSideBearing);
writer.WriteFWORD(table.XMaxExtent);
writer.WriteInt16(table.CaretSlopeRise);
writer.WriteInt16(table.CaretSlopeRun);
writer.WriteInt16(table.CaretOffset);
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // metricDataFormat should be 0
writer.WriteUInt16(table.NumberOfHMetrics);
}
public static void WriteHeadTable(this BigEndianBinaryWriter writer, HeadTable table)
{
// Type | Name | Description
// -------------|--------------------|----------------------------------------------------------------------------------------------------
// uint16 | majorVersion | Major version number of the font header table — set to 1.
// uint16 | minorVersion | Minor version number of the font header table — set to 0.
// Fixed | fontRevision | Set by font manufacturer.
// uint32 | checkSumAdjustment | To compute: set it to 0, sum the entire font as uint32, then store 0xB1B0AFBA - sum.If the font is used as a component in a font collection file, the value of this field will be invalidated by changes to the file structure and font table directory, and must be ignored.
// uint32 | magicNumber | Set to 0x5F0F3CF5.
// uint16 | flags | Bit 0: Baseline for font at y = 0;
// Bit 1: Left sidebearing point at x = 0(relevant only for TrueType rasterizers) — see the note below regarding variable fonts;
// Bit 2: Instructions may depend on point size;
// Bit 3: Force ppem to integer values for all internal scaler math; may use fractional ppem sizes if this bit is clear;
// Bit 4: Instructions may alter advance width(the advance widths might not scale linearly);
// Bit 5: This bit is not used in OpenType, and should not be set in order to ensure compatible behavior on all platforms.If set, it may result in different behavior for vertical layout in some platforms. (See Apple's specification for details regarding behavior in Apple platforms.)
// Bits 6–10: These bits are not used in Opentype and should always be cleared. (See Apple's specification for details regarding legacy used in Apple platforms.)
// Bit 11: Font data is ‘lossless’ as a results of having been subjected to optimizing transformation and/or compression (such as e.g.compression mechanisms defined by ISO/IEC 14496-18, MicroType Express, WOFF 2.0 or similar) where the original font functionality and features are retained but the binary compatibility between input and output font files is not guaranteed.As a result of the applied transform, the ‘DSIG’ Table may also be invalidated.
// Bit 12: Font converted (produce compatible metrics)
// Bit 13: Font optimized for ClearType™. Note, fonts that rely on embedded bitmaps (EBDT) for rendering should not be considered optimized for ClearType, and therefore should keep this bit cleared.
// Bit 14: Last Resort font.If set, indicates that the glyphs encoded in the cmap subtables are simply generic symbolic representations of code point ranges and don’t truly represent support for those code points.If unset, indicates that the glyphs encoded in the cmap subtables represent proper support for those code points.
// Bit 15: Reserved, set to 0
// uint16 | unitsPerEm | Valid range is from 16 to 16384. This value should be a power of 2 for fonts that have TrueType outlines.
// LONGDATETIME | created | Number of seconds since 12:00 midnight that started January 1st 1904 in GMT/UTC time zone. 64-bit integer
// LONGDATETIME | modified | Number of seconds since 12:00 midnight that started January 1st 1904 in GMT/UTC time zone. 64-bit integer
// int16 | xMin | For all glyph bounding boxes.
// int16 | yMin | For all glyph bounding boxes.
// int16 | xMax | For all glyph bounding boxes.
// int16 | yMax | For all glyph bounding boxes.
// uint16 | macStyle | Bit 0: Bold (if set to 1);
// Bit 1: Italic(if set to 1)
// Bit 2: Underline(if set to 1)
// Bit 3: Outline(if set to 1)
// Bit 4: Shadow(if set to 1)
// Bit 5: Condensed(if set to 1)
// Bit 6: Extended(if set to 1)
// Bits 7–15: Reserved(set to 0).
// uint16 |lowestRecPPEM | Smallest readable size in pixels.
// int16 | fontDirectionHint | Deprecated(Set to 2).
// 0: Fully mixed directional glyphs;
// 1: Only strongly left to right;
// 2: Like 1 but also contains neutrals;
// -1: Only strongly right to left;
// -2: Like -1 but also contains neutrals. 1
// int16 | indexToLocFormat | 0 for short offsets (Offset16), 1 for long (Offset32).
// int16 | glyphDataFormat | 0 for current format.
writer.WriteUInt16(1);
writer.WriteUInt16(0);
writer.WriteUInt32(0);
writer.WriteUInt32(0);
writer.WriteUInt32(0x5F0F3CF5);
writer.WriteUInt16((ushort)table.Flags);
writer.WriteUInt16(table.UnitsPerEm);
var startDate = new DateTime(1904, 01, 01, 0, 0, 0, DateTimeKind.Utc);
writer.WriteInt64((long)table.Created.Subtract(startDate).TotalSeconds);
writer.WriteInt64((long)table.Modified.Subtract(startDate).TotalSeconds);
writer.WriteInt16((short)table.Bounds.Min.X);
writer.WriteInt16((short)table.Bounds.Min.Y);
writer.WriteInt16((short)table.Bounds.Max.X);
writer.WriteInt16((short)table.Bounds.Max.Y);
writer.WriteUInt16((ushort)table.MacStyle);
writer.WriteUInt16(table.LowestRecPPEM);
writer.WriteInt16(2);
writer.WriteInt16((short)table.IndexLocationFormat);
writer.WriteInt16(0);
}
public static void WriteVerticalHeadTable(this BigEndianBinaryWriter writer, VerticalHeadTable table)
{
// Type | Name | Description
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// fixed32 | version | Version number of the Vertical Header Table (0x00011000 for the current version).
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | vertTypoAscender | The vertical typographic ascender for this font. It is the distance in FUnits from the vertical center
// | | baseline to the right of the design space. This will usually be set to half the horizontal advance of
// | | full-width glyphs. For example, if the full width is 1000 FUnits, this field will be set to 500.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | vertTypoDescender | The vertical typographic descender for this font. It is the distance in FUnits from the vertical center
// | | baseline to the left of the design space. This will usually be set to half the horizontal advance of
// | | full-width glyphs. For example, if the full width is 1000 FUnits, this field will be set to -500.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | vertTypoLineGap | The vertical typographic line gap for this font.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | advanceHeightMax | The maximum advance height measurement in FUnits found in the font.
// | This value must be consistent with the entries in the vertical metrics table.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | minTopSideBearing | The minimum top side bearing measurement in FUnits found in the font, in FUnits.
// ----------|----------------------| This value must be consistent with the entries in the vertical metrics table.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | minBottomSideBearing | The minimum bottom side bearing measurement in FUnits found in the font, in FUnits.
// ----------|----------------------| This value must be consistent with the entries in the vertical metrics table.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | yMaxExtent | This is defined as the value of the minTopSideBearing field added to the result of the value of the
// | | yMin field subtracted from the value of the yMax field.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | caretSlopeRise | The value of the caretSlopeRise field divided by the value of the caretSlopeRun field determines the
// | | slope of the caret.
// | | A value of 0 for the rise and a value of 1 for the run specifies a horizontal caret.
// | | A value of 1 for the rise and a value of 0 for the run specifies a vertical caret.
// | | A value between 0 for the rise and 1 for the run is desirable for fonts whose glyphs are oblique or
// | | italic. For a vertical font, a horizontal caret is best.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | caretSlopeRun | See the caretSlopeRise field. Value = 0 for non-slanted fonts.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | caretOffset | The amount by which the highlight on a slanted glyph needs to be shifted away from the glyph in
// | | order to produce the best appearance. Set value equal to 0 for non-slanted fonts.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | reserved | Set to 0.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | reserved | Set to 0.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | reserved | Set to 0.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | reserved | Set to 0.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// int16 | metricDataFormat | Set to 0.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
// uint16 | numOfLongVerMetrics | Number of advance heights in the Vertical Metrics table.
// ----------|----------------------|----------------------------------------------------------------------------------------------------
writer.WriteUInt16(1);
writer.WriteUInt16(1);
writer.WriteInt16(table.Ascender);
writer.WriteInt16(table.Descender);
writer.WriteInt16(table.LineGap);
writer.WriteInt16(table.AdvanceHeightMax);
writer.WriteInt16(table.MinTopSideBearing);
writer.WriteInt16(table.MinBottomSideBearing);
writer.WriteInt16(table.YMaxExtent);
writer.WriteInt16(table.CaretSlopeRise);
writer.WriteInt16(table.CaretSlopeRun);
writer.WriteInt16(table.CaretOffset);
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // reserved
writer.WriteInt16(0); // metricDataFormat should be 0
writer.WriteUInt16(table.NumberOfVMetrics);
}
public static void WriteColrTable(this BigEndianBinaryWriter writer, ColrGlyphRecord[] data)
{
var formatted = data.ToList();
// Type | Name | Description
// ----------|------------------------|----------------------------------------------------------------------------------------------------
// uint16 | version | Table version number(starts at 0).
// uint16 | numBaseGlyphRecords | Number of Base Glyph Records.
// Offset32 | baseGlyphRecordsOffset | Offset(from beginning of COLR table) to Base Glyph records.
// Offset32 | layerRecordsOffset | Offset(from beginning of COLR table) to Layer Records.
// uint16 | numLayerRecords | Number of Layer Records.
// write header
writer.WriteUInt16(0);
writer.WriteUInt16((ushort)formatted.Count);
uint headerEnd = 14;
writer.WriteOffset32(headerEnd);
long baseGlyphEnd = formatted.Sum(x => x.HeaderSize) + headerEnd;
writer.WriteOffset32((uint)baseGlyphEnd);
int layerCount = formatted.Sum(x => x.Layers.Count);
writer.WriteUInt16((ushort)layerCount);
ushort totalLayers = 0;
foreach (ColrGlyphRecord g in formatted)
{
writer.WriteUInt16(g.Glyph);
writer.WriteUInt16(totalLayers);
ushort layers = (ushort)g.Layers.Count;
writer.WriteUInt16(layers);
totalLayers += layers;
}
foreach (ColrGlyphRecord g in formatted)
{
foreach (ColrLayerRecord l in g.Layers)
{
writer.WriteUInt16(l.Glyph);
writer.WriteUInt16(l.Palette);
}
}
}
| WriterExtensions |
csharp | dotnet__efcore | test/EFCore.OData.FunctionalTests/Query/GearsOfWarODataContext.cs | {
"start": 252,
"end": 3668
} | public class ____(DbContextOptions options) : PoolableDbContext(options)
{
public DbSet<Gear> Gears { get; set; }
public DbSet<Squad> Squads { get; set; }
public DbSet<CogTag> Tags { get; set; }
public DbSet<Weapon> Weapons { get; set; }
public DbSet<City> Cities { get; set; }
public DbSet<Mission> Missions { get; set; }
public DbSet<SquadMission> SquadMissions { get; set; }
public DbSet<Faction> Factions { get; set; }
public DbSet<LocustLeader> LocustLeaders { get; set; }
public DbSet<LocustHighCommand> LocustHighCommands { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<City>(b =>
{
b.HasKey(c => c.Name);
});
modelBuilder.Entity<Gear>(b =>
{
b.HasKey(g => new { g.Nickname, g.SquadId });
b.HasOne(g => g.CityOfBirth).WithMany(c => c.BornGears).HasForeignKey(g => g.CityOfBirthName).IsRequired();
b.HasOne(g => g.Tag).WithOne(t => t.Gear).HasForeignKey<CogTag>(t => new { t.GearNickName, t.GearSquadId });
b.HasOne(g => g.AssignedCity).WithMany(c => c.StationedGears).IsRequired(false);
});
modelBuilder.Entity<Officer>().HasMany(o => o.Reports).WithOne().HasForeignKey(o => new { o.LeaderNickname, o.LeaderSquadId });
modelBuilder.Entity<Squad>(b =>
{
b.HasKey(s => s.Id);
b.Property(s => s.Id).ValueGeneratedNever();
b.Property(s => s.Banner5).HasMaxLength(5);
b.HasMany(s => s.Members).WithOne(g => g.Squad).HasForeignKey(g => g.SquadId);
});
modelBuilder.Entity<Weapon>(b =>
{
b.Property(w => w.Id).ValueGeneratedNever();
b.HasOne(w => w.SynergyWith).WithOne().HasForeignKey<Weapon>(w => w.SynergyWithId);
b.HasOne(w => w.Owner).WithMany(g => g.Weapons).HasForeignKey(w => w.OwnerFullName).HasPrincipalKey(g => g.FullName);
});
modelBuilder.Entity<Mission>().Property(m => m.Id).ValueGeneratedNever();
modelBuilder.Entity<SquadMission>(b =>
{
b.HasKey(sm => new { sm.SquadId, sm.MissionId });
b.HasOne(sm => sm.Mission).WithMany(m => m.ParticipatingSquads).HasForeignKey(sm => sm.MissionId);
b.HasOne(sm => sm.Squad).WithMany(s => s.Missions).HasForeignKey(sm => sm.SquadId);
});
modelBuilder.Entity<Faction>().HasKey(f => f.Id);
modelBuilder.Entity<Faction>().Property(f => f.Id).ValueGeneratedNever();
modelBuilder.Entity<LocustHorde>().HasBaseType<Faction>();
modelBuilder.Entity<LocustHorde>().HasMany(h => h.Leaders).WithOne();
modelBuilder.Entity<LocustHorde>().HasOne(h => h.Commander).WithOne(c => c.CommandingFaction);
modelBuilder.Entity<LocustLeader>().HasKey(l => l.Name);
modelBuilder.Entity<LocustCommander>().HasBaseType<LocustLeader>();
modelBuilder.Entity<LocustCommander>().HasOne(c => c.DefeatedBy).WithOne()
.HasForeignKey<LocustCommander>(c => new { c.DefeatedByNickname, c.DefeatedBySquadId });
modelBuilder.Entity<LocustHighCommand>().HasKey(l => l.Id);
modelBuilder.Entity<LocustHighCommand>().Property(l => l.Id).ValueGeneratedNever();
modelBuilder.Entity<City>().Property(g => g.Location).HasColumnType("varchar(100)");
}
}
| GearsOfWarODataContext |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs | {
"start": 719,
"end": 810
} | class ____ adds razor page functionality to <see cref="IMvcCoreBuilder"/>.
/// </summary>
| that |
csharp | dotnet__aspnetcore | src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs | {
"start": 115565,
"end": 115697
} | private class ____
{
public TestInnerModel[] InnerModels { get; set; } = Array.Empty<TestInnerModel>();
}
| TestModel |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Controllers/EmailAccountController.cs | {
"start": 648,
"end": 7252
} | public class ____ : BaseAdminController
{
private readonly ICacheBase _cacheBase;
private readonly IEmailAccountService _emailAccountService;
private readonly EmailAccountSettings _emailAccountSettings;
private readonly IEmailAccountViewModelService _emailAccountViewModelService;
private readonly ISettingService _settingService;
private readonly ITranslationService _translationService;
public EmailAccountController(IEmailAccountViewModelService emailAccountViewModelService,
IEmailAccountService emailAccountService,
ITranslationService translationService, ISettingService settingService,
EmailAccountSettings emailAccountSettings, ICacheBase cacheBase)
{
_emailAccountViewModelService = emailAccountViewModelService;
_emailAccountService = emailAccountService;
_translationService = translationService;
_emailAccountSettings = emailAccountSettings;
_settingService = settingService;
_cacheBase = cacheBase;
}
public IActionResult List()
{
return View();
}
[HttpPost]
[PermissionAuthorizeAction(PermissionActionName.List)]
public async Task<IActionResult> List(DataSourceRequest command)
{
var emailAccountModels = (await _emailAccountService.GetAllEmailAccounts())
.Select(x => x.ToModel())
.ToList();
foreach (var eam in emailAccountModels)
eam.IsDefaultEmailAccount = eam.Id == _emailAccountSettings.DefaultEmailAccountId;
var gridModel = new DataSourceResult {
Data = emailAccountModels,
Total = emailAccountModels.Count
};
return Json(gridModel);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> MarkAsDefaultEmail(string id)
{
var defaultEmailAccount = await _emailAccountService.GetEmailAccountById(id);
if (defaultEmailAccount != null)
{
_emailAccountSettings.DefaultEmailAccountId = defaultEmailAccount.Id;
await _settingService.SaveSetting(_emailAccountSettings);
}
//now clear cache
await _cacheBase.Clear();
return RedirectToAction("List");
}
[PermissionAuthorizeAction(PermissionActionName.Create)]
public IActionResult Create()
{
var model = _emailAccountViewModelService.PrepareEmailAccountModel();
return View(model);
}
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
[PermissionAuthorizeAction(PermissionActionName.Create)]
public async Task<IActionResult> Create(EmailAccountModel model, bool continueEditing)
{
if (ModelState.IsValid)
{
var emailAccount = await _emailAccountViewModelService.InsertEmailAccountModel(model);
Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> Edit(string id)
{
var emailAccount = await _emailAccountService.GetEmailAccountById(id);
if (emailAccount == null)
//No email account found with the specified id
return RedirectToAction("List");
return View(emailAccount.ToModel());
}
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> Edit(EmailAccountModel model, bool continueEditing)
{
var emailAccount = await _emailAccountService.GetEmailAccountById(model.Id);
if (emailAccount == null)
//No email account found with the specified id
return RedirectToAction("List");
if (ModelState.IsValid)
{
emailAccount = await _emailAccountViewModelService.UpdateEmailAccountModel(emailAccount, model);
Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Updated"));
return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> SendTestEmail(EmailAccountModel model)
{
var emailAccount = await _emailAccountService.GetEmailAccountById(model.Id);
if (emailAccount == null)
//No email account found with the specified id
return RedirectToAction("List");
try
{
if (string.IsNullOrWhiteSpace(model.SendTestEmailTo))
throw new GrandException("Enter test email address");
if (ModelState.IsValid)
{
await _emailAccountViewModelService.SendTestEmail(emailAccount, model);
Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.SendTestEmail.Success"),
false);
}
else
{
Error(ModelState);
}
}
catch (Exception exc)
{
Error(exc.Message);
}
//If we got this far, something failed, redisplay form
return RedirectToAction("Edit", new { id = model.Id });
}
[HttpPost]
[PermissionAuthorizeAction(PermissionActionName.Delete)]
public async Task<IActionResult> Delete(string id)
{
var emailAccount = await _emailAccountService.GetEmailAccountById(id);
if (emailAccount == null)
//No email account found with the specified id
return RedirectToAction("List");
try
{
if (ModelState.IsValid)
{
await _emailAccountService.DeleteEmailAccount(emailAccount);
Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Deleted"));
}
else
{
Error(ModelState);
}
return RedirectToAction("List");
}
catch (Exception exc)
{
Error(exc);
return RedirectToAction("Edit", new { id = emailAccount.Id });
}
}
} | EmailAccountController |
csharp | Cysharp__MemoryPack | src/MemoryPack.Core/MemoryPackWriter.cs | {
"start": 355,
"end": 20253
} | partial struct ____<TBufferWriter>
#if NET7_0_OR_GREATER
where TBufferWriter : IBufferWriter<byte>
#else
where TBufferWriter : class, IBufferWriter<byte>
#endif
{
const int DepthLimit = 1000;
#if NET7_0_OR_GREATER
ref TBufferWriter bufferWriter;
ref byte bufferReference;
#else
TBufferWriter bufferWriter;
Span<byte> bufferReference;
#endif
int bufferLength;
int advancedCount;
int depth; // check recursive serialize
int writtenCount;
readonly bool serializeStringAsUtf8;
readonly MemoryPackWriterOptionalState optionalState;
public int WrittenCount => writtenCount;
public int BufferLength => bufferLength;
public MemoryPackWriterOptionalState OptionalState => optionalState;
public MemoryPackSerializerOptions Options => optionalState.Options;
public MemoryPackWriter(ref TBufferWriter writer, MemoryPackWriterOptionalState optionalState)
{
#if NET7_0_OR_GREATER
this.bufferWriter = ref writer;
this.bufferReference = ref Unsafe.NullRef<byte>();
#else
this.bufferWriter = writer;
this.bufferReference = default;
#endif
this.bufferLength = 0;
this.advancedCount = 0;
this.writtenCount = 0;
this.depth = 0;
this.serializeStringAsUtf8 = optionalState.Options.StringEncoding == StringEncoding.Utf8;
this.optionalState = optionalState;
}
// optimized ctor, avoid first GetSpan call if we can.
public MemoryPackWriter(ref TBufferWriter writer, byte[] firstBufferOfWriter, MemoryPackWriterOptionalState optionalState)
{
#if NET7_0_OR_GREATER
this.bufferWriter = ref writer;
this.bufferReference = ref GetArrayDataReference(firstBufferOfWriter);
#else
this.bufferWriter = writer;
this.bufferReference = firstBufferOfWriter.AsSpan();
#endif
this.bufferLength = firstBufferOfWriter.Length;
this.advancedCount = 0;
this.writtenCount = 0;
this.depth = 0;
this.serializeStringAsUtf8 = optionalState.Options.StringEncoding == StringEncoding.Utf8;
this.optionalState = optionalState;
}
public MemoryPackWriter(ref TBufferWriter writer, Span<byte> firstBufferOfWriter, MemoryPackWriterOptionalState optionalState)
{
#if NET7_0_OR_GREATER
this.bufferWriter = ref writer;
this.bufferReference = ref MemoryMarshal.GetReference(firstBufferOfWriter);
#else
this.bufferWriter = writer;
this.bufferReference = firstBufferOfWriter;
#endif
this.bufferLength = firstBufferOfWriter.Length;
this.advancedCount = 0;
this.writtenCount = 0;
this.depth = 0;
this.serializeStringAsUtf8 = optionalState.Options.StringEncoding == StringEncoding.Utf8;
this.optionalState = optionalState;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref byte GetSpanReference(int sizeHint)
{
if (bufferLength < sizeHint)
{
RequestNewBuffer(sizeHint);
}
#if NET7_0_OR_GREATER
return ref bufferReference;
#else
return ref MemoryMarshal.GetReference(bufferReference);
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
void RequestNewBuffer(int sizeHint)
{
if (advancedCount != 0)
{
bufferWriter.Advance(advancedCount);
advancedCount = 0;
}
var span = bufferWriter.GetSpan(sizeHint);
#if NET7_0_OR_GREATER
bufferReference = ref MemoryMarshal.GetReference(span);
#else
bufferReference = span;
#endif
bufferLength = span.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(int count)
{
if (count == 0) return;
var rest = bufferLength - count;
if (rest < 0)
{
MemoryPackSerializationException.ThrowInvalidAdvance();
}
bufferLength = rest;
#if NET7_0_OR_GREATER
bufferReference = ref Unsafe.Add(ref bufferReference, count);
#else
bufferReference = bufferReference.Slice(count);
#endif
advancedCount += count;
writtenCount += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Flush()
{
if (advancedCount != 0)
{
bufferWriter.Advance(advancedCount);
advancedCount = 0;
}
#if NET7_0_OR_GREATER
bufferReference = ref Unsafe.NullRef<byte>();
#else
bufferReference = default;
#endif
bufferLength = 0;
writtenCount = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IMemoryPackFormatter GetFormatter(Type type)
{
return MemoryPackFormatterProvider.GetFormatter(type);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IMemoryPackFormatter<T> GetFormatter<T>()
{
return MemoryPackFormatterProvider.GetFormatter<T>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetStringWriteLength(string? value)
{
if (value == null || value.Length == 0)
{
return 4;
}
if (serializeStringAsUtf8)
{
return Encoding.UTF8.GetByteCount(value) + 8;
}
else
{
return checked(value.Length * 2) + 4;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetUnmanageArrayWriteLength<T>(T[]? value)
where T : unmanaged
{
if (value == null || value.Length == 0)
{
return 4;
}
return (Unsafe.SizeOf<T>() * value.Length) + 4;
}
// Write methods
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteObjectHeader(byte memberCount)
{
if (memberCount >= MemoryPackCode.Reserved1)
{
MemoryPackSerializationException.ThrowWriteInvalidMemberCount(memberCount);
}
GetSpanReference(1) = memberCount;
Advance(1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteNullObjectHeader()
{
GetSpanReference(1) = MemoryPackCode.NullObject;
Advance(1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteObjectReferenceId(uint referenceId)
{
GetSpanReference(1) = MemoryPackCode.ReferenceId;
Advance(1);
WriteVarInt(referenceId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUnionHeader(ushort tag)
{
if (tag < MemoryPackCode.WideTag)
{
GetSpanReference(1) = (byte)tag;
Advance(1);
}
else
{
ref var spanRef = ref GetSpanReference(3);
Unsafe.WriteUnaligned(ref spanRef, MemoryPackCode.WideTag);
Unsafe.WriteUnaligned(ref Unsafe.Add(ref spanRef, 1), tag);
Advance(3);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteNullUnionHeader()
{
WriteNullObjectHeader();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteCollectionHeader(int length)
{
Unsafe.WriteUnaligned(ref GetSpanReference(4), length);
Advance(4);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteNullCollectionHeader()
{
Unsafe.WriteUnaligned(ref GetSpanReference(4), MemoryPackCode.NullCollection);
Advance(4);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteString(string? value)
{
if (serializeStringAsUtf8)
{
WriteUtf8(value);
}
else
{
WriteUtf16(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUtf16(string? value)
{
if (value == null)
{
WriteNullCollectionHeader();
return;
}
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
var copyByteCount = checked(value.Length * 2);
ref var dest = ref GetSpanReference(copyByteCount + 4);
Unsafe.WriteUnaligned(ref dest, value.Length);
#if NET7_0_OR_GREATER
ref var src = ref Unsafe.As<char, byte>(ref Unsafe.AsRef(in value.GetPinnableReference()));
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dest, 4), ref src, (uint)copyByteCount);
#else
MemoryMarshal.AsBytes(value.AsSpan()).CopyTo(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref dest, 4), copyByteCount));
#endif
Advance(copyByteCount + 4);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUtf16(ReadOnlySpan<char> value)
{
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
var copyByteCount = checked(value.Length * 2);
ref var dest = ref GetSpanReference(copyByteCount + 4);
Unsafe.WriteUnaligned(ref dest, value.Length);
MemoryMarshal.AsBytes(value).CopyTo(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref dest, 4), copyByteCount));
Advance(copyByteCount + 4);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUtf8(string? value)
{
if (value == null)
{
WriteNullCollectionHeader();
return;
}
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
// (int ~utf8-byte-count, int utf16-length, utf8-bytes)
var source = value.AsSpan();
// UTF8.GetMaxByteCount -> (length + 1) * 3
var maxByteCount = (source.Length + 1) * 3;
ref var destPointer = ref GetSpanReference(maxByteCount + 8); // header
// write utf16-length
Unsafe.WriteUnaligned(ref Unsafe.Add(ref destPointer, 4), source.Length);
var dest = MemoryMarshal.CreateSpan(ref Unsafe.Add(ref destPointer, 8), maxByteCount);
#if NET7_0_OR_GREATER
var status = Utf8.FromUtf16(source, dest, out var _, out var bytesWritten, replaceInvalidSequences: false);
if (status != OperationStatus.Done)
{
MemoryPackSerializationException.ThrowFailedEncoding(status);
}
#else
var bytesWritten = Encoding.UTF8.GetBytes(value, dest);
#endif
// write written utf8-length in header, that is ~length
Unsafe.WriteUnaligned(ref destPointer, ~bytesWritten);
Advance(bytesWritten + 8); // + header
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUtf8(ReadOnlySpan<byte> utf8Value, int utf16Length = -1)
{
if (utf8Value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
// (int ~utf8-byte-count, int utf16-length, utf8-bytes)
ref var destPointer = ref GetSpanReference(utf8Value.Length + 8); // header
Unsafe.WriteUnaligned(ref destPointer, ~utf8Value.Length);
Unsafe.WriteUnaligned(ref Unsafe.Add(ref destPointer, 4), utf16Length);
var dest = MemoryMarshal.CreateSpan(ref Unsafe.Add(ref destPointer, 8), utf8Value.Length);
utf8Value.CopyTo(dest);
Advance(utf8Value.Length + 8);
}
#if NET7_0_OR_GREATER
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WritePackable<T>(scoped in T? value)
where T : IMemoryPackable<T>
{
depth++;
if (depth == DepthLimit) MemoryPackSerializationException.ThrowReachedDepthLimit(typeof(T));
T.Serialize(ref this, ref Unsafe.AsRef(in value));
depth--;
}
#else
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WritePackable<T>(scoped in T? value)
where T : IMemoryPackable<T>
{
WriteValue(value);
}
#endif
// non packable, get formatter dynamically.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(scoped in T? value)
{
depth++;
if (depth == DepthLimit) MemoryPackSerializationException.ThrowReachedDepthLimit(typeof(T));
GetFormatter<T>().Serialize(ref this, ref Unsafe.AsRef(in value));
depth--;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Type type, object? value)
{
depth++;
if (depth == DepthLimit) MemoryPackSerializationException.ThrowReachedDepthLimit(type);
GetFormatter(type).Serialize(ref this, ref value);
depth--;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueWithFormatter<TFormatter, T>(TFormatter formatter, scoped in T? value)
where TFormatter : IMemoryPackFormatter<T>
{
depth++;
formatter.Serialize(ref this, ref Unsafe.AsRef(in value));
depth--;
}
#region WriteArray/Span
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteArray<T>(T?[]? value)
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedArray(value);
return;
}
if (value == null)
{
WriteNullCollectionHeader();
return;
}
var formatter = GetFormatter<T>();
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
formatter.Serialize(ref this, ref value[i]);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteSpan<T>(scoped Span<T?> value)
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedSpan(value);
return;
}
var formatter = GetFormatter<T>();
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
formatter.Serialize(ref this, ref value[i]);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteSpan<T>(scoped ReadOnlySpan<T?> value)
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedSpan(value);
return;
}
var formatter = GetFormatter<T>();
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
formatter.Serialize(ref this, ref Unsafe.AsRef(in value[i]));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WritePackableArray<T>(T?[]? value)
where T : IMemoryPackable<T>
{
#if !NET7_0_OR_GREATER
WriteArray(value);
return;
#else
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedArray(value);
return;
}
if (value == null)
{
WriteNullCollectionHeader();
return;
}
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
T.Serialize(ref this, ref value[i]);
}
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WritePackableSpan<T>(scoped Span<T?> value)
where T : IMemoryPackable<T>
{
#if !NET7_0_OR_GREATER
WriteSpan(value);
return;
#else
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedSpan(value);
return;
}
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
T.Serialize(ref this, ref value[i]);
}
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WritePackableSpan<T>(scoped ReadOnlySpan<T?> value)
where T : IMemoryPackable<T>
{
#if !NET7_0_OR_GREATER
WriteSpan(value);
return;
#else
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
DangerousWriteUnmanagedSpan(value);
return;
}
WriteCollectionHeader(value.Length);
for (int i = 0; i < value.Length; i++)
{
T.Serialize(ref this, ref Unsafe.AsRef(in value[i]));
}
#endif
}
#endregion
#region WriteUnmanagedArray/Span
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUnmanagedArray<T>(T[]? value)
where T : unmanaged
{
DangerousWriteUnmanagedArray(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUnmanagedSpan<T>(scoped Span<T> value)
where T : unmanaged
{
DangerousWriteUnmanagedSpan(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUnmanagedSpan<T>(scoped ReadOnlySpan<T> value)
where T : unmanaged
{
DangerousWriteUnmanagedSpan(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DangerousWriteUnmanagedArray<T>(T[]? value)
{
if (value == null)
{
WriteNullCollectionHeader();
return;
}
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
var srcLength = Unsafe.SizeOf<T>() * value.Length;
var allocSize = srcLength + 4;
ref var dest = ref GetSpanReference(allocSize);
ref var src = ref Unsafe.As<T, byte>(ref GetArrayDataReference(value));
Unsafe.WriteUnaligned(ref dest, value.Length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dest, 4), ref src, (uint)srcLength);
Advance(allocSize);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DangerousWriteUnmanagedSpan<T>(scoped Span<T> value)
{
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
var srcLength = Unsafe.SizeOf<T>() * value.Length;
var allocSize = srcLength + 4;
ref var dest = ref GetSpanReference(allocSize);
ref var src = ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value));
Unsafe.WriteUnaligned(ref dest, value.Length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dest, 4), ref src, (uint)srcLength);
Advance(allocSize);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DangerousWriteUnmanagedSpan<T>(scoped ReadOnlySpan<T> value)
{
if (value.Length == 0)
{
WriteCollectionHeader(0);
return;
}
var srcLength = Unsafe.SizeOf<T>() * value.Length;
var allocSize = srcLength + 4;
ref var dest = ref GetSpanReference(allocSize);
ref var src = ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value));
Unsafe.WriteUnaligned(ref dest, value.Length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dest, 4), ref src, (uint)srcLength);
Advance(allocSize);
}
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteSpanWithoutLengthHeader<T>(scoped ReadOnlySpan<T?> value)
{
if (value.Length == 0) return;
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
var srcLength = Unsafe.SizeOf<T>() * value.Length;
ref var dest = ref GetSpanReference(srcLength);
ref var src = ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)!);
Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)srcLength);
Advance(srcLength);
return;
}
else
{
var formatter = GetFormatter<T>();
for (int i = 0; i < value.Length; i++)
{
formatter.Serialize(ref this, ref Unsafe.AsRef(in value[i]));
}
}
}
}
| MemoryPackWriter |
csharp | rabbitmq__rabbitmq-dotnet-client | projects/Benchmarks/WireFormatting/PrimitivesSerialization.cs | {
"start": 1802,
"end": 2281
} | public class ____ : PrimitivesBase
{
public override void Setup() => WireFormatting.WriteLong(ref _buffer.Span.GetStart(), 12345u);
[Benchmark]
public uint LongRead()
{
WireFormatting.ReadLong(_buffer.Span, out uint v1);
return v1;
}
[Benchmark]
[Arguments(12345u)]
public int LongWrite(uint value) => WireFormatting.WriteLong(ref _buffer.Span.GetStart(), value);
}
| PrimitivesLong |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Features.Tests/FeatureCollectionTests.cs | {
"start": 1569,
"end": 2865
} | struct ____ method can't return null. Use 'featureCollection[typeof(System.Int32)] "
+ "is not null' to check if the feature exists.", ex.Message);
}
[Fact]
public void GetMissingFeatureReturnsNull()
{
var interfaces = new FeatureCollection();
Assert.Null(interfaces.Get<Thing>());
}
[Fact]
public void GetStructFeature()
{
var interfaces = new FeatureCollection();
const int value = 20;
interfaces.Set(value);
Assert.Equal(value, interfaces.Get<int>());
}
[Fact]
public void GetNullableStructFeatureWhenSetWithNonNullableStruct()
{
var interfaces = new FeatureCollection();
const int value = 20;
interfaces.Set(value);
Assert.Null(interfaces.Get<int?>());
}
[Fact]
public void GetNullableStructFeatureWhenSetWithNullableStruct()
{
var interfaces = new FeatureCollection();
const int value = 20;
interfaces.Set<int?>(value);
Assert.Equal(value, interfaces.Get<int?>());
}
[Fact]
public void GetFeature()
{
var interfaces = new FeatureCollection();
var thing = new Thing();
interfaces.Set(thing);
Assert.Equal(thing, interfaces.Get<Thing>());
}
}
| the |
csharp | ServiceStack__ServiceStack | ServiceStack.Redis/src/ServiceStack.Redis/RedisClientSortedSet.Async.cs | {
"start": 466,
"end": 5241
} | internal partial class ____
: IRedisSortedSetAsync
{
private IRedisClientAsync AsyncClient => client;
ValueTask IRedisSortedSetAsync.AddAsync(string value, CancellationToken token)
=> AsyncClient.AddItemToSortedSetAsync(setId, value, token).Await();
private IRedisSortedSetAsync AsAsync() => this;
ValueTask IRedisSortedSetAsync.ClearAsync(CancellationToken token)
=> new ValueTask(AsyncClient.RemoveAsync(setId, token));
ValueTask<bool> IRedisSortedSetAsync.ContainsAsync(string value, CancellationToken token)
=> AsyncClient.SortedSetContainsItemAsync(setId, value, token);
ValueTask<int> IRedisSortedSetAsync.CountAsync(CancellationToken token)
=> AsyncClient.GetSortedSetCountAsync(setId, token).AsInt32();
ValueTask<List<string>> IRedisSortedSetAsync.GetAllAsync(CancellationToken token)
=> AsyncClient.GetAllItemsFromSortedSetAsync(setId, token);
async IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(CancellationToken token)
{
// uses ZSCAN
await foreach (var pair in AsyncClient.ScanAllSortedSetItemsAsync(setId, token: token).ConfigureAwait(false))
{
yield return pair.Key;
}
}
ValueTask<long> IRedisSortedSetAsync.GetItemIndexAsync(string value, CancellationToken token)
=> AsyncClient.GetItemIndexInSortedSetAsync(setId, value, token);
ValueTask<double> IRedisSortedSetAsync.GetItemScoreAsync(string value, CancellationToken token)
=> AsyncClient.GetItemScoreInSortedSetAsync(setId, value, token);
ValueTask<List<string>> IRedisSortedSetAsync.GetRangeAsync(int startingRank, int endingRank, CancellationToken token)
=> AsyncClient.GetRangeFromSortedSetAsync(setId, startingRank, endingRank, token);
ValueTask<List<string>> IRedisSortedSetAsync.GetRangeByScoreAsync(string fromStringScore, string toStringScore, CancellationToken token)
=> AsAsync().GetRangeByScoreAsync(fromStringScore, toStringScore, null, null, token);
ValueTask<List<string>> IRedisSortedSetAsync.GetRangeByScoreAsync(string fromStringScore, string toStringScore, int? skip, int? take, CancellationToken token)
=> AsyncClient.GetRangeFromSortedSetByLowestScoreAsync(setId, fromStringScore, toStringScore, skip, take, token);
ValueTask<List<string>> IRedisSortedSetAsync.GetRangeByScoreAsync(double fromScore, double toScore, CancellationToken token)
=> AsAsync().GetRangeByScoreAsync(fromScore, toScore, null, null, token);
ValueTask<List<string>> IRedisSortedSetAsync.GetRangeByScoreAsync(double fromScore, double toScore, int? skip, int? take, CancellationToken token)
=> AsyncClient.GetRangeFromSortedSetByLowestScoreAsync(setId, fromScore, toScore, skip, take, token);
ValueTask IRedisSortedSetAsync.IncrementItemScoreAsync(string value, double incrementByScore, CancellationToken token)
=> AsyncClient.IncrementItemInSortedSetAsync(setId, value, incrementByScore, token).Await();
ValueTask<string> IRedisSortedSetAsync.PopItemWithHighestScoreAsync(CancellationToken token)
=> AsyncClient.PopItemWithHighestScoreFromSortedSetAsync(setId, token);
ValueTask<string> IRedisSortedSetAsync.PopItemWithLowestScoreAsync(CancellationToken token)
=> AsyncClient.PopItemWithLowestScoreFromSortedSetAsync(setId, token);
ValueTask<bool> IRedisSortedSetAsync.RemoveAsync(string value, CancellationToken token)
=> AsyncClient.RemoveItemFromSortedSetAsync(setId, value, token).AwaitAsTrue(); // see Remove() for why "true"
ValueTask IRedisSortedSetAsync.RemoveRangeAsync(int fromRank, int toRank, CancellationToken token)
=> AsyncClient.RemoveRangeFromSortedSetAsync(setId, fromRank, toRank, token).Await();
ValueTask IRedisSortedSetAsync.RemoveRangeByScoreAsync(double fromScore, double toScore, CancellationToken token)
=> AsyncClient.RemoveRangeFromSortedSetByScoreAsync(setId, fromScore, toScore, token).Await();
ValueTask IRedisSortedSetAsync.StoreFromIntersectAsync(IRedisSortedSetAsync[] ofSets, CancellationToken token)
=> AsyncClient.StoreIntersectFromSortedSetsAsync(setId, ofSets.GetIds(), token).Await();
ValueTask IRedisSortedSetAsync.StoreFromIntersectAsync(params IRedisSortedSetAsync[] ofSets)
=> AsAsync().StoreFromIntersectAsync(ofSets, token: default);
ValueTask IRedisSortedSetAsync.StoreFromUnionAsync(IRedisSortedSetAsync[] ofSets, CancellationToken token)
=> AsyncClient.StoreUnionFromSortedSetsAsync(setId, ofSets.GetIds(), token).Await();
ValueTask IRedisSortedSetAsync.StoreFromUnionAsync(params IRedisSortedSetAsync[] ofSets)
=> AsAsync().StoreFromUnionAsync(ofSets, token: default);
} | RedisClientSortedSet |
csharp | xunit__xunit | src/xunit.v3.core.tests/Utility/FixtureMappingManagerTests.cs | {
"start": 4015,
"end": 4688
} | class ____(
IMessageSink messageSink,
ITestContextAccessor contextAccessor)
{
public ITestContextAccessor ContextAccessor { get; } = contextAccessor;
public IMessageSink MessageSink { get; } = messageSink;
}
[Fact]
public async ValueTask CallsDispose()
{
var manager = new TestableFixtureMappingManager();
await manager.InitializeAsync(typeof(FixtureWithDispose));
var result = await manager.GetFixture(typeof(FixtureWithDispose));
var typedResult = Assert.IsType<FixtureWithDispose>(result);
Assert.False(typedResult.DisposeCalled);
await manager.DisposeAsync();
Assert.True(typedResult.DisposeCalled);
}
| FixtureWithMessageSinkAndTestContext |
csharp | microsoft__garnet | test/Garnet.test/RespEtagTests.cs | {
"start": 24218,
"end": 41176
} | record ____ 40 bytes here, because they do not have expirations
while (info.ReadOnlyAddress < untilAddress)
{
var key = $"key{i++:00000}";
_ = db.StringSet(key, key);
info = TestUtils.GetStoreAddressInfo(server);
}
}
#endregion
#region Edgecases
[Test]
[TestCase("m", "mo", null)] // RCU with no existing exp on noetag key
[TestCase("mexicanmochawithdoubleespresso", "c", null)] // IPU with no existing exp on noetag key
[TestCase("m", "mo", 30)] // RCU with existing exp on noetag key
[TestCase("mexicanmochawithdoubleespresso", "c", 30)] // IPU with existing exp on noetag key
public void SetIfGreaterWhenExpIsSentForExistingNonEtagKey(string initialValue, string newValue, double? exp)
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var key = "meow-key";
if (exp != null)
db.StringSet(key, initialValue, TimeSpan.FromSeconds(exp.Value));
else
db.StringSet(key, initialValue);
RedisResult[] arrRes = (RedisResult[])db.Execute("SETIFGREATER", key, newValue, 5, "EX", 90);
ClassicAssert.AreEqual(5, (long)arrRes[0]);
ClassicAssert.IsTrue(arrRes[1].IsNull);
var res = db.StringGetWithExpiry(key);
ClassicAssert.AreEqual(newValue, res.Value.ToString());
ClassicAssert.IsTrue(res.Expiry.HasValue);
}
[Test]
[TestCase("m", "mo", null)] // RCU with no existing exp on noetag key
[TestCase("mexicanmochawithdoubleespresso", "c", null)] // IPU with no existing exp on noetag key
[TestCase("m", "mo", 30)] // RCU with existing exp on noetag key
[TestCase("mexicanmochawithdoubleespresso", "c", 30)] // IPU with existing exp on noetag key
public void SetIfMatchWhenExpIsSentForExistingNonEtagKey(string initialValue, string newValue, int? exp)
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var key = "meow-key";
if (exp != null)
db.StringSet(key, initialValue, TimeSpan.FromSeconds(exp.Value));
else
db.StringSet(key, initialValue);
RedisResult[] arrRes = (RedisResult[])db.Execute("SETIFMATCH", key, newValue, 0, "EX", 90);
ClassicAssert.AreEqual(1, (long)arrRes[0]);
ClassicAssert.IsTrue(arrRes[1].IsNull);
var res = db.StringGetWithExpiry(key);
ClassicAssert.AreEqual(newValue, res.Value.ToString());
ClassicAssert.IsTrue(res.Expiry.HasValue);
}
[Test]
public void SetIfMatchSetsKeyValueOnNonExistingKey()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
RedisResult[] result = (RedisResult[])db.Execute("SETIFMATCH", "key", "valueanother", 1, "EX", 3);
ClassicAssert.AreEqual(2, (long)result[0]);
ClassicAssert.IsTrue(result[1].IsNull);
}
[Test]
public void SetIfGreaterSetsKeyValueOnNonExistingKey()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
RedisResult[] result = (RedisResult[])db.Execute("SETIFGREATER", "key", "valueanother", 1, "EX", 3);
ClassicAssert.AreEqual(1, (long)result[0]);
ClassicAssert.IsTrue(result[1].IsNull);
}
[Test]
public void SETOnAlreadyExistingSETDataOverridesItWithInitialEtag()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
RedisResult res = db.Execute("SET", "rizz", "buzz", "WITHETAG");
long etag = (long)res;
ClassicAssert.AreEqual(1, etag);
// update to value to update the etag
RedisResult[] updateRes = (RedisResult[])db.Execute("SETIFMATCH", ["rizz", "fixx", etag.ToString()]);
etag = (long)updateRes[0];
ClassicAssert.AreEqual(2, etag);
ClassicAssert.IsTrue(updateRes[1].IsNull);
// inplace update
res = db.Execute("SET", "rizz", "meow", "WITHETAG");
etag = (long)res;
ClassicAssert.AreEqual(3, etag);
// update to value to update the etag
updateRes = (RedisResult[])db.Execute("SETIFMATCH", ["rizz", "fooo", etag.ToString()]);
etag = (long)updateRes[0];
ClassicAssert.AreEqual(4, etag);
ClassicAssert.IsTrue(updateRes[1].IsNull);
// Copy update
res = db.Execute("SET", ["rizz", "oneofus", "WITHETAG"]);
etag = (long)res;
// now we should do a getwithetag and see the etag as 0
res = db.Execute("SET", ["rizz", "oneofus"]);
ClassicAssert.AreEqual(res.ToString(), "OK");
var getwithetagRes = (RedisResult[])db.Execute("GETWITHETAG", "rizz");
ClassicAssert.AreEqual("0", getwithetagRes[0].ToString());
}
[Test]
public void SETWithWITHETAGOnAlreadyExistingSETDataOverridesItButUpdatesEtag()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
RedisResult res = db.Execute("SET", ["rizz", "buzz", "WITHETAG"]);
long etag = (long)res;
ClassicAssert.AreEqual(1, etag);
// update to value to update the etag
RedisResult[] updateRes = (RedisResult[])db.Execute("SETIFMATCH", ["rizz", "fixx", etag.ToString()]);
etag = (long)updateRes[0];
ClassicAssert.AreEqual(2, etag);
ClassicAssert.IsTrue(updateRes[1].IsNull);
// inplace update
res = db.Execute("SET", ["rizz", "meow", "WITHETAG"]);
etag = (long)res;
ClassicAssert.AreEqual(3, etag);
// update to value to update the etag
updateRes = (RedisResult[])db.Execute("SETIFMATCH", ["rizz", "fooo", etag.ToString()]);
etag = (long)updateRes[0];
ClassicAssert.AreEqual(4, etag);
ClassicAssert.IsTrue(updateRes[1].IsNull);
// Copy update
res = db.Execute("SET", ["rizz", "oneofus", "WITHETAG"]);
etag = (long)res;
ClassicAssert.AreEqual(5, etag);
}
[Test]
public void SETWithWITHETAGOnAlreadyExistingNonEtagDataOverridesItToInitialEtag()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
ClassicAssert.IsTrue(db.StringSet("rizz", "used"));
// inplace update
RedisResult res = db.Execute("SET", ["rizz", "buzz", "WITHETAG"]);
long etag = long.Parse(res.ToString());
ClassicAssert.AreEqual(1, etag);
db.KeyDelete("rizz");
ClassicAssert.IsTrue(db.StringSet("rizz", "my"));
// Copy update
res = db.Execute("SET", ["rizz", "some", "WITHETAG"]);
etag = long.Parse(res.ToString());
ClassicAssert.AreEqual(1, etag);
}
[Test]
public void DelIfGreaterOnNonExistingKeyWorks()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
RedisResult res = db.Execute("DELIFGREATER", "nonexistingkey", 10);
ClassicAssert.AreEqual(0, (long)res);
}
#endregion
#region ETAG Apis with non-etag data
[Test]
public void SETOnAlreadyExistingNonEtagDataOverridesIt()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
ClassicAssert.IsTrue(db.StringSet("rizz", "used"));
// inplace update
RedisResult res = db.Execute("SET", ["rizz", "buzz", "WITHETAG"]);
long etag = long.Parse(res.ToString());
ClassicAssert.AreEqual(1, etag);
res = db.Execute("SET", ["rizz", "buzz", "WITHETAG"]);
etag = long.Parse(res.ToString());
ClassicAssert.AreEqual(2, etag);
db.KeyDelete("rizz");
ClassicAssert.IsTrue(db.StringSet("rizz", "my"));
// Copy update
res = db.Execute("SET", ["rizz", "some", "WITHETAG"]);
etag = long.Parse(res.ToString());
ClassicAssert.AreEqual(1, etag);
}
[Test]
public void SetIfMatchOnNonEtagDataReturnsNewEtagAndNoValue()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var _ = db.StringSet("h", "k");
var res = (RedisResult[])db.Execute("SETIFMATCH", ["h", "t", "0"]);
ClassicAssert.AreEqual("1", res[0].ToString());
ClassicAssert.IsTrue(res[1].IsNull);
}
[Test]
public void SetIfMatchReturnsNewEtagButNoValueWhenUsingNoGet()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var _ = db.StringSet("h", "k");
var res = (RedisResult[])db.Execute("SETIFMATCH", "h", "t", "0", "NOGET");
ClassicAssert.AreEqual("1", res[0].ToString());
ClassicAssert.IsTrue(res[1].IsNull);
// ETag mismatch
res = (RedisResult[])db.Execute("SETIFMATCH", "h", "t", "2", "NOGET");
ClassicAssert.AreEqual("1", res[0].ToString());
ClassicAssert.IsTrue(res[1].IsNull);
}
[Test]
public void GetIfNotMatchOnNonEtagDataReturnsNilForEtagAndCorrectData()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var _ = db.StringSet("h", "k");
var res = (RedisResult[])db.Execute("GETIFNOTMATCH", ["h", "1"]);
ClassicAssert.AreEqual("0", res[0].ToString());
ClassicAssert.AreEqual("k", res[1].ToString());
}
[Test]
public void GetWithEtagOnNonEtagDataReturns0ForEtagAndCorrectData()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
IDatabase db = redis.GetDatabase(0);
var _ = db.StringSet("h", "k");
var res = (RedisResult[])db.Execute("GETWITHETAG", ["h"]);
ClassicAssert.AreEqual("0", res[0].ToString());
ClassicAssert.AreEqual("k", res[1].ToString());
}
#endregion
#region Backwards Compatability Testing
[Test]
public void SingleEtagSetGet()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
string origValue = "abcdefg";
db.Execute("SET", ["mykey", origValue, "WITHETAG"]);
string retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(origValue, retValue);
}
[Test]
public async Task SingleUnicodeEtagSetGetGarnetClient()
{
using var db = TestUtils.GetGarnetClient();
db.Connect();
string origValue = "笑い男";
await db.ExecuteForLongResultAsync("SET", ["mykey", origValue, "WITHETAG"]);
string retValue = await db.StringGetAsync("mykey");
ClassicAssert.AreEqual(origValue, retValue);
}
[Test]
public async Task LargeEtagSetGet()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
const int length = (1 << 19) + 100;
var value = new byte[length];
for (int i = 0; i < length; i++)
value[i] = (byte)((byte)'a' + ((byte)i % 26));
RedisResult res = await db.ExecuteAsync("SET", ["mykey", value, "WITHETAG"]);
long initalEtag = long.Parse(res.ToString());
ClassicAssert.AreEqual(1, initalEtag);
// Backwards compatability of data set with etag and plain GET call
var retvalue = (byte[])await db.StringGetAsync("mykey");
ClassicAssert.IsTrue(new ReadOnlySpan<byte>(value).SequenceEqual(new ReadOnlySpan<byte>(retvalue)));
}
[Test]
public void SetExpiryForEtagSetData()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
string origValue = "abcdefghij";
// set with etag
long initalEtag = long.Parse(db.Execute("SET", ["mykey", origValue, "EX", 2, "WITHETAG"]).ToString());
ClassicAssert.AreEqual(1, initalEtag);
string retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(origValue, retValue, "Get() before expiration");
var actualDbSize = db.Execute("DBSIZE");
ClassicAssert.AreEqual(1, (ulong)actualDbSize, "DBSIZE before expiration");
var actualKeys = db.Execute("KEYS", ["*"]);
ClassicAssert.AreEqual(1, ((RedisResult[])actualKeys).Length, "KEYS before expiration");
var actualScan = db.Execute("SCAN", "0");
ClassicAssert.AreEqual(1, ((RedisValue[])((RedisResult[])actualScan!)[1]).Length, "SCAN before expiration");
Thread.Sleep(2500);
retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(null, retValue, "Get() after expiration");
actualDbSize = db.Execute("DBSIZE");
ClassicAssert.AreEqual(0, (ulong)actualDbSize, "DBSIZE after expiration");
actualKeys = db.Execute("KEYS", ["*"]);
ClassicAssert.AreEqual(0, ((RedisResult[])actualKeys).Length, "KEYS after expiration");
actualScan = db.Execute("SCAN", "0");
ClassicAssert.AreEqual(0, ((RedisValue[])((RedisResult[])actualScan!)[1]).Length, "SCAN after expiration");
}
[Test]
public void SetExpiryHighPrecisionForEtagSetDatat()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
var origValue = "abcdeghijklmno";
// set with etag
long initalEtag = long.Parse(db.Execute("SET", ["mykey", origValue, "PX", 1900, "WITHETAG"]).ToString());
ClassicAssert.AreEqual(1, initalEtag);
string retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(origValue, retValue);
Thread.Sleep(1000);
retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(origValue, retValue);
Thread.Sleep(2000);
retValue = db.StringGet("mykey");
ClassicAssert.AreEqual(null, retValue);
}
[Test]
public void SetExpiryIncrForEtagSetData()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
// Key storing integer
var nVal = -100000;
var strKey = "key1";
db.Execute("SET", [strKey, nVal, "WITHETAG"]);
db.KeyExpire(strKey, TimeSpan.FromSeconds(5));
string res1 = db.StringGet(strKey);
long n = db.StringIncrement(strKey);
// This should increase the ETAG internally so we have a check for that here
var checkEtag = long.Parse(db.Execute("GETWITHETAG", [strKey])[0].ToString());
ClassicAssert.AreEqual(2, checkEtag);
string res = db.StringGet(strKey);
long nRetVal = Convert.ToInt64(res);
ClassicAssert.AreEqual(n, nRetVal);
ClassicAssert.AreEqual(-99999, nRetVal);
n = db.StringIncrement(strKey);
// This should increase the ETAG internally so we have a check for that here
checkEtag = long.Parse(db.Execute("GETWITHETAG", [strKey])[0].ToString());
ClassicAssert.AreEqual(3, checkEtag);
nRetVal = Convert.ToInt64(db.StringGet(strKey));
ClassicAssert.AreEqual(n, nRetVal);
ClassicAssert.AreEqual(-99998, nRetVal);
var res69 = db.KeyTimeToLive(strKey);
Thread.Sleep(5000);
// Expired key, restart increment,after exp this is treated as new | is |
csharp | dotnet__maui | src/Controls/src/Core/PlatformConfiguration/iOSSpecific/ScrollView.cs | {
"start": 245,
"end": 2488
} | public static class ____
{
/// <summary>Bindable property for <see cref="ShouldDelayContentTouches"/>.</summary>
public static readonly BindableProperty ShouldDelayContentTouchesProperty = BindableProperty.Create(nameof(ShouldDelayContentTouches), typeof(bool), typeof(ScrollView), true);
/// <summary>Returns a Boolean value that tells whether iOS will wait to determine if a touch is intended as a scroll, or scroll immediately.</summary>
/// <param name="element">The platform specific element on which to perform the operation.</param>
/// <returns>A Boolean value that tells whether iOS will wait to determine if a touch is intended as a scroll, or scroll immediately.</returns>
public static bool GetShouldDelayContentTouches(BindableObject element)
{
return (bool)element.GetValue(ShouldDelayContentTouchesProperty);
}
/// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/ScrollView.xml" path="//Member[@MemberName='SetShouldDelayContentTouches'][1]/Docs/*" />
public static void SetShouldDelayContentTouches(BindableObject element, bool value)
{
element.SetValue(ShouldDelayContentTouchesProperty, value);
}
/// <summary>Returns a Boolean value that tells whether iOS will wait to determine if a touch is intended as a scroll, or scroll immediately.</summary>
/// <param name="config">The platform specific configuration that contains the element on which to perform the operation.</param>
/// <returns>A Boolean value that tells whether iOS will wait to determine if a touch is intended as a scroll, or scroll immediately.</returns>
public static bool ShouldDelayContentTouches(this IPlatformElementConfiguration<iOS, FormsElement> config)
{
return GetShouldDelayContentTouches(config.Element);
}
/// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/ScrollView.xml" path="//Member[@MemberName='SetShouldDelayContentTouches'][2]/Docs/*" />
public static IPlatformElementConfiguration<iOS, FormsElement> SetShouldDelayContentTouches(this IPlatformElementConfiguration<iOS, FormsElement> config, bool value)
{
SetShouldDelayContentTouches(config.Element, value);
return config;
}
}
}
| ScrollView |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/Primitives/Thumb.cs | {
"start": 2318,
"end": 2724
} | class ____
/// for this event.
/// </summary>
/// <param name="e">Data about the event.</param>
protected virtual void OnDragStarted(VectorEventArgs e)
{
}
/// <summary>
/// Invoked when an unhandled <see cref="DragDeltaEvent"/> reaches an element in its
/// route that is derived from this class. Implement this method to add | handling |
csharp | aspnetboilerplate__aspnetboilerplate | test/Abp.Tests/Threading/LockExtensions_Tests.cs | {
"start": 133,
"end": 608
} | public class ____
{
private readonly List<int> _list;
public LockExtensions_Tests()
{
_list = new List<int> { 1 };
}
[Fact]
public void Test_Locking()
{
//Just sample usages:
_list.Locking(() => { });
_list.Locking(list => { });
_list.Locking(() => 42).ShouldBe(42);
_list.Locking(list => 42).ShouldBe(42);
}
}
}
| LockExtensions_Tests |
csharp | dotnet__aspire | src/Aspire.Hosting/Backchannel/AuxiliaryBackchannelRpcTarget.cs | {
"start": 523,
"end": 5197
} | internal sealed class ____(
ILogger<AuxiliaryBackchannelRpcTarget> logger,
IServiceProvider serviceProvider)
{
private const string McpEndpointName = "mcp";
/// <summary>
/// Gets information about the AppHost for the MCP server.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The AppHost information including the fully qualified path and process ID.</returns>
/// <exception cref="InvalidOperationException">Thrown when AppHost information is not available.</exception>
public Task<AppHostInformation> GetAppHostInformationAsync(CancellationToken cancellationToken = default)
{
// The cancellationToken parameter is not currently used, but is retained for API consistency and potential future support for cancellation.
_ = cancellationToken;
var configuration = serviceProvider.GetService<IConfiguration>();
if (configuration is null)
{
logger.LogError("Configuration not found.");
throw new InvalidOperationException("Configuration not found.");
}
// First try to get the file path (with extension), otherwise fall back to the path (without extension)
var appHostPath = configuration["AppHost:FilePath"] ?? configuration["AppHost:Path"];
if (string.IsNullOrEmpty(appHostPath))
{
logger.LogError("AppHost path not found in configuration.");
throw new InvalidOperationException("AppHost path not found in configuration.");
}
// Get the CLI process ID if the AppHost was launched via the CLI
int? cliProcessId = null;
var cliPidString = configuration[KnownConfigNames.CliProcessId];
if (!string.IsNullOrEmpty(cliPidString) && int.TryParse(cliPidString, out var parsedCliPid))
{
cliProcessId = parsedCliPid;
}
return Task.FromResult(new AppHostInformation
{
AppHostPath = appHostPath,
ProcessId = Environment.ProcessId,
CliProcessId = cliProcessId
});
}
/// <summary>
/// Gets the Dashboard MCP connection information including endpoint URL and API token.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The MCP connection information, or null if the dashboard is not part of the application model.</returns>
public async Task<DashboardMcpConnectionInfo?> GetDashboardMcpConnectionInfoAsync(CancellationToken cancellationToken = default)
{
var appModel = serviceProvider.GetService<DistributedApplicationModel>();
if (appModel is null)
{
logger.LogWarning("Application model not found.");
return null;
}
// Find the dashboard resource
var dashboardResource = appModel.Resources.FirstOrDefault(r =>
string.Equals(r.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName)) as IResourceWithEndpoints;
if (dashboardResource is null)
{
logger.LogDebug("Dashboard resource not found in application model.");
return null;
}
// Get the MCP endpoint from the dashboard resource
var mcpEndpoint = dashboardResource.GetEndpoint(McpEndpointName);
if (!mcpEndpoint.Exists)
{
// Fallback to the frontend endpoint (http/https) as done in DashboardEventHandlers
mcpEndpoint = dashboardResource.GetEndpoint("https");
if (!mcpEndpoint.Exists)
{
mcpEndpoint = dashboardResource.GetEndpoint("http");
}
}
if (!mcpEndpoint.Exists)
{
logger.LogWarning("Dashboard MCP endpoint not found or not allocated.");
return null;
}
var endpointUrl = await mcpEndpoint.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(endpointUrl))
{
logger.LogWarning("Dashboard MCP endpoint URL is not allocated.");
return null;
}
// Get the API key from dashboard options
var dashboardOptions = serviceProvider.GetService<IOptions<DashboardOptions>>();
var mcpApiKey = dashboardOptions?.Value.McpApiKey;
if (string.IsNullOrEmpty(mcpApiKey))
{
logger.LogWarning("Dashboard MCP API key is not available.");
return null;
}
return new DashboardMcpConnectionInfo
{
EndpointUrl = $"{endpointUrl}/mcp",
ApiToken = mcpApiKey
};
}
}
| AuxiliaryBackchannelRpcTarget |
csharp | abpframework__abp | framework/src/Volo.Abp.Authorization/Volo/Abp/Authorization/Permissions/PermissionValueProviderManager.cs | {
"start": 236,
"end": 1622
} | public class ____ : IPermissionValueProviderManager, ISingletonDependency
{
public IReadOnlyList<IPermissionValueProvider> ValueProviders => _lazyProviders.Value;
private readonly Lazy<List<IPermissionValueProvider>> _lazyProviders;
protected AbpPermissionOptions Options { get; }
protected IServiceProvider ServiceProvider { get; }
public PermissionValueProviderManager(
IServiceProvider serviceProvider,
IOptions<AbpPermissionOptions> options)
{
Options = options.Value;
ServiceProvider = serviceProvider;
_lazyProviders = new Lazy<List<IPermissionValueProvider>>(GetProviders, true);
}
protected virtual List<IPermissionValueProvider> GetProviders()
{
var providers = Options
.ValueProviders
.Select(type => (ServiceProvider.GetRequiredService(type) as IPermissionValueProvider)!)
.ToList();
var multipleProviders = providers.GroupBy(p => p.Name).FirstOrDefault(x => x.Count() > 1);
if(multipleProviders != null)
{
throw new AbpException($"Duplicate permission value provider name detected: {multipleProviders.Key}. Providers:{Environment.NewLine}{multipleProviders.Select(p => p.GetType().FullName!).JoinAsString(Environment.NewLine)}");
}
return providers;
}
}
| PermissionValueProviderManager |
csharp | duplicati__duplicati | Duplicati/WebserverCore/Abstractions/ISystemInfoProvider.cs | {
"start": 1318,
"end": 1619
} | public interface ____
{
/// <summary>
/// Gets the system information.
/// </summary>
/// <param name="browserlanguage">The browser language.</param>
/// <returns>The system information.</returns>
Dto.SystemInfoDto GetSystemInfo(CultureInfo? browserlanguage);
}
| ISystemInfoProvider |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/Storage/Metastreams/when_having_multiple_metaevents_in_metastream_and_read_index_is_set_to_keep_last_2.cs | {
"start": 600,
"end": 4028
} | public class
____<TLogFormat, TStreamId> : SimpleDbTestScenario<TLogFormat, TStreamId> {
public when_having_multiple_metaevents_in_metastream_and_read_index_is_set_to_keep_last_2()
: base(metastreamMaxCount: 2) {
}
protected override ValueTask<DbResult> CreateDb(TFChunkDbCreationHelper<TLogFormat, TStreamId> dbCreator, CancellationToken token) {
return dbCreator.Chunk(
Rec.Prepare(0, "$$test", "0", metadata: new StreamMetadata(10, null, null, null, null)),
Rec.Prepare(0, "$$test", "1", metadata: new StreamMetadata(9, null, null, null, null)),
Rec.Prepare(0, "$$test", "2", metadata: new StreamMetadata(8, null, null, null, null)),
Rec.Prepare(0, "$$test", "3", metadata: new StreamMetadata(7, null, null, null, null)),
Rec.Prepare(0, "$$test", "4", metadata: new StreamMetadata(6, null, null, null, null)),
Rec.Commit(0, "$$test"))
.CreateDb(token: token);
}
[Test]
public async Task last_event_read_returns_correct_event() {
var res = await ReadIndex.ReadEvent("$$test", -1, CancellationToken.None);
Assert.AreEqual(ReadEventResult.Success, res.Result);
Assert.AreEqual("4", res.Record.EventType);
}
[Test]
public async Task last_event_stream_number_is_correct() {
Assert.AreEqual(4, await ReadIndex.GetStreamLastEventNumber("$$test", CancellationToken.None));
}
[Test]
public async Task single_event_read_returns_last_two_events() {
Assert.AreEqual(ReadEventResult.NotFound, (await ReadIndex.ReadEvent("$$test", 0, CancellationToken.None)).Result);
Assert.AreEqual(ReadEventResult.NotFound, (await ReadIndex.ReadEvent("$$test", 1, CancellationToken.None)).Result);
Assert.AreEqual(ReadEventResult.NotFound, (await ReadIndex.ReadEvent("$$test", 2, CancellationToken.None)).Result);
var res = await ReadIndex.ReadEvent("$$test", 3, CancellationToken.None);
Assert.AreEqual(ReadEventResult.Success, res.Result);
Assert.AreEqual("3", res.Record.EventType);
res = await ReadIndex.ReadEvent("$$test", 4, CancellationToken.None);
Assert.AreEqual(ReadEventResult.Success, res.Result);
Assert.AreEqual("4", res.Record.EventType);
}
[Test]
public async Task stream_read_forward_returns_last_two_events() {
var res = await ReadIndex.ReadStreamEventsForward("$$test", 0, 100, CancellationToken.None);
Assert.AreEqual(ReadStreamResult.Success, res.Result);
Assert.AreEqual(2, res.Records.Length);
Assert.AreEqual("3", res.Records[0].EventType);
Assert.AreEqual("4", res.Records[1].EventType);
}
[Test]
public async Task stream_read_backward_returns_last_two_events() {
var res = await ReadIndex.ReadStreamEventsBackward("$$test", -1, 100, CancellationToken.None);
Assert.AreEqual(ReadStreamResult.Success, res.Result);
Assert.AreEqual(2, res.Records.Length);
Assert.AreEqual("4", res.Records[0].EventType);
Assert.AreEqual("3", res.Records[1].EventType);
}
[Test]
public async Task metastream_metadata_is_correct() {
var metadata = await ReadIndex.GetStreamMetadata("$$test", CancellationToken.None);
Assert.AreEqual(2, metadata.MaxCount);
Assert.AreEqual(null, metadata.MaxAge);
}
[Test]
public async Task original_stream_metadata_is_taken_from_last_metaevent() {
var metadata = await ReadIndex.GetStreamMetadata("test", CancellationToken.None);
Assert.AreEqual(6, metadata.MaxCount);
Assert.AreEqual(null, metadata.MaxAge);
}
}
| when_having_multiple_metaevents_in_metastream_and_read_index_is_set_to_keep_last_2 |
csharp | dotnet__aspnetcore | src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs | {
"start": 23203,
"end": 23322
} | public enum ____
{
None = 0,
FlushHeaders = 1,
Aborted = 2,
Completed = 4
}
}
| State |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/Renderers/NavigationRenderer.cs | {
"start": 29901,
"end": 31343
} | class ____ : UIToolbar
{
readonly List<UIView> _lines = new List<UIView>();
public SecondaryToolbar()
{
TintColor = UIColor.White;
}
public override UIBarButtonItem[] Items
{
get { return base.Items; }
set
{
base.Items = value;
SetupLines();
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (Items == null || Items.Length == 0)
return;
LayoutToolbarItems(Bounds.Width, Bounds.Height, 0);
}
void LayoutToolbarItems(nfloat toolbarWidth, nfloat toolbarHeight, nfloat padding)
{
var x = padding;
var y = 0;
var itemH = toolbarHeight;
var itemW = toolbarWidth / Items.Length;
foreach (var item in Items)
{
var frame = new RectangleF(x, y, itemW, itemH);
if (frame == item.CustomView.Frame)
continue;
item.CustomView.Frame = frame;
x += itemW + padding;
}
x = itemW + padding * 1.5f;
y = (int)Bounds.GetMidY();
foreach (var l in _lines)
{
l.Center = new PointF(x, y);
x += itemW + padding;
}
}
void SetupLines()
{
_lines.ForEach(l => l.RemoveFromSuperview());
_lines.Clear();
if (Items == null)
return;
for (var i = 1; i < Items.Length; i++)
{
var l = new UIView(new RectangleF(0, 0, 1, 24)) { BackgroundColor = new UIColor(0, 0, 0, 0.2f) };
AddSubview(l);
_lines.Add(l);
}
}
}
| SecondaryToolbar |
csharp | SixLabors__ImageSharp | src/ImageSharp/Processing/ResizeMode.cs | {
"start": 214,
"end": 1438
} | public enum ____
{
/// <summary>
/// Crops the resized image to fit the bounds of its container.
/// </summary>
Crop,
/// <summary>
/// Pads the resized image to fit the bounds of its container.
/// If only one dimension is passed, will maintain the original aspect ratio.
/// </summary>
Pad,
/// <summary>
/// Pads the image to fit the bound of the container without resizing the
/// original source.
/// When downscaling, performs the same functionality as <see cref="Pad"/>
/// </summary>
BoxPad,
/// <summary>
/// Constrains the resized image to fit the bounds of its container maintaining
/// the original aspect ratio.
/// </summary>
Max,
/// <summary>
/// Resizes the image until the shortest side reaches the set given dimension.
/// Upscaling is disabled in this mode and the original image will be returned
/// if attempted.
/// </summary>
Min,
/// <summary>
/// Stretches the resized image to fit the bounds of its container.
/// </summary>
Stretch,
/// <summary>
/// The target location and size of the resized image has been manually set.
/// </summary>
Manual
}
| ResizeMode |
csharp | PrismLibrary__Prism | tests/Prism.Core.Tests/Events/EventBaseFixture.cs | {
"start": 3196,
"end": 3644
} | class ____ : IEventSubscription
{
public Action<object[]> GetPublishActionReturnValue;
public bool GetPublishActionCalled;
public Action<object[]> GetExecutionStrategy()
{
GetPublishActionCalled = true;
return GetPublishActionReturnValue;
}
public SubscriptionToken SubscriptionToken { get; set; }
}
| MockEventSubscription |
csharp | dotnet__aspnetcore | src/Servers/Kestrel/Core/test/MessageBodyTests.cs | {
"start": 53716,
"end": 54892
} | private class ____ : Stream
{
public override void Flush()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await Task.Delay(1);
throw new NotImplementedException();
}
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite => true;
public override long Length { get; }
public override long Position { get; set; }
}
}
| ThrowOnWriteAsynchronousStream |
csharp | abpframework__abp | modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/Rendering/ScribanDocumentSectionRenderer.cs | {
"start": 298,
"end": 5214
} | public class ____ : IDocumentSectionRenderer
{
protected readonly static List<DocsJsonSection> DocsJsonSections =
[
new("````json", "````"),
new("```json", "```")
];
protected const string DocsParam = "//[doc-params]";
protected const string DocsTemplates = "//[doc-template]";
protected const string DocsNav = "//[doc-nav]";
protected const string DocsSeo = "//[doc-seo]";
public ILogger<ScribanDocumentSectionRenderer> Logger { get; set; }
public ScribanDocumentSectionRenderer()
{
Logger = NullLogger<ScribanDocumentSectionRenderer>.Instance;
}
public async Task<string> RenderAsync(
string document,
DocumentRenderParameters parameters = null,
List<DocumentPartialTemplateContent> partialTemplates = null)
{
if (partialTemplates != null && partialTemplates.Any())
{
document = SetPartialTemplates(document, partialTemplates);
}
var scribanTemplate = Template.Parse(document);
if (parameters == null)
{
return await scribanTemplate.RenderAsync();
}
var result = await scribanTemplate.RenderAsync(parameters);
return RemoveOptionsJson(result, DocsParam, DocsNav, DocsSeo);
}
public Task<Dictionary<string, List<string>>> GetAvailableParametersAsync(string document)
{
return GetSectionAsync<Dictionary<string, List<string>>>(document, DocsParam);
}
protected virtual async Task<T> GetSectionAsync<T>(string document, string sectionName) where T : new()
{
try
{
if (!HasJsonSection(document) || !document.Contains(sectionName))
{
return new T();
}
var (jsonBeginningIndex, jsonEndingIndex, insideJsonSection, _) =
GetJsonBeginEndIndexesAndPureJson(document, sectionName);
if (jsonBeginningIndex < 0 || jsonEndingIndex <= 0 || string.IsNullOrWhiteSpace(insideJsonSection))
{
return new T();
}
var pureJson = insideJsonSection.Replace(sectionName, "").Trim();
if (!DocsJsonSerializerHelper.TryDeserialize<T>(pureJson, out var section))
{
throw new UserFriendlyException($"ERROR-20200327: Cannot validate JSON content for `{sectionName}`!");
}
return await Task.FromResult(section);
}
catch (Exception)
{
Logger.LogWarning("Unable to parse parameters of document.");
return new T();
}
}
protected static string RemoveOptionsJson(string document, params string[] sectionNames)
{
foreach (var sectionName in sectionNames)
{
var orgDocument = document;
try
{
if (!HasJsonSection(document) || !document.Contains(sectionName))
{
continue;
}
var (jsonBeginningIndex, jsonEndingIndex, insideJsonSection, jsonSection) =
GetJsonBeginEndIndexesAndPureJson(document, sectionName);
if (jsonBeginningIndex < 0 || jsonEndingIndex <= 0 || string.IsNullOrWhiteSpace(insideJsonSection))
{
continue;
}
document = document.Remove(
jsonBeginningIndex - jsonSection.Opener.Length,
(jsonEndingIndex + jsonSection.Closer.Length) - (jsonBeginningIndex - jsonSection.Opener.Length)
);
}
catch (Exception)
{
document = orgDocument;
}
}
return document;
}
protected static bool HasJsonSection(string document)
{
return DocsJsonSections.Any(section => document.Contains(section.Opener) && document.Contains(section.Closer));
}
protected static (int, int, string, DocsJsonSection) GetJsonBeginEndIndexesAndPureJson(string document, string sectionName)
{
foreach (var section in DocsJsonSections)
{
var (jsonBeginningIndex, jsonEndingIndex, insideJsonSection) =
section.GetJsonBeginEndIndexesAndPureJson(document, sectionName);
if (jsonBeginningIndex >= 0 && jsonEndingIndex > 0 && !string.IsNullOrWhiteSpace(insideJsonSection))
{
return (jsonBeginningIndex, jsonEndingIndex, insideJsonSection, section);
}
}
return (-1, -1, "", null);
}
protected static string SetPartialTemplates(string document, IReadOnlyCollection<DocumentPartialTemplateContent> templates)
{
foreach (var section in DocsJsonSections)
{
document = section.SetPartialTemplates(document, templates);
}
return document;
}
| ScribanDocumentSectionRenderer |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.Dapper/Dapper/Filters/Query/MayHaveTenantDapperQueryFilter.cs | {
"start": 273,
"end": 2925
} | public class ____ : IDapperQueryFilter
{
private readonly ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;
public MayHaveTenantDapperQueryFilter(ICurrentUnitOfWorkProvider currentUnitOfWorkProvider)
{
_currentUnitOfWorkProvider = currentUnitOfWorkProvider;
}
private int? TenantId
{
get
{
DataFilterConfiguration filter = _currentUnitOfWorkProvider.Current.Filters.FirstOrDefault(x => x.FilterName == FilterName);
if (filter.FilterParameters.ContainsKey(AbpDataFilters.Parameters.TenantId))
{
return (int?)filter.FilterParameters[AbpDataFilters.Parameters.TenantId];
}
return null;
}
}
public string FilterName { get; } = AbpDataFilters.MayHaveTenant;
public bool IsEnabled => _currentUnitOfWorkProvider.Current.IsFilterEnabled(FilterName);
public IFieldPredicate ExecuteFilter<TEntity, TPrimaryKey>() where TEntity : class, IEntity<TPrimaryKey>
{
IFieldPredicate predicate = null;
if (typeof(IMayHaveTenant).IsAssignableFrom(typeof(TEntity)) && IsEnabled)
{
predicate = Predicates.Field<TEntity>(f => (f as IMayHaveTenant).TenantId, Operator.Eq, TenantId);
}
return predicate;
}
public Expression<Func<TEntity, bool>> ExecuteFilter<TEntity, TPrimaryKey>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, IEntity<TPrimaryKey>
{
if (typeof(IMayHaveTenant).IsAssignableFrom(typeof(TEntity)) && IsEnabled)
{
PropertyInfo propType = typeof(TEntity).GetProperty(nameof(IMayHaveTenant.TenantId));
if (predicate == null)
{
predicate = ExpressionUtils.MakePredicate<TEntity>(nameof(IMayHaveTenant.TenantId), TenantId, propType.PropertyType);
}
else
{
ParameterExpression paramExpr = predicate.Parameters[0];
MemberExpression memberExpr = Expression.Property(paramExpr, nameof(IMayHaveTenant.TenantId));
BinaryExpression body = Expression.AndAlso(
predicate.Body,
Expression.Equal(memberExpr, Expression.Constant(TenantId, propType.PropertyType)));
predicate = Expression.Lambda<Func<TEntity, bool>>(body, paramExpr);
}
}
return predicate;
}
}
}
| MayHaveTenantDapperQueryFilter |
csharp | dotnet__aspnetcore | src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs | {
"start": 1314,
"end": 2226
} | public class ____<TUser> :
IdentityUserContext<TUser, string>
where TUser : IdentityUser
{
private readonly DbConnection _connection;
private readonly IServiceProvider _serviceProvider;
private InMemoryContext(DbConnection connection, IServiceProvider serviceProvider)
{
_connection = connection;
_serviceProvider = serviceProvider;
}
public static InMemoryContext<TUser> Create(DbConnection connection, IServiceCollection services = null)
{
services = InMemoryContext.ConfigureDbServices(services);
return InMemoryContext.Initialize(new InMemoryContext<TUser>(connection, services.BuildServiceProvider()));
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(_connection);
optionsBuilder.UseApplicationServiceProvider(_serviceProvider);
}
}
| InMemoryContext |
csharp | Cysharp__MemoryPack | src/MemoryPack.Generator/MemoryPackGenerator.cs | {
"start": 3577,
"end": 12348
} | record
____ (node is ClassDeclarationSyntax
or StructDeclarationSyntax
or RecordDeclarationSyntax
or InterfaceDeclarationSyntax);
},
transform: static (context, token) =>
{
return (TypeDeclarationSyntax)context.TargetNode;
})
.WithTrackingName("MemoryPack.MemoryPackable.1_ForAttributeMemoryPackableAttribute");
var typeDeclarations2 = context.SyntaxProvider.ForAttributeWithMetadataName(
MemoryPackUnionFormatterAttributeFullName,
predicate: static (node, token) =>
{
return (node is ClassDeclarationSyntax);
},
transform: static (context, token) =>
{
return (TypeDeclarationSyntax)context.TargetNode;
})
.WithTrackingName("MemoryPack.MemoryPackable.1_ForAttributeMemoryPackUnion");
{
var source = typeDeclarations
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance)
.Combine(logProvider)
.Combine(parseOptions)
.WithTrackingName("MemoryPack.MemoryPackable.2_MemoryPackableCombined");
context.RegisterSourceOutput(source, static (context, source) =>
{
var (typeDeclaration, compilation) = source.Left.Item1;
var logPath = source.Left.Item2;
var (langVersion, net7) = source.Right;
Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7));
});
}
{
var source = typeDeclarations2
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance)
.Combine(logProvider)
.Combine(parseOptions)
.WithTrackingName("MemoryPack.MemoryPackable.2_MemoryPackUnionCombined");
context.RegisterSourceOutput(source, static (context, source) =>
{
var (typeDeclaration, compilation) = source.Left.Item1;
var logPath = source.Left.Item2;
var (langVersion, net7) = source.Right;
Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7));
});
}
}
void RegisterTypeScript(IncrementalGeneratorInitializationContext context)
{
var typeScriptEnabled = context.AnalyzerConfigOptionsProvider
.Select((configOptions, token) =>
{
// https://github.com/dotnet/project-system/blob/main/docs/design-time-builds.md
var isDesignTimeBuild = configOptions.GlobalOptions.TryGetValue("build_property.DesignTimeBuild", out var designTimeBuild) && designTimeBuild == "true";
string? path;
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptOutputDirectory", out path))
{
path = null;
}
string ext;
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptImportExtension", out ext!))
{
ext = ".js";
}
string convertProp;
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptConvertPropertyName", out convertProp!))
{
convertProp = "true";
}
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptEnableNullableTypes", out var enableNullableTypes))
{
enableNullableTypes = "false";
}
if (!bool.TryParse(convertProp, out var convert)) convert = true;
if (path == null) return null;
return new TypeScriptGenerateOptions
{
OutputDirectory = path,
ImportExtension = ext,
ConvertPropertyName = convert,
EnableNullableTypes = bool.TryParse(enableNullableTypes, out var enabledNullableTypesParsed) && enabledNullableTypesParsed,
IsDesignTimeBuild = isDesignTimeBuild
};
});
var typeScriptDeclarations = context.SyntaxProvider.ForAttributeWithMetadataName(
GenerateTypeScriptAttributeFullName,
predicate: static (node, token) =>
{
return (node is ClassDeclarationSyntax
or RecordDeclarationSyntax
or InterfaceDeclarationSyntax);
},
transform: static (context, token) =>
{
return (TypeDeclarationSyntax)context.TargetNode;
});
var typeScriptGenerateSource = typeScriptDeclarations
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance)
.Combine(typeScriptEnabled)
.Where(x => x.Right != null) // filter
.Collect();
context.RegisterSourceOutput(typeScriptGenerateSource, static (context, source) =>
{
ReferenceSymbols? reference = null;
string? generatePath = null;
var unionMap = new Dictionary<ITypeSymbol, ITypeSymbol>(SymbolEqualityComparer.Default); // <impl, base>
foreach (var item in source)
{
var tsOptions = item.Right;
if (tsOptions == null) continue;
if (tsOptions.IsDesignTimeBuild) continue; // designtime build(in IDE), do nothing.
var syntax = item.Left.Item1;
var compilation = item.Left.Item2;
var semanticModel = compilation.GetSemanticModel(syntax.SyntaxTree);
var typeSymbol = semanticModel.GetDeclaredSymbol(syntax, context.CancellationToken) as ITypeSymbol;
if (typeSymbol == null) continue;
if (reference == null)
{
reference = new ReferenceSymbols(compilation);
}
if (generatePath is null && item.Right is { } options)
{
generatePath = options.OutputDirectory;
}
var isUnion = typeSymbol.ContainsAttribute(reference.MemoryPackUnionAttribute);
if (isUnion)
{
var unionTags = typeSymbol.GetAttributes()
.Where(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, reference.MemoryPackUnionAttribute))
.Where(x => x.ConstructorArguments.Length == 2)
.Select(x => (INamedTypeSymbol)x.ConstructorArguments[1].Value!);
foreach (var implType in unionTags)
{
unionMap[implType] = typeSymbol;
}
}
}
if (generatePath != null)
{
var collector = new TypeCollector();
foreach (var item in source)
{
var typeDeclaration = item.Left.Item1;
var compilation = item.Left.Item2;
if (reference == null)
{
reference = new ReferenceSymbols(compilation);
}
var meta = GenerateTypeScript(typeDeclaration, compilation, item.Right!, context, reference, unionMap);
if (meta != null)
{
collector.Visit(meta, false);
}
}
GenerateEnums(collector.GetEnums(), generatePath);
// generate runtime
var runtime = new[]{
("MemoryPackWriter.ts", TypeScriptRuntime.MemoryPackWriter),
("MemoryPackReader.ts", TypeScriptRuntime.MemoryPackReader),
};
foreach (var item in runtime)
{
var filePath = Path.Combine(generatePath, item.Item1);
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, item.Item2, new UTF8Encoding(false));
}
}
}
});
}
| return |
csharp | CommunityToolkit__Maui | src/CommunityToolkit.Maui.Core/Primitives/TouchInteractionStatusChangedEventArgs.shared.cs | {
"start": 126,
"end": 408
} | public class ____(TouchInteractionStatus touchInteractionStatus) : EventArgs
{
/// <summary>
/// Gets the current touch interaction status.
/// </summary>
public TouchInteractionStatus TouchInteractionStatus { get; } = touchInteractionStatus;
} | TouchInteractionStatusChangedEventArgs |
csharp | dotnetcore__WTM | src/WalkingTec.Mvvm.Core/Support/ClaimComparer.cs | {
"start": 198,
"end": 347
} | public class ____ : EqualityComparer<Claim>
{
/// <summary>
/// Claim comparison options
/// </summary>
| ClaimComparer |
csharp | dotnet__efcore | src/ef/Commands/DbContextScriptCommand.Configure.cs | {
"start": 290,
"end": 665
} | internal partial class ____ : ContextCommandBase
{
private CommandOption? _output;
public override void Configure(CommandLineApplication command)
{
command.Description = Resources.DbContextScriptDescription;
_output = command.Option("-o|--output <FILE>", Resources.OutputDescription);
base.Configure(command);
}
}
| DbContextScriptCommand |
csharp | simplcommerce__SimplCommerce | src/Modules/SimplCommerce.Module.Catalog/Models/ProductOption.cs | {
"start": 142,
"end": 462
} | public class ____ : EntityBase
{
public ProductOption()
{
}
public ProductOption(long id)
{
Id = id;
}
[Required(ErrorMessage = "The {0} field is required.")]
[StringLength(450)]
public string Name { get; set; }
}
}
| ProductOption |
csharp | Cysharp__MemoryPack | src/MemoryPack.Unity/Assets/MemoryPack.Unity/Runtime/UnityFormatters.cs | {
"start": 1446,
"end": 2879
} | internal sealed class ____ : MemoryPackFormatter<Gradient>
{
[Preserve]
public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref Gradient? value)
{
if (value == null)
{
writer.WriteNullObjectHeader();
return;
}
writer.WriteObjectHeader(3);
writer.WriteUnmanagedArray(value.@colorKeys);
writer.WriteUnmanagedArray(value.@alphaKeys);
writer.WriteUnmanaged(value.@mode);
}
[Preserve]
public override void Deserialize(ref MemoryPackReader reader, ref Gradient? value)
{
if (!reader.TryReadObjectHeader(out var count))
{
value = null;
return;
}
if (count != 3) MemoryPackSerializationException.ThrowInvalidPropertyCount(3, count);
var colorKeys = reader.ReadUnmanagedArray<global::UnityEngine.GradientColorKey>();
var alphaKeys = reader.ReadUnmanagedArray<global::UnityEngine.GradientAlphaKey>();
reader.ReadUnmanaged(out GradientMode mode);
if (value == null)
{
value = new Gradient();
}
value.colorKeys = colorKeys;
value.alphaKeys = alphaKeys;
value.mode = mode;
}
}
[Preserve]
| GradientFormatter |
csharp | Antaris__RazorEngine | src/source/RazorEngine.Core/Compilation/ReferenceResolver/CompilerReference.cs | {
"start": 11041,
"end": 11931
} | public class ____ : CompilerReference
{
/// <summary>
/// The referenced file.
/// </summary>
public string File { get; private set; }
internal FileReference(string file)
: base(CompilerReferenceType.FileReference)
{
File = new System.Uri(Path.GetFullPath(file)).LocalPath;
}
/// <summary>
/// Visit the given visitor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="visitor"></param>
/// <returns></returns>
public override T Visit<T>(ICompilerReferenceVisitor<T> visitor)
{
return visitor.Visit(File);
}
}
/// <summary>
/// A direct assembly reference.
/// </summary>
| FileReference |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedAssertDifferentLsidOnLastTwoCommandsOperation.cs | {
"start": 784,
"end": 1487
} | public class ____ : IUnifiedSpecialTestOperation
{
private readonly EventCapturer _eventCapturer;
public UnifiedAssertDifferentLsidOnLastTwoCommandsOperation(EventCapturer eventCapturer)
{
_eventCapturer = eventCapturer;
}
public void Execute()
{
var lastTwoLsids = _eventCapturer
.Events
.Skip(_eventCapturer.Events.Count - 2)
.Select(commandStartedEvent => ((CommandStartedEvent)commandStartedEvent).Command["lsid"])
.ToList();
lastTwoLsids[0].Should().NotBe(lastTwoLsids[1]);
}
}
| UnifiedAssertDifferentLsidOnLastTwoCommandsOperation |
csharp | louthy__language-ext | LanguageExt.Parsec/Exceptions.cs | {
"start": 91,
"end": 408
} | public class ____ : Exception
{
public ParserException()
{
}
public ParserException(string message) : base(message)
{
}
public ParserException(string message, Exception innerException) : base(message, innerException)
{
}
}
} | ParserException |
csharp | Testably__Testably.Abstractions | Tests/Testably.Abstractions.Testing.Tests/FileSystem/FileStreamFactoryMockTests.SafeFileHandle.cs | {
"start": 262,
"end": 3430
} | partial class ____
{
[Theory]
[AutoData]
public void MissingFile_ShouldThrowFileNotFoundException(
string path, string contents)
{
Skip.If(Test.IsNetFramework);
path = RealFileSystem.Path.GetFullPath(path);
RealFileSystem.File.WriteAllText(path, contents);
using SafeFileHandle handle = UnmanagedFileLoader.CreateSafeFileHandle(path);
handle.IsInvalid.Should().BeFalse();
MockFileSystem.WithSafeFileHandleStrategy(
new DefaultSafeFileHandleStrategy(_ => new SafeFileHandleMock(path)));
Exception? exception = Record.Exception(() =>
{
// ReSharper disable once AccessToDisposedClosure
MockFileSystem.FileStream.New(handle, FileAccess.Read);
});
exception.Should().BeOfType<FileNotFoundException>()
.Which.Message.Should().Contain($"'{MockFileSystem.Path.GetFullPath(path)}'");
}
[Theory]
[AutoData]
public void UnregisteredFileHandle_ShouldThrowNotSupportedException(
string path, string contents)
{
path = RealFileSystem.Path.GetFullPath(path);
RealFileSystem.File.WriteAllText(path, contents);
using SafeFileHandle handle = UnmanagedFileLoader.CreateSafeFileHandle(path);
handle.IsInvalid.Should().BeFalse();
Exception? exception = Record.Exception(() =>
{
// ReSharper disable once AccessToDisposedClosure
MockFileSystem.FileStream.New(handle, FileAccess.Read);
});
exception.Should().BeOfType<NotSupportedException>()
.Which.Message.Should().Contain(nameof(MockFileSystem) + "." +
nameof(MockFileSystem.WithSafeFileHandleStrategy));
}
[Theory]
[AutoData]
public void UnregisteredFileHandle_WithBufferSize_ShouldThrowNotSupportedException(
string path, string contents, int bufferSize)
{
path = RealFileSystem.Path.GetFullPath(path);
RealFileSystem.File.WriteAllText(path, contents);
using SafeFileHandle handle = UnmanagedFileLoader.CreateSafeFileHandle(path);
handle.IsInvalid.Should().BeFalse();
Exception? exception = Record.Exception(() =>
{
// ReSharper disable once AccessToDisposedClosure
MockFileSystem.FileStream.New(handle, FileAccess.Read, bufferSize);
});
exception.Should().BeOfType<NotSupportedException>()
.Which.Message.Should().Contain(nameof(MockFileSystem) + "." +
nameof(MockFileSystem.WithSafeFileHandleStrategy));
}
[Theory]
[AutoData]
public void
UnregisteredFileHandle_WithBufferSizeAndIsAsync_ShouldThrowNotSupportedException(
string path, string contents, int bufferSize, bool isAsync)
{
path = RealFileSystem.Path.GetFullPath(path);
RealFileSystem.File.WriteAllText(path, contents);
using SafeFileHandle handle = UnmanagedFileLoader.CreateSafeFileHandle(path);
handle.IsInvalid.Should().BeFalse();
Exception? exception = Record.Exception(() =>
{
// ReSharper disable once AccessToDisposedClosure
MockFileSystem.FileStream.New(handle, FileAccess.Read, bufferSize, isAsync);
});
exception.Should().BeOfType<NotSupportedException>()
.Which.Message.Should().Contain(nameof(MockFileSystem) + "." +
nameof(MockFileSystem.WithSafeFileHandleStrategy));
}
}
#endif
| FileStreamFactoryMockTests |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition/RectangleClip.cs | {
"start": 297,
"end": 7483
} | public partial class ____ : global::Windows.UI.Composition.CompositionClip
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal RectangleClip()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 TopRightRadius
{
get
{
throw new global::System.NotImplementedException("The member Vector2 RectangleClip.TopRightRadius is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20RectangleClip.TopRightRadius");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "Vector2 RectangleClip.TopRightRadius");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 TopLeftRadius
{
get
{
throw new global::System.NotImplementedException("The member Vector2 RectangleClip.TopLeftRadius is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20RectangleClip.TopLeftRadius");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "Vector2 RectangleClip.TopLeftRadius");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public float Top
{
get
{
throw new global::System.NotImplementedException("The member float RectangleClip.Top is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=float%20RectangleClip.Top");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "float RectangleClip.Top");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public float Right
{
get
{
throw new global::System.NotImplementedException("The member float RectangleClip.Right is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=float%20RectangleClip.Right");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "float RectangleClip.Right");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public float Left
{
get
{
throw new global::System.NotImplementedException("The member float RectangleClip.Left is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=float%20RectangleClip.Left");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "float RectangleClip.Left");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 BottomRightRadius
{
get
{
throw new global::System.NotImplementedException("The member Vector2 RectangleClip.BottomRightRadius is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20RectangleClip.BottomRightRadius");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "Vector2 RectangleClip.BottomRightRadius");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Numerics.Vector2 BottomLeftRadius
{
get
{
throw new global::System.NotImplementedException("The member Vector2 RectangleClip.BottomLeftRadius is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Vector2%20RectangleClip.BottomLeftRadius");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "Vector2 RectangleClip.BottomLeftRadius");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public float Bottom
{
get
{
throw new global::System.NotImplementedException("The member float RectangleClip.Bottom is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=float%20RectangleClip.Bottom");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.RectangleClip", "float RectangleClip.Bottom");
}
}
#endif
// Forced skipping of method Windows.UI.Composition.RectangleClip.Bottom.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.Bottom.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.BottomLeftRadius.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.BottomLeftRadius.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.BottomRightRadius.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.BottomRightRadius.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.Left.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.Left.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.Right.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.Right.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.Top.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.Top.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.TopLeftRadius.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.TopLeftRadius.set
// Forced skipping of method Windows.UI.Composition.RectangleClip.TopRightRadius.get
// Forced skipping of method Windows.UI.Composition.RectangleClip.TopRightRadius.set
}
}
| RectangleClip |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Commands/Models/News/InsertNewsCommentCommand.cs | {
"start": 114,
"end": 273
} | public class ____ : IRequest<NewsComment>
{
public NewsItem NewsItem { get; set; }
public AddNewsCommentModel Model { get; set; }
} | InsertNewsCommentCommand |
csharp | FastEndpoints__FastEndpoints | Src/Library/Endpoint/Processor/IPreProcessorContext.cs | {
"start": 1024,
"end": 1219
} | interface ____ a pre-processor context with a specific type for the request.
/// </summary>
/// <typeparam name="TRequest">The type of the request object, which must be non-nullable.</typeparam>
| for |
csharp | dotnetcore__FreeSql | Extensions/FreeSql.Extensions.Linq/FreeSqlExtensionsLinq.cs | {
"start": 296,
"end": 2570
} | public static class ____
{
/// <summary>
/// 将 ISelect<T1> 转换为 IQueryable<T1><para></para>
/// 用于扩展如:abp IRepository GetAll() 接口方法需要返回 IQueryable 对象<para></para>
/// 提示:IQueryable 方法污染严重,查询功能的实现也不理想,应尽量避免此转换<para></para>
/// IQueryable<T1> 扩展方法 RestoreToSelect() 可以还原为 ISelect<T1>
/// </summary>
/// <returns></returns>
public static IQueryable<T1> AsQueryable<T1>(this ISelect<T1> that) where T1 : class
{
return new QueryableProvider<T1, T1>(that as Select1Provider<T1>);
}
/// <summary>
/// 将 IQueryable<T1> 转换为 ISelect<T1><para></para>
/// 前提:IQueryable 必须由 FreeSql.Extensions.Linq.QueryableProvider 实现
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="that"></param>
/// <returns></returns>
public static ISelect<T1> RestoreToSelect<T1>(this IQueryable<T1> that) where T1 : class
{
var queryable = that as QueryableProvider<T1, T1> ?? throw new Exception(CoreErrorStrings.S_CannotBeConverted_To_ISelect(typeof(T1).Name));
return queryable._select;
}
/// <summary>
/// 【linq to sql】专用扩展方法,不建议直接使用
/// </summary>
public static ISelect<TReturn> Select<T1, TReturn>(this ISelect<T1> that, Expression<Func<T1, TReturn>> select)
{
var s1p = that as Select1Provider<T1>;
if (typeof(TReturn) == typeof(T1)) return that as ISelect<TReturn>;
s1p._tables[0].Parameter = select.Parameters[0];
s1p._selectExpression = select.Body;
if (s1p._orm.CodeFirst.IsAutoSyncStructure)
(s1p._orm.CodeFirst as CodeFirstProvider)._dicSycedTryAdd(typeof(TReturn)); //._dicSyced.TryAdd(typeof(TReturn), true);
var ret = (s1p._orm as BaseDbProvider).CreateSelectProvider<TReturn>(null) as Select1Provider<TReturn>;
Select0Provider.CopyData(s1p, ret, null);
return ret;
}
/// <summary>
/// 【linq to sql】专用扩展方法,不建议直接使用
/// </summary>
public static ISelect<TResult> Join<T1, TInner, TKey, TResult>(this ISelect<T1> that, ISelect<TInner> inner, Expression<Func<T1, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<T1, TInner, TResult>> resultSelector) where T1 : | FreeSqlExtensionsLinqSql |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Server.Tests/ProxyFeatureTests.cs | {
"start": 9915,
"end": 10005
} | public partial class ____
: TechnologyBase
{
}
| Technology |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 244932,
"end": 246968
} | public partial class ____ : global::System.IEquatable<FetchConfiguration_FusionConfigurationByApiId_FusionConfiguration>, IFetchConfiguration_FusionConfigurationByApiId_FusionConfiguration
{
public FetchConfiguration_FusionConfigurationByApiId_FusionConfiguration(global::System.String downloadUrl, global::System.String tag)
{
DownloadUrl = downloadUrl;
Tag = tag;
}
public global::System.String DownloadUrl { get; }
public global::System.String Tag { get; }
public virtual global::System.Boolean Equals(FetchConfiguration_FusionConfigurationByApiId_FusionConfiguration? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (DownloadUrl.Equals(other.DownloadUrl)) && Tag.Equals(other.Tag);
}
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((FetchConfiguration_FusionConfigurationByApiId_FusionConfiguration)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * DownloadUrl.GetHashCode();
hash ^= 397 * Tag.GetHashCode();
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| FetchConfiguration_FusionConfigurationByApiId_FusionConfiguration |
csharp | abpframework__abp | modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs | {
"start": 169,
"end": 901
} | public interface ____ : IBasicRepository<IdentityLinkUser, Guid>
{
Task<IdentityLinkUser> FindAsync(
IdentityLinkUserInfo sourceLinkUserInfo,
IdentityLinkUserInfo targetLinkUserInfo,
CancellationToken cancellationToken = default);
Task<List<IdentityLinkUser>> GetListAsync(
IdentityLinkUserInfo linkUserInfo,
List<IdentityLinkUserInfo> excludes = null,
CancellationToken cancellationToken = default);
Task<List<IdentityLinkUser>> GetListAsync(
int batchSize,
CancellationToken cancellationToken = default);
Task DeleteAsync(
IdentityLinkUserInfo linkUserInfo,
CancellationToken cancellationToken = default);
}
| IIdentityLinkUserRepository |
csharp | dotnet__efcore | src/Shared/ExpressionVisitorExtensions.cs | {
"start": 295,
"end": 4494
} | internal static class ____
{
/// <summary>
/// Dispatches the list of expressions to one of the more specialized visit methods in this class.
/// </summary>
/// <param name="visitor">The expression visitor.</param>
/// <param name="nodes">The expressions to visit.</param>
/// <returns>
/// The modified expression list, if any of the elements were modified; otherwise, returns the original expression list.
/// </returns>
public static IReadOnlyList<Expression> Visit(this ExpressionVisitor visitor, IReadOnlyList<Expression> nodes)
{
Expression[]? newNodes = null;
for (int i = 0, n = nodes.Count; i < n; i++)
{
var node = visitor.Visit(nodes[i]);
if (newNodes is not null)
{
newNodes[i] = node;
}
else if (!ReferenceEquals(node, nodes[i]))
{
newNodes = new Expression[n];
for (var j = 0; j < i; j++)
{
newNodes[j] = nodes[j];
}
newNodes[i] = node;
}
}
return newNodes ?? nodes;
}
/// <summary>
/// Visits an expression, casting the result back to the original expression type.
/// </summary>
/// <typeparam name="T">The type of the expression.</typeparam>
/// <param name="visitor">The expression visitor.</param>
/// <param name="nodes">The expression to visit.</param>
/// <param name="callerName">The name of the calling method; used to report a better error message.</param>
/// <returns>
/// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression.
/// </returns>
/// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception>
public static IReadOnlyList<T> VisitAndConvert<T>(
this ExpressionVisitor visitor,
IReadOnlyList<T> nodes,
[CallerMemberName] string? callerName = null)
where T : Expression
{
T[]? newNodes = null;
for (int i = 0, n = nodes.Count; i < n; i++)
{
if (visitor.Visit(nodes[i]) is not T node)
{
throw new InvalidOperationException(CoreStrings.MustRewriteToSameNode(callerName, typeof(T).Name));
}
if (newNodes is not null)
{
newNodes[i] = node;
}
else if (!ReferenceEquals(node, nodes[i]))
{
newNodes = new T[n];
for (var j = 0; j < i; j++)
{
newNodes[j] = nodes[j];
}
newNodes[i] = node;
}
}
return newNodes ?? nodes;
}
/// <summary>
/// Visits all nodes in the collection using a specified element visitor.
/// </summary>
/// <typeparam name="T">The type of the nodes.</typeparam>
/// <param name="visitor">The expression visitor.</param>
/// <param name="nodes">The nodes to visit.</param>
/// <param name="elementVisitor">
/// A delegate that visits a single element,
/// optionally replacing it with a new element.
/// </param>
/// <returns>
/// The modified node list, if any of the elements were modified;
/// otherwise, returns the original node list.
/// </returns>
public static IReadOnlyList<T> Visit<T>(this ExpressionVisitor visitor, IReadOnlyList<T> nodes, Func<T, T> elementVisitor)
{
T[]? newNodes = null;
for (int i = 0, n = nodes.Count; i < n; i++)
{
var node = elementVisitor(nodes[i]);
if (newNodes is not null)
{
newNodes[i] = node;
}
else if (!ReferenceEquals(node, nodes[i]))
{
newNodes = new T[n];
for (var j = 0; j < i; j++)
{
newNodes[j] = nodes[j];
}
newNodes[i] = node;
}
}
return newNodes ?? nodes;
}
}
| ExpressionVisitorExtensions |
csharp | AvaloniaUI__Avalonia | src/Markup/Avalonia.Markup/Markup/Parsers/PropertyPathGrammar.cs | {
"start": 7782,
"end": 8293
} | public class ____ : ISyntax
{
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is CastTypeSyntax other
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
}
}
| CastTypeSyntax |
csharp | smartstore__Smartstore | src/Smartstore.Web.Common/Modelling/InvariantFloatingPointTypeModelBinderProvider.cs | {
"start": 392,
"end": 1126
} | public class ____ : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
Guard.NotNull(context, nameof(context));
var modelType = context.Metadata.UnderlyingOrModelType;
if (modelType == typeof(decimal))
{
return new InvariantDecimalModelBinder();
}
if (modelType == typeof(double))
{
return new InvariantDoubleModelBinder();
}
if (modelType == typeof(float))
{
return new InvariantFloatModelBinder();
}
return null;
}
}
| InvariantFloatingPointTypeModelBinderProvider |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Types/TypeSelectorSpecs.cs | {
"start": 621,
"end": 24564
} | public class ____
{
[Fact]
public void When_type_selector_is_created_with_a_null_type_it_should_throw()
{
// Arrange
TypeSelector propertyInfoSelector;
// Act
Action act = () => propertyInfoSelector = new TypeSelector((Type)null);
// Assert
act.Should().ThrowExactly<ArgumentNullException>()
.WithParameterName("types");
}
[Fact]
public void When_type_selector_is_created_with_a_null_type_list_it_should_throw()
{
// Arrange
TypeSelector propertyInfoSelector;
// Act
Action act = () => propertyInfoSelector = new TypeSelector((Type[])null);
// Assert
act.Should().ThrowExactly<ArgumentNullException>()
.WithParameterName("types");
}
[Fact]
public void When_type_selector_is_null_then_should_should_throw()
{
// Arrange
TypeSelector propertyInfoSelector = null;
// Act
var act = () => propertyInfoSelector.Should();
// Assert
act.Should().ThrowExactly<ArgumentNullException>()
.WithParameterName("typeSelector");
}
[Fact]
public void When_selecting_types_that_derive_from_a_specific_class_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassDerivedFromSomeBaseClass).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatDeriveFrom<SomeBaseClass>();
// Assert
types.Should().ContainSingle()
.Which.Should().Be(typeof(ClassDerivedFromSomeBaseClass));
}
[Fact]
public void When_selecting_types_that_derive_from_a_specific_generic_class_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassDerivedFromSomeGenericBaseClass).Assembly;
// Act
TypeSelector types = AllTypes.From(assembly).ThatDeriveFrom<SomeGenericBaseClass<int>>();
// Assert
types.ToArray().Should().ContainSingle()
.Which.Should().Be(typeof(ClassDerivedFromSomeGenericBaseClass));
}
[Fact]
public void When_selecting_types_that_do_not_derive_from_a_specific_class_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassDerivedFromSomeBaseClass).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.Main.Test")
.ThatDoNotDeriveFrom<SomeBaseClass>();
// Assert
types.Should()
.HaveCount(12);
}
[Fact]
public void When_selecting_types_that_do_not_derive_from_a_specific_generic_class_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassDerivedFromSomeGenericBaseClass).Assembly;
// Act
TypeSelector types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.Main.Test")
.ThatDoNotDeriveFrom<SomeGenericBaseClass<int>>();
// Assert
types.ToArray().Should()
.HaveCount(12);
}
[Fact]
public void When_selecting_types_that_implement_a_specific_interface_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassImplementingSomeInterface).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatImplement<ISomeInterface>();
// Assert
types.Should()
.HaveCount(2)
.And.Contain(typeof(ClassImplementingSomeInterface))
.And.Contain(typeof(ClassWithSomeAttributeThatImplementsSomeInterface));
}
[Fact]
public void When_selecting_types_that_do_not_implement_a_specific_interface_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassImplementingSomeInterface).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.Main.Test")
.ThatDoNotImplement<ISomeInterface>();
// Assert
types.Should()
.HaveCount(10);
}
[Fact]
public void When_selecting_types_that_are_decorated_with_a_specific_attribute_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatAreDecoratedWith<SomeAttribute>();
// Assert
types.Should()
.HaveCount(2)
.And.Contain(typeof(ClassWithSomeAttribute))
.And.Contain(typeof(ClassWithSomeAttributeThatImplementsSomeInterface));
}
[Fact]
public void When_selecting_types_that_are_not_decorated_with_a_specific_attribute_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatAreNotDecoratedWith<SomeAttribute>();
// Assert
types.Should()
.NotBeEmpty()
.And.NotContain(typeof(ClassWithSomeAttribute))
.And.NotContain(typeof(ClassWithSomeAttributeThatImplementsSomeInterface));
}
[Fact]
public void When_selecting_types_from_specific_namespace_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatAreInNamespace("Internal.Other.Test");
// Assert
types.Should().ContainSingle()
.Which.Should().Be(typeof(SomeOtherClass));
}
[Fact]
public void When_selecting_types_other_than_from_specific_namespace_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreUnderNamespace("Internal.Other")
.ThatAreNotInNamespace("Internal.Other.Test");
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(SomeCommonClass));
}
[Fact]
public void When_selecting_types_from_specific_namespace_or_sub_namespaces_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly).ThatAreUnderNamespace("Internal.Other.Test");
// Assert
types.Should()
.HaveCount(2)
.And.Contain(typeof(SomeOtherClass))
.And.Contain(typeof(SomeCommonClass));
}
[Fact]
public void When_selecting_types_other_than_from_specific_namespace_or_sub_namespaces_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreUnderNamespace("Internal.Other")
.ThatAreNotUnderNamespace("Internal.Other.Test");
// Assert
types.Should()
.BeEmpty();
}
[Fact]
public void When_combining_type_selection_filters_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(ClassWithSomeAttribute).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreDecoratedWith<SomeAttribute>()
.ThatImplement<ISomeInterface>()
.ThatAreInNamespace("Internal.Main.Test");
// Assert
types.Should().ContainSingle()
.Which.Should().Be(typeof(ClassWithSomeAttributeThatImplementsSomeInterface));
}
[Fact]
public void When_using_the_single_type_ctor_of_TypeSelector_it_should_contain_that_singe_type()
{
// Arrange
Type type = typeof(ClassWithSomeAttribute);
// Act
var typeSelector = new TypeSelector(type);
// Assert
typeSelector
.ToArray()
.Should()
.ContainSingle()
.Which.Should().Be(type);
}
[Fact]
public void When_selecting_types_decorated_with_an_inheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreDecoratedWith<SomeAttribute>();
// Assert
types.Should().BeEmpty();
}
[Fact]
public void
When_selecting_types_decorated_with_or_inheriting_an_inheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreDecoratedWithOrInherit<SomeAttribute>();
// Assert
types.Should().ContainSingle();
}
[Fact]
public void When_selecting_types_not_decorated_with_an_inheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreNotDecoratedWith<SomeAttribute>();
// Assert
types.Should().ContainSingle();
}
[Fact]
public void
When_selecting_types_not_decorated_with_or_inheriting_an_inheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreNotDecoratedWithOrInherit<SomeAttribute>();
// Assert
types.Should().BeEmpty();
}
[Fact]
public void When_selecting_types_decorated_with_a_noninheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeNonInheritableAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreDecoratedWith<SomeAttribute>();
// Assert
types.Should().BeEmpty();
}
[Fact]
public void
When_selecting_types_decorated_with_or_inheriting_a_noninheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeNonInheritableAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreDecoratedWithOrInherit<SomeAttribute>();
// Assert
types.Should().BeEmpty();
}
[Fact]
public void
When_selecting_types_not_decorated_with_a_noninheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeNonInheritableAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreNotDecoratedWith<SomeAttribute>();
// Assert
types.Should().ContainSingle();
}
[Fact]
public void
When_selecting_types_not_decorated_with_or_inheriting_a_noninheritable_attribute_it_should_only_return_the_applicable_types()
{
// Arrange
Type type = typeof(ClassWithSomeNonInheritableAttributeDerived);
// Act
IEnumerable<Type> types = type.Types().ThatAreNotDecoratedWithOrInherit<SomeAttribute>();
// Assert
types.Should().ContainSingle();
}
[Fact]
public void When_selecting_global_types_from_global_namespace_it_should_succeed()
{
// Arrange
TypeSelector types = new[] { typeof(ClassInGlobalNamespace) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreUnderNamespace(null);
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().ContainSingle();
}
[Fact]
public void When_selecting_global_types_not_from_global_namespace_it_should_succeed()
{
// Arrange
TypeSelector types = new[] { typeof(ClassInGlobalNamespace) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreNotUnderNamespace(null);
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().BeEmpty();
}
[Fact]
public void When_selecting_local_types_from_global_namespace_it_should_succeed()
{
// Arrange
TypeSelector types = new[] { typeof(SomeBaseClass) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreUnderNamespace(null);
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().ContainSingle();
}
[Fact]
public void When_selecting_local_types_not_from_global_namespace_it_should_succeed()
{
// Arrange
TypeSelector types = new[] { typeof(SomeBaseClass) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreNotUnderNamespace(null);
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().BeEmpty();
}
[Fact]
public void When_selecting_a_prefix_of_a_namespace_it_should_not_match()
{
// Arrange
TypeSelector types = new[] { typeof(SomeBaseClass) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreUnderNamespace("Internal.Main.Tes");
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().BeEmpty();
}
[Fact]
public void When_deselecting_a_prefix_of_a_namespace_it_should_not_match()
{
// Arrange
TypeSelector types = new[] { typeof(SomeBaseClass) }.Types();
// Act
TypeSelector filteredTypes = types.ThatAreNotUnderNamespace("Internal.Main.Tes");
// Assert
filteredTypes.As<IEnumerable<Type>>().Should().ContainSingle();
}
[Fact]
public void When_selecting_types_that_are_classes_it_should_return_the_correct_types()
{
// Arrange
TypeSelector types = new[]
{
typeof(NotOnlyClassesClass), typeof(NotOnlyClassesEnumeration), typeof(INotOnlyClassesInterface)
}.Types();
// Act
IEnumerable<Type> filteredTypes = types.ThatAreClasses();
// Assert
filteredTypes.Should()
.ContainSingle()
.Which.Should().Be(typeof(NotOnlyClassesClass));
}
[Fact]
public void When_selecting_types_that_are_not_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(NotOnlyClassesClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.NotOnlyClasses.Test")
.ThatAreNotClasses();
// Assert
types.Should()
.HaveCount(2)
.And.Contain(typeof(INotOnlyClassesInterface))
.And.Contain(typeof(NotOnlyClassesEnumeration));
}
[Fact]
public void When_selecting_types_that_are_value_types_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(InternalEnumValueType).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.ValueTypesAndNotValueTypes.Test")
.ThatAreValueTypes();
// Assert
types.Should()
.HaveCount(3);
}
[Fact]
public void When_selecting_types_that_are_not_value_types_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(InternalEnumValueType).Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.ValueTypesAndNotValueTypes.Test")
.ThatAreNotValueTypes();
// Assert
types.Should()
.HaveCount(3);
}
[Fact]
public void When_selecting_types_that_are_abstract_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(AbstractClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.AbstractAndNotAbstractClasses.Test")
.ThatAreAbstract();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(AbstractClass));
}
[Fact]
public void When_selecting_types_that_are_not_abstract_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(NotAbstractClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.AbstractAndNotAbstractClasses.Test")
.ThatAreNotAbstract();
// Assert
types.Should()
.HaveCount(2);
}
[Fact]
public void When_selecting_types_that_are_sealed_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(SealedClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.SealedAndNotSealedClasses.Test")
.ThatAreSealed();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(SealedClass));
}
[Fact]
public void When_selecting_types_that_are_not_sealed_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(NotSealedClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.SealedAndNotSealedClasses.Test")
.ThatAreNotSealed();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(NotSealedClass));
}
[Fact]
public void When_selecting_types_that_are_static_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(StaticClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.StaticAndNonStaticClasses.Test")
.ThatAreStatic();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(StaticClass));
}
[Fact]
public void When_selecting_types_that_are_not_static_classes_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(StaticClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.StaticAndNonStaticClasses.Test")
.ThatAreNotStatic();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(NotAStaticClass));
}
[Fact]
public void When_selecting_types_with_predicate_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(SomeBaseClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatSatisfy(t => t.GetCustomAttribute<SomeAttribute>() is not null);
// Assert
types.Should()
.HaveCount(3)
.And.Contain(typeof(ClassWithSomeAttribute))
.And.Contain(typeof(ClassWithSomeAttributeDerived))
.And.Contain(typeof(ClassWithSomeAttributeThatImplementsSomeInterface));
}
[Fact]
public void When_unwrap_task_types_it_should_return_the_correct_types()
{
IEnumerable<Type> types = typeof(ClassToExploreUnwrappedTaskTypes)
.Methods()
.ReturnTypes()
.UnwrapTaskTypes();
types.Should()
.BeEquivalentTo([typeof(int), typeof(void), typeof(void), typeof(string), typeof(bool)]);
}
[Fact]
public void When_unwrap_enumerable_types_it_should_return_the_correct_types()
{
IEnumerable<Type> types = typeof(ClassToExploreUnwrappedEnumerableTypes)
.Methods()
.ReturnTypes()
.UnwrapEnumerableTypes();
types.Should()
.HaveCount(4)
.And.Contain(typeof(IEnumerable))
.And.Contain(typeof(bool))
.And.Contain(typeof(int))
.And.Contain(typeof(string));
}
[Fact]
public void When_selecting_types_that_are_interfaces_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(InternalInterface).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.InterfaceAndClasses.Test")
.ThatAreInterfaces();
// Assert
types.Should()
.ContainSingle()
.Which.Should().Be(typeof(InternalInterface));
}
[Fact]
public void When_selecting_types_that_are_not_interfaces_it_should_return_the_correct_types()
{
// Arrange
Assembly assembly = typeof(InternalNotInterfaceClass).GetTypeInfo().Assembly;
// Act
IEnumerable<Type> types = AllTypes.From(assembly)
.ThatAreInNamespace("Internal.InterfaceAndClasses.Test")
.ThatAreNotInterfaces();
// Assert
types.Should()
.HaveCount(2)
.And.Contain(typeof(InternalNotInterfaceClass))
.And.Contain(typeof(InternalAbstractClass));
}
}
}
#region Internal classes used in unit tests
namespace Internal.Main.Test
{
| TypeSelectorSpecs |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ScriptTests/JsArrowFunctionTests.cs | {
"start": 7085,
"end": 8287
} | public class ____ : IEqualityComparer<string>
{
public bool Equals(string x, string y) => GetCanonicalString(x) == GetCanonicalString(y);
public int GetHashCode(string obj) => GetCanonicalString(obj).GetHashCode();
private string GetCanonicalString(string word)
{
var wordChars = word.ToCharArray();
Array.Sort(wordChars);
return new string(wordChars);
}
}
[Test]
public void Does_evaluate_groupBy_Arrow_Expressions()
{
var context = new ScriptContext
{
Args =
{
["anagramComparer"] = new AnagramEqualityComparer()
}
}.Init();
Assert.That(context.EvaluateScript(@"{{ ['from ', ' salt', ' earn ', ' last ', ' near ', ' form '] |> assignTo: anagrams }}
{{#each groupBy(anagrams, w => trim(w), { map: x => upper(x), comparer: anagramComparer }) }}{{it |> json}}{{/each}}"),
Is.EqualTo(@"[""FROM "","" FORM ""]["" SALT"","" LAST ""]["" EARN "","" NEAR ""]"));
}
| AnagramEqualityComparer |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3217702,
"end": 3219209
} | public partial class ____ : global::System.IEquatable<PageClientVersionDetailQuery_Node_Workspace>, IPageClientVersionDetailQuery_Node_Workspace
{
public PageClientVersionDetailQuery_Node_Workspace()
{
}
public virtual global::System.Boolean Equals(PageClientVersionDetailQuery_Node_Workspace? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return true;
}
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((PageClientVersionDetailQuery_Node_Workspace)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| PageClientVersionDetailQuery_Node_Workspace |
csharp | unoplatform__uno | src/Uno.UI.Tests/Windows_UI_Input/Given_GestureRecognizer.cs | {
"start": 65433,
"end": 69267
} | public abstract class ____<TArgs> : Validator
{
private string _pendingAssertIdentifier;
private List<(string name, object expected, object actual)> _pendingAssertResult;
internal override void Assert(object args, string identifier)
{
try
{
_pendingAssertIdentifier = identifier;
if (!(args is TArgs t))
{
Failed($"is not of the expected type: {typeof(TArgs).Name}");
return;
}
_pendingAssertResult = new List<(string, object, object)>();
Assert(t);
if (_pendingAssertResult.Any())
{
Failed("has some unexpected values: \r\n" + string.Join("\r\n", _pendingAssertResult.Select(r => $"\t{r.name} (expected: {r.expected} / actual: {r.actual})")));
}
}
catch (Exception e) when (!(e is AssertionFailedException))
{
throw new AssertionFailedException($"{identifier} validation failed: {e.Message}");
}
finally
{
_pendingAssertResult = null;
}
}
protected abstract void Assert(TArgs args);
protected void Failed(string reason)
=> throw new AssertionFailedException($"{_pendingAssertIdentifier} {reason}");
protected void AreEquals(string name, Point? expected, Point actual)
{
if (expected.HasValue && expected.Value != actual)
_pendingAssertResult.Add((name, expected.Value, actual));
}
protected void AreEquals(string name, bool? expected, bool actual)
{
if (expected.HasValue && expected.Value != actual)
_pendingAssertResult.Add((name, expected.Value, actual));
}
protected void AreEquals(string name, PointerDeviceType? expected, PointerDeviceType actual)
{
if (expected.HasValue && expected.Value != actual)
_pendingAssertResult.Add((name, expected.Value, actual));
}
protected void AreEquals(string name, uint? expected, uint actual)
{
if (expected.HasValue && expected.Value != actual)
_pendingAssertResult.Add((name, expected.Value, actual));
}
protected void AreEquals(string name, ManipulationDelta? expected, ManipulationDelta actual)
{
if (!expected.HasValue)
{
return;
}
var e = expected.Value;
if (Math.Abs(e.Translation.X - actual.Translation.X) > .00001)
_pendingAssertResult.Add((name + ".Translation.X", expected.Value.Translation.X, actual.Translation.X));
if (Math.Abs(e.Translation.Y - actual.Translation.Y) > .00001)
_pendingAssertResult.Add((name + ".Translation.Y", expected.Value.Translation.Y, actual.Translation.Y));
if (Math.Abs(e.Rotation - actual.Rotation) > .00001)
_pendingAssertResult.Add((name + ".Rotation", expected.Value.Rotation, actual.Rotation));
if (Math.Abs(e.Scale - actual.Scale) > .00001)
_pendingAssertResult.Add((name + ".Scale", expected.Value.Scale, actual.Scale));
if (Math.Abs(e.Expansion - actual.Expansion) > .00001)
_pendingAssertResult.Add((name + ".Expansion", expected.Value.Expansion, actual.Expansion));
}
protected void AreEquals(string name, ManipulationVelocities? expected, ManipulationVelocities actual)
{
if (!expected.HasValue)
{
return;
}
var e = expected.Value;
if (e.Linear.X != actual.Linear.X)
_pendingAssertResult.Add((name + ".Linear.X", expected.Value.Linear.X, actual.Linear.X));
if (e.Linear.Y != actual.Linear.Y)
_pendingAssertResult.Add((name + ".Linear.Y", expected.Value.Linear.Y, actual.Linear.Y));
if (Math.Abs(e.Angular - actual.Angular) > .00001)
_pendingAssertResult.Add((name + ".Angular", expected.Value.Angular, actual.Angular));
if (Math.Abs(e.Expansion - actual.Expansion) > .00001)
_pendingAssertResult.Add((name + ".Expansion", expected.Value.Expansion, actual.Expansion));
}
/// <inheritdoc />
public override string ToString()
=> typeof(TArgs).Name;
}
| Validator |
csharp | xunit__xunit | src/xunit.v3.core.tests/Acceptance/Xunit3TheoryAcceptanceTests.cs | {
"start": 97397,
"end": 97530
} | class ____ : Repro<ClassUnderTest_StaticInterfaceMethod>, IInterfaceWithStaticVirtualMember
{ }
| ClassUnderTest_StaticInterfaceMethod |
csharp | dotnet__aspnetcore | src/Http/Http/test/ApplicationBuilderTests.cs | {
"start": 5397,
"end": 6156
} | private class ____ : IHttpResponseFeature
{
private int _statusCode = 200;
public int StatusCode
{
get => _statusCode;
set
{
_statusCode = HasStarted ? throw new NotSupportedException("The response has already started") : value;
}
}
public string ReasonPhrase { get; set; }
public IHeaderDictionary Headers { get; set; }
public Stream Body { get; set; } = Stream.Null;
public bool HasStarted { get; set; }
public void OnCompleted(Func<object, Task> callback, object state)
{
}
public void OnStarting(Func<object, Task> callback, object state)
{
}
}
}
| TestHttpResponseFeature |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.