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
|
unoplatform__uno
|
src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Http/HttpProgress.cs
|
{
"start": 291,
"end": 1285
}
|
public partial struct ____
{
// Forced skipping of method Windows.Web.Http.HttpProgress.HttpProgress()
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public global::Windows.Web.Http.HttpProgressStage Stage;
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public ulong BytesSent;
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public ulong? TotalBytesToSend;
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public ulong BytesReceived;
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public ulong? TotalBytesToReceive;
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
public uint Retries;
#endif
}
}
|
HttpProgress
|
csharp
|
AutoMapper__AutoMapper
|
src/UnitTests/Bug/NestedMappingProjectionsExplicitExpanding.cs
|
{
"start": 410,
"end": 480
}
|
public class ____
{
public Man Man { get; set; }
}
|
Fu
|
csharp
|
EventStore__EventStore
|
src/Connectors/KurrentDB.Connectors/Planes/Control/ConnectorsActivator.cs
|
{
"start": 11870,
"end": 12029
}
|
record ____ Activated : IActivationResult {
public Exception? Error => null;
public bool Success => true;
}
public readonly
|
struct
|
csharp
|
dotnet__aspnetcore
|
src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.ComplexType.cs
|
{
"start": 21374,
"end": 21501
}
|
private class ____
{
[Required]
public string RequiredProperty { get; set; } = "";
}
|
PrivateNestedType
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.ImageAnalytics/VectorToImageTransform.cs
|
{
"start": 5012,
"end": 17675
}
|
internal class ____ : TransformInputBase
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:src)", Name = "Column", ShortName = "col", SortOrder = 1)]
public Column[] Columns;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use alpha channel", ShortName = "alpha")]
public bool ContainsAlpha = (ImagePixelExtractingEstimator.Defaults.Colors & ImagePixelExtractingEstimator.ColorBits.Alpha) > 0;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use red channel", ShortName = "red")]
public bool ContainsRed = (ImagePixelExtractingEstimator.Defaults.Colors & ImagePixelExtractingEstimator.ColorBits.Red) > 0;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use green channel", ShortName = "green")]
public bool ContainsGreen = (ImagePixelExtractingEstimator.Defaults.Colors & ImagePixelExtractingEstimator.ColorBits.Green) > 0;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use blue channel", ShortName = "blue")]
public bool ContainsBlue = (ImagePixelExtractingEstimator.Defaults.Colors & ImagePixelExtractingEstimator.ColorBits.Blue) > 0;
[Argument(ArgumentType.AtMostOnce, HelpText = "Order of colors.")]
public ImagePixelExtractingEstimator.ColorsOrder Order = ImagePixelExtractingEstimator.Defaults.Order;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to separate each channel or interleave in specified order")]
public bool Interleave = ImagePixelExtractingEstimator.Defaults.Interleave;
[Argument(ArgumentType.AtMostOnce, HelpText = "Width of the image", ShortName = "width")]
public int ImageWidth;
[Argument(ArgumentType.AtMostOnce, HelpText = "Height of the image", ShortName = "height")]
public int ImageHeight;
[Argument(ArgumentType.AtMostOnce, HelpText = "Offset (pre-scale)")]
public Single Offset = VectorToImageConvertingEstimator.Defaults.Offset;
[Argument(ArgumentType.AtMostOnce, HelpText = "Scale factor")]
public Single Scale = VectorToImageConvertingEstimator.Defaults.Scale;
[Argument(ArgumentType.AtMostOnce, HelpText = "Default value for alpha channel. Will be used if ContainsAlpha set to false")]
public int DefaultAlpha = VectorToImageConvertingEstimator.Defaults.DefaultAlpha;
[Argument(ArgumentType.AtMostOnce, HelpText = "Default value for red channel. Will be used if ContainsRed set to false")]
public int DefaultRed = VectorToImageConvertingEstimator.Defaults.DefaultRed;
[Argument(ArgumentType.AtMostOnce, HelpText = "Default value for green channel. Will be used if ContainsGreen set to false")]
public int DefaultGreen = VectorToImageConvertingEstimator.Defaults.DefaultGreen;
[Argument(ArgumentType.AtMostOnce, HelpText = "Default value for blue channel. Will be used if ContainsBlue set to false")]
public int DefaultBlue = VectorToImageConvertingEstimator.Defaults.DefaultBlue;
}
internal const string Summary = "Converts vector array into image type.";
internal const string UserName = "Vector To Image Transform";
internal const string LoaderSignature = "VectorToImageConverter";
internal const uint BeforeOrderVersion = 0x00010002;
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "VECTOIMG",
//verWrittenCur: 0x00010001, // Initial
//verWrittenCur: 0x00010002, // Swith from OpenCV to Bitmap
verWrittenCur: 0x00010003, // order for pixel colors, default colors, no size(float)
verReadableCur: 0x00010002,
verWeCanReadBack: 0x00010003,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(VectorToImageConvertingTransformer).Assembly.FullName);
}
private const string RegistrationName = "VectorToImageConverter";
private readonly VectorToImageConvertingEstimator.ColumnOptions[] _columns;
/// <summary>
/// The columns passed to this <see cref="ITransformer"/>.
/// </summary>
internal IReadOnlyCollection<VectorToImageConvertingEstimator.ColumnOptions> Columns => _columns.AsReadOnly();
internal VectorToImageConvertingTransformer(IHostEnvironment env, params VectorToImageConvertingEstimator.ColumnOptions[] columns)
: base(Contracts.CheckRef(env, nameof(env)).Register(RegistrationName), GetColumnPairs(columns))
{
Host.AssertNonEmpty(columns);
_columns = columns.ToArray();
}
/// <param name="env">The host environment.</param>
/// <param name="outputColumnName">Name of the column resulting from the transformation of <paramref name="inputColumnName"/>.</param>
/// <param name="imageHeight">The height of the output images.</param>
/// <param name="imageWidth">The width of the output images.</param>
/// <param name="inputColumnName">Name of column to transform. If set to <see langword="null"/>, the value of the <paramref name="outputColumnName"/> will be used as source.</param>
/// <param name="colorsPresent">Specifies which <see cref="ImagePixelExtractingEstimator.ColorBits"/> are in present the input pixel vectors. The order of colors is specified in <paramref name="orderOfColors"/>.</param>
/// <param name="orderOfColors">The order in which colors are presented in the input vector.</param>
/// <param name="interleavedColors">Whether the pixels are interleaved, meaning whether they are in <paramref name="orderOfColors"/> order, or separated in the planar form, where the colors are specified one by one
/// for all the pixels of the image. </param>
/// <param name="scaleImage">Scale each pixel's color value by this amount.</param>
/// <param name="offsetImage">Offset each pixel's color value by this amount.</param>
/// <param name="defaultAlpha">Default value for alpha color, would be overridden if <paramref name="colorsPresent"/> contains <see cref="ImagePixelExtractingEstimator.ColorBits.Alpha"/>.</param>
/// <param name="defaultRed">Default value for red color, would be overridden if <paramref name="colorsPresent"/> contains <see cref="ImagePixelExtractingEstimator.ColorBits.Red"/>.</param>
/// <param name="defaultGreen">Default value for green color, would be overridden if <paramref name="colorsPresent"/> contains <see cref="ImagePixelExtractingEstimator.ColorBits.Green"/>.</param>
/// <param name="defaultBlue">Default value for blue color, would be overridden if <paramref name="colorsPresent"/> contains <see cref="ImagePixelExtractingEstimator.ColorBits.Blue"/>.</param>
internal VectorToImageConvertingTransformer(IHostEnvironment env, string outputColumnName,
int imageHeight, int imageWidth,
string inputColumnName = null,
ImagePixelExtractingEstimator.ColorBits colorsPresent = ImagePixelExtractingEstimator.Defaults.Colors,
ImagePixelExtractingEstimator.ColorsOrder orderOfColors = ImagePixelExtractingEstimator.Defaults.Order,
bool interleavedColors = ImagePixelExtractingEstimator.Defaults.Interleave,
float scaleImage = VectorToImageConvertingEstimator.Defaults.Scale,
float offsetImage = VectorToImageConvertingEstimator.Defaults.Offset,
int defaultAlpha = VectorToImageConvertingEstimator.Defaults.DefaultAlpha,
int defaultRed = VectorToImageConvertingEstimator.Defaults.DefaultRed,
int defaultGreen = VectorToImageConvertingEstimator.Defaults.DefaultGreen,
int defaultBlue = VectorToImageConvertingEstimator.Defaults.DefaultBlue)
: this(env, new VectorToImageConvertingEstimator.ColumnOptions(outputColumnName, imageHeight, imageWidth, inputColumnName, colorsPresent, orderOfColors, interleavedColors, scaleImage, offsetImage, defaultAlpha, defaultRed, defaultGreen, defaultBlue))
{
}
// Constructor corresponding to SignatureDataTransform.
internal static IDataTransform Create(IHostEnvironment env, Options args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(input, nameof(input));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = new VectorToImageConvertingEstimator.ColumnOptions[args.Columns.Length];
for (int i = 0; i < columns.Length; i++)
{
var item = args.Columns[i];
columns[i] = new VectorToImageConvertingEstimator.ColumnOptions(item, args);
}
var transformer = new VectorToImageConvertingTransformer(env, columns);
return new RowToRowMapperTransform(env, input, transformer.MakeRowMapper(input.Schema), transformer.MakeRowMapper);
}
private VectorToImageConvertingTransformer(IHost host, ModelLoadContext ctx)
: base(host, ctx)
{
Host.AssertValue(ctx);
// *** Binary format ***
// <base>
// foreach added column
// ColumnOptions
_columns = new VectorToImageConvertingEstimator.ColumnOptions[ColumnPairs.Length];
for (int i = 0; i < _columns.Length; i++)
_columns[i] = new VectorToImageConvertingEstimator.ColumnOptions(ColumnPairs[i].outputColumnName, ColumnPairs[i].inputColumnName, ctx);
}
private static VectorToImageConvertingTransformer Create(IHostEnvironment env, ModelLoadContext ctx)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(RegistrationName);
h.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel(GetVersionInfo());
if (ctx.Header.ModelVerWritten <= VectorToImageConvertingTransformer.BeforeOrderVersion)
ctx.Reader.ReadFloat();
return h.Apply("Loading Model",
ch =>
{
return new VectorToImageConvertingTransformer(h, ctx);
});
}
// Factory method for SignatureLoadDataTransform.
private static IDataTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
=> Create(env, ctx).MakeDataTransform(input);
// Factory method for SignatureLoadRowMapper.
private static IRowMapper Create(IHostEnvironment env, ModelLoadContext ctx, DataViewSchema inputSchema)
=> Create(env, ctx).MakeRowMapper(inputSchema);
private protected override void SaveModel(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
// *** Binary format ***
// <base>
// foreach added column
// ColInfoEx
base.SaveColumns(ctx);
for (int i = 0; i < _columns.Length; i++)
_columns[i].Save(ctx);
}
private static (string outputColumnName, string inputColumnName)[] GetColumnPairs(VectorToImageConvertingEstimator.ColumnOptions[] columns)
{
Contracts.CheckValue(columns, nameof(columns));
return columns.Select(x => (x.Name, x.InputColumnName)).ToArray();
}
private protected override IRowMapper MakeRowMapper(DataViewSchema schema) => new Mapper(this, schema);
private protected override void CheckInputColumn(DataViewSchema inputSchema, int col, int srcCol)
{
var inputColName = _columns[col].InputColumnName;
var vectorType = inputSchema[srcCol].Type as VectorDataViewType;
if (vectorType == null)
throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", inputColName, "image", inputSchema[srcCol].Type.ToString());
if (vectorType.GetValueCount() != _columns[col].ImageHeight * _columns[col].ImageWidth * _columns[col].Planes)
throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", inputColName, new VectorDataViewType(vectorType.ItemType, _columns[col].ImageHeight, _columns[col].ImageWidth, _columns[col].Planes).ToString(), vectorType.ToString());
}
|
Options
|
csharp
|
dotnet__efcore
|
test/EFCore.Relational.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryRelationalTestBase.cs
|
{
"start": 10229,
"end": 10365
}
|
protected class ____
{
public int Id { get; set; }
public TestOwned Owned { get; set; }
}
[Owned]
|
TestOwner
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.StandardTrainers/Optimizer/Optimizer.cs
|
{
"start": 3532,
"end": 4283
}
|
public abstract class ____ : Exception
{
/// <summary>
/// The state of the optimizer when premature convergence happened.
/// </summary>
public OptimizerState State { get; }
internal OptimizerException(OptimizerState state, string message)
: base(message)
{
State = state;
}
}
internal virtual OptimizerState MakeState(IChannel ch, IProgressChannelProvider progress, DifferentiableFunction function, ref VBuffer<float> initial)
{
return new FunctionOptimizerState(ch, progress, function, in initial, M, TotalMemoryLimit, KeepDense, EnforceNonNegativity);
}
|
OptimizerException
|
csharp
|
mongodb__mongo-csharp-driver
|
src/MongoDB.Driver/DensifyRange.cs
|
{
"start": 15590,
"end": 16386
}
|
public enum ____
{
/// <summary>
/// Milliseconds.
/// </summary>
Milliseconds = 1,
/// <summary>
/// Seconds.
/// </summary>
Seconds,
/// <summary>
/// Minutes.
/// </summary>
Minutes,
/// <summary>
/// Hours.
/// </summary>
Hours,
/// <summary>
/// Days.
/// </summary>
Days,
/// <summary>
/// Weeks.
/// </summary>
Weeks,
/// <summary>
/// Months.
/// </summary>
Months,
/// <summary>
/// Quarters.
/// </summary>
Quarters,
/// <summary>
/// Years.
/// </summary>
Years
}
}
|
DensifyDateTimeUnit
|
csharp
|
microsoft__semantic-kernel
|
dotnet/src/Experimental/Process.Core/Workflow/WorkflowBuilder.cs
|
{
"start": 565,
"end": 6704
}
|
internal class ____
{
private readonly Dictionary<string, ProcessStepBuilder> _stepBuilders = [];
private readonly Dictionary<string, CloudEvent> _inputEvents = [];
private string? _yaml;
/// <summary>
/// Builds a process from a workflow definition.
/// </summary>
/// <param name="workflow">An instance of <see cref="Workflow"/>.</param>
/// <param name="yaml">Workflow definition in YAML format.</param>
/// <param name="stepTypes">Collection of preloaded step types.</param>
public async Task<KernelProcess?> BuildProcessAsync(Workflow workflow, string yaml, Dictionary<string, Type>? stepTypes = null)
{
this._yaml = yaml;
var stepBuilders = new Dictionary<string, ProcessStepBuilder>();
if (workflow.Nodes is null || workflow.Nodes.Count == 0)
{
throw new ArgumentException("Workflow nodes are not specified.");
}
if (workflow.Inputs is null)
{
throw new ArgumentException("Workflow inputs are not specified.");
}
// TODO: Process outputs
// TODO: Process variables
ProcessBuilder processBuilder = new(workflow.Id, description: workflow.Description, stateType: typeof(ProcessDefaultState));
if (workflow.Inputs.Events?.CloudEvents is not null)
{
foreach (CloudEvent inputEvent in workflow.Inputs.Events.CloudEvents)
{
await this.AddInputEventAsync(inputEvent, processBuilder).ConfigureAwait(false);
}
}
if (workflow.Inputs.Messages is not null)
{
await this.AddInputMessagesEventAsync(processBuilder).ConfigureAwait(false);
}
// Process the nodes
foreach (var step in workflow.Nodes)
{
await this.AddStepAsync(step, processBuilder, stepTypes).ConfigureAwait(false);
}
// Process the orchestration
if (workflow.Orchestration is not null)
{
await this.BuildOrchestrationAsync(workflow.Orchestration, processBuilder).ConfigureAwait(false);
}
return processBuilder.Build();
}
#region Inputs
private Task AddInputEventAsync(CloudEvent inputEvent, ProcessBuilder processBuilder)
{
this._inputEvents[inputEvent.Type] = inputEvent;
return Task.CompletedTask;
}
private Task AddInputMessagesEventAsync(ProcessBuilder processBuilder)
{
string inputMessageEventType = "input_message_received";
this._inputEvents[inputMessageEventType] = new CloudEvent() { Type = inputMessageEventType };
return Task.CompletedTask;
}
#endregion
#region Nodes and Steps
internal async Task AddStepAsync(Node node, ProcessBuilder processBuilder, Dictionary<string, Type>? stepTypes = null)
{
Verify.NotNull(node);
if (node.Type == "dotnet")
{
await this.BuildDotNetStepAsync(node, processBuilder, stepTypes).ConfigureAwait(false);
}
else if (node.Type == "python")
{
await this.BuildPythonStepAsync(node, processBuilder).ConfigureAwait(false);
}
else if (node.Type == "declarative")
{
await this.BuildDeclarativeStepAsync(node, processBuilder).ConfigureAwait(false);
}
else
{
throw new ArgumentException($"Unsupported node type: {node.Type}");
}
}
private Task BuildDeclarativeStepAsync(Node node, ProcessBuilder processBuilder)
{
Verify.NotNull(node);
// Check for built-in step types
if (node.Id.Equals("End", StringComparison.OrdinalIgnoreCase))
{
var endBuilder = processBuilder.AddEndStep();
this._stepBuilders["End"] = endBuilder;
return Task.CompletedTask;
}
AgentDefinition? agentDefinition = node.Agent ?? throw new KernelException("Declarative steps must have an agent defined.");
var stepBuilder = processBuilder.AddStepFromAgent(agentDefinition, node.Id);
if (stepBuilder is not ProcessAgentBuilder agentBuilder)
{
throw new KernelException($"Failed to build step from agent definition: {node.Id}");
}
// ########################### Parsing on_complete and on_error conditions ###########################
if (node.OnComplete != null)
{
if (node.OnComplete.Any(c => c is null || c.OnCondition is null))
{
throw new ArgumentException("A complete on_complete condition is required for declarative steps.");
}
agentBuilder.OnComplete([.. node.OnComplete.Select(c => c.OnCondition!)]);
}
if (node.OnError != null)
{
if (node.OnError.Any(c => c is null || c.OnCondition is null))
{
throw new ArgumentException("A complete on_complete condition is required for declarative steps.");
}
agentBuilder.OnComplete([.. node.OnError.Select(c => c.OnCondition!)]);
}
// ########################### Parsing node inputs ###########################
if (node.Inputs != null)
{
var inputMapping = this.ExtractNodeInputs(node.Id);
//agentBuilder.WithNodeInputs(node.Inputs); TODO: What to do here?
}
this._stepBuilders[node.Id] = stepBuilder;
return Task.CompletedTask;
}
private Task BuildPythonStepAsync(Node node, ProcessBuilder processBuilder)
{
throw new KernelException("Python nodes are not supported in the dotnet runtime.");
}
private Task BuildDotNetStepAsync(Node node, ProcessBuilder processBuilder, Dictionary<string, Type>? stepTypes = null)
{
Verify.NotNull(node);
if (node.Agent is null || string.IsNullOrEmpty(node.Agent.Type))
{
throw new ArgumentException($"The agent specified in the Node with id {node.Id} is not fully specified.");
}
// For dotnet node type, the agent type specifies the assembly qualified namespace of the
|
WorkflowBuilder
|
csharp
|
dotnet__maui
|
src/Controls/src/Core/Compatibility/Handlers/ListView/Android/EntryCellView.cs
|
{
"start": 407,
"end": 4447
}
|
public sealed class ____ : LinearLayout, ITextWatcher, global::Android.Views.View.IOnFocusChangeListener, TextView.IOnEditorActionListener, INativeElementView
{
public const double DefaultMinHeight = 55;
#pragma warning disable CS0618 // Type or member is obsolete
readonly Cell _cell;
#pragma warning restore CS0618 // Type or member is obsolete
readonly AppCompatTextView _label;
Color _labelTextColor;
string _labelTextText;
#pragma warning disable CS0618 // Type or member is obsolete
public EntryCellView(Context context, Cell cell) : base(context)
#pragma warning restore CS0618 // Type or member is obsolete
{
_cell = cell;
SetMinimumWidth((int)context.ToPixels(50));
SetMinimumHeight((int)context.ToPixels(85));
Orientation = Orientation.Horizontal;
var padding = (int)context.ToPixels(8);
SetPadding((int)context.ToPixels(15), padding, padding, padding);
_label = new AppCompatTextView(context);
TextViewCompat.SetTextAppearance(_label, global::Android.Resource.Style.TextAppearanceSmall);
var layoutParams = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent) { Gravity = GravityFlags.CenterVertical };
using (layoutParams)
AddView(_label, layoutParams);
EditText = new EntryCellEditText(context);
EditText.AddTextChangedListener(this);
EditText.OnFocusChangeListener = this;
EditText.SetOnEditorActionListener(this);
EditText.ImeOptions = ImeAction.Done;
EditText.BackButtonPressed += OnBackButtonPressed;
//editText.SetBackgroundDrawable (null);
layoutParams = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) { Width = 0, Weight = 1, Gravity = GravityFlags.FillHorizontal | GravityFlags.Center };
using (layoutParams)
AddView(EditText, layoutParams);
}
public Action EditingCompleted { get; set; }
public EntryCellEditText EditText { get; }
public Action<bool> FocusChanged { get; set; }
public string LabelText
{
get { return _labelTextText; }
set
{
if (_labelTextText == value)
return;
_labelTextText = value;
_label.Text = value;
}
}
public Action<string> TextChanged { get; set; }
public Element Element
{
get { return _cell; }
}
bool TextView.IOnEditorActionListener.OnEditorAction(TextView v, ImeAction actionId, KeyEvent e)
{
if (actionId == ImeAction.Done)
{
OnKeyboardDoneButtonPressed(EditText, EventArgs.Empty);
EditText.ClearFocus();
v.HideSoftInput();
}
// Fire Completed and dismiss keyboard for hardware / physical keyboards
if (actionId == ImeAction.ImeNull && e.KeyCode == Keycode.Enter)
{
OnKeyboardDoneButtonPressed(EditText, EventArgs.Empty);
EditText.ClearFocus();
v.HideSoftInput();
}
return true;
}
void IOnFocusChangeListener.OnFocusChange(global::Android.Views.View view, bool hasFocus)
{
Action<bool> focusChanged = FocusChanged;
if (focusChanged != null)
focusChanged(hasFocus);
}
void ITextWatcher.AfterTextChanged(IEditable s)
{
}
void ITextWatcher.BeforeTextChanged(ICharSequence s, int start, int count, int after)
{
}
void ITextWatcher.OnTextChanged(ICharSequence s, int start, int before, int count)
{
Action<string> changed = TextChanged;
if (changed != null)
changed(s?.ToString());
}
public void SetLabelTextColor(Color color, int defaultColorResourceId)
{
if (_labelTextColor == color)
return;
_labelTextColor = color;
_label.SetTextColor(color.ToPlatform(defaultColorResourceId, _label.Context));
}
public void SetRenderHeight(double height)
{
SetMinimumHeight((int)Context.ToPixels(height == -1 ? DefaultMinHeight : height));
}
void OnBackButtonPressed(object sender, EventArgs e)
{
// TODO Clear focus
}
void OnKeyboardDoneButtonPressed(object sender, EventArgs e)
{
// TODO Clear focus
Action editingCompleted = EditingCompleted;
if (editingCompleted != null)
editingCompleted();
}
}
}
|
EntryCellView
|
csharp
|
dotnet__maui
|
src/Controls/src/Core/Platform/AlertManager/AlertManager.cs
|
{
"start": 1933,
"end": 2331
}
|
internal interface ____
{
void OnActionSheetRequested(Page sender, ActionSheetArguments arguments);
void OnAlertRequested(Page sender, AlertArguments arguments);
void OnPromptRequested(Page sender, PromptArguments arguments);
[Obsolete("This method is obsolete in .NET 10 and will be removed in .NET11.")]
void OnPageBusy(Page sender, bool enabled);
}
|
IAlertManagerSubscription
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.FastTree/Training/BaggingProvider.cs
|
{
"start": 267,
"end": 3265
}
|
internal class ____
{
protected Dataset CompleteTrainingSet;
protected DocumentPartitioning CurrentTrainPartition;
protected DocumentPartitioning CurrentOutOfBagPartition;
protected Random RndGenerator;
protected int MaxLeaves;
protected double TrainFraction;
public BaggingProvider(Dataset completeTrainingSet, int maxLeaves, int randomSeed, double trainFraction)
{
CompleteTrainingSet = completeTrainingSet;
MaxLeaves = maxLeaves;
RndGenerator = new Random(randomSeed);
TrainFraction = trainFraction;
GenerateNewBag();
}
public virtual void GenerateNewBag()
{
int[] trainDocs = new int[CompleteTrainingSet.NumDocs];
int[] outOfBagDocs = new int[CompleteTrainingSet.NumDocs];
int trainSize = 0;
int outOfBagSize = 0;
for (int i = 0; i < CompleteTrainingSet.NumQueries; i++)
{
int begin = CompleteTrainingSet.Boundaries[i];
int numDocuments = CompleteTrainingSet.Boundaries[i + 1] - begin;
for (int d = 0; d < numDocuments; d++)
{
if (RndGenerator.NextDouble() < TrainFraction)
{
trainDocs[trainSize] = begin + d;
trainSize++;
}
else
{
outOfBagDocs[outOfBagSize] = begin + d;
outOfBagSize++;
}
}
}
CurrentTrainPartition = new DocumentPartitioning(trainDocs, trainSize, MaxLeaves);
CurrentOutOfBagPartition = new DocumentPartitioning(outOfBagDocs, outOfBagSize, MaxLeaves);
CurrentTrainPartition.Initialize();
CurrentOutOfBagPartition.Initialize();
}
public DocumentPartitioning GetCurrentTrainingPartition()
{
return CurrentTrainPartition;
}
public DocumentPartitioning GetCurrentOutOfBagPartition()
{
return CurrentOutOfBagPartition;
}
public int GetBagCount(int numTrees, int bagSize)
{
return numTrees / bagSize;
}
// Divides output values of leaves to bag count.
// This brings back the final scores generated by model on a same
// range as when we didn't use bagging
internal void ScaleEnsembleLeaves(int numTrees, int bagSize, InternalTreeEnsemble ensemble)
{
int bagCount = GetBagCount(numTrees, bagSize);
for (int t = 0; t < ensemble.NumTrees; t++)
{
InternalRegressionTree tree = ensemble.GetTreeAt(t);
tree.ScaleOutputsBy(1.0 / bagCount);
}
}
}
//REVIEW: Should FastTree binary application have instances bagging or query bagging?
|
BaggingProvider
|
csharp
|
getsentry__sentry-dotnet
|
src/Sentry/SentryGraphQLHttpFailedRequestHandler.cs
|
{
"start": 100,
"end": 3849
}
|
internal class ____ : SentryFailedRequestHandler
{
private readonly IHub _hub;
private readonly SentryOptions _options;
internal const string MechanismType = "GraphqlInstrumentation";
private readonly SentryHttpFailedRequestHandler _httpFailedRequestHandler;
internal SentryGraphQLHttpFailedRequestHandler(IHub hub, SentryOptions options)
: base(hub, options)
{
_hub = hub;
_options = options;
_httpFailedRequestHandler = new SentryHttpFailedRequestHandler(hub, options);
}
protected internal override void DoEnsureSuccessfulResponse([NotNull] HttpRequestMessage request, [NotNull] HttpResponseMessage response)
{
JsonElement? json = null;
try
{
json = GraphQLContentExtractor.ExtractResponseContentAsync(response, _options).Result;
if (json is { } jsonElement)
{
if (jsonElement.TryGetProperty("errors", out var errorsElement))
{
// We just show the first error... maybe there's a better way to do this when multiple errors exist.
// We should check what the Java code is doing.
var errorMessage = errorsElement[0].GetProperty("message").GetString() ?? "GraphQL Error";
throw new GraphQLHttpRequestException(errorMessage);
}
}
// No GraphQL errors, but we still might have an HTTP error status
_httpFailedRequestHandler.DoEnsureSuccessfulResponse(request, response);
}
catch (Exception exception)
{
exception.SetSentryMechanism(MechanismType, "GraphQL Failed Request Handler", false);
var @event = new SentryEvent(exception);
var hint = new SentryHint(HintTypes.HttpResponseMessage, response);
var sentryRequest = new SentryRequest
{
QueryString = request.RequestUri?.Query,
Method = request.Method.Method.ToUpperInvariant(),
ApiTarget = "graphql"
};
var responseContext = new Response
{
StatusCode = (short)response.StatusCode,
#if NET5_0_OR_GREATER
// Starting with .NET 5, the content and headers are guaranteed to not be null.
BodySize = response.Content?.Headers.ContentLength,
#else
BodySize = response.Content?.Headers?.ContentLength,
#endif
};
var requestContent = request.GetFused<GraphQLRequestContent>();
if (!_options.SendDefaultPii)
{
sentryRequest.Url = request.RequestUri?.HttpRequestUrl();
}
else
{
sentryRequest.Cookies = request.Headers.GetCookies();
sentryRequest.Data = requestContent?.RequestContent;
sentryRequest.Url = request.RequestUri?.AbsoluteUri;
sentryRequest.AddHeaders(request.Headers);
responseContext.Cookies = response.Headers.GetCookies();
responseContext.Data = json;
responseContext.AddHeaders(response.Headers);
}
@event.Request = sentryRequest;
@event.Contexts[Response.Type] = responseContext;
if (requestContent is not null)
{
@event.Fingerprint = new[]
{
requestContent.OperationNameOrFallback(),
requestContent.OperationTypeOrFallback(),
((int)response.StatusCode).ToString()
};
}
Hub.CaptureEvent(@event, hint: hint);
}
}
}
|
SentryGraphQLHttpFailedRequestHandler
|
csharp
|
CommunityToolkit__WindowsCommunityToolkit
|
Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ReferenceNodes/ManipulationPropertySetReferenceNode.cs
|
{
"start": 369,
"end": 520
}
|
class ____ be inherited.
/// </summary>
/// <seealso cref="Microsoft.Toolkit.Uwp.UI.Animations.Expressions.PropertySetReferenceNode" />
|
cannot
|
csharp
|
unoplatform__uno
|
src/Uno.UI.RemoteControl.Server.Processors/HotReload/MetadataUpdates/WatchHotReloadService.cs
|
{
"start": 407,
"end": 685
}
|
public class ____
{
private Func<Solution, CancellationToken, Task>? _startSessionAsync;
private Func<Solution, CancellationToken, Task<ITuple>>? _emitSolutionUpdateAsync;
private Action? _endSession;
private object? _targetInstance;
public readonly
|
WatchHotReloadService
|
csharp
|
nuke-build__nuke
|
source/Nuke.Components/IReportIssues.cs
|
{
"start": 601,
"end": 5940
}
|
public interface ____ : IRestore, IHazReports
{
AbsolutePath InspectCodeReportFile => ReportDirectory / "inspect-code.xml";
Target ReportIssues => _ => _
.DependsOn(Restore)
.TryAfter<ITest>()
.Executes(() =>
{
ReSharperInspectCode(_ => _
.Apply(InspectCodeSettingsBase)
.Apply(InspectCodeSettings)
.CombineWith(InspectCodePlugins, (_, v) => _
.AddPlugin(v.PackageId, v.Version)));
TeamCity.Instance?.ImportData(TeamCityImportType.ReSharperInspectCode, InspectCodeReportFile);
InspectCodeCheckResults();
});
IEnumerable<(string PackageId, string Version)> InspectCodePlugins => new (string PackageId, string Version)[0];
sealed Configure<ReSharperInspectCodeSettings> InspectCodeSettingsBase => _ => _
.SetTargetPath(Solution)
.SetOutput(InspectCodeReportFile)
.SetSeverity(ReSharperSeverity.WARNING)
.When(RootDirectory.Contains(DotNetPath), _ => _
.SetDotNetCore(DotNetPath));
Configure<ReSharperInspectCodeSettings> InspectCodeSettings => _ => _;
bool InspectCodeFailOnError => true;
bool InspectCodeFailOnWarning => true;
bool InspectCodeReportIssueSummary => true;
bool InspectCodeReportWarnings => true;
IEnumerable<string> InspectCodeFailOnIssues => new string[0];
IEnumerable<string> InspectCodeFailOnCategories => new string[0];
void InspectCodeCheckResults()
{
var issueTypes = XmlTasks.XmlPeekElements(InspectCodeReportFile, "//Report/IssueTypes/IssueType")
.Select(x => (
Id: x.GetAttributeValue("Id"),
CategoryId: x.GetAttributeValue("CategoryId"),
Severity: x.GetAttributeValue("Severity")))
.ToDictionary(x => x.Id, x => x);
var issues = XmlTasks.XmlPeekElements(InspectCodeReportFile, "//Report/Issues/Project/Issue")
.Select(x => (
TypeId: x.GetAttributeValue("TypeId"),
Message: x.GetAttributeValue("Message"),
File: x.GetAttributeValue("File"),
Line: x.GetAttributeValue("Line")))
.Select(x => (
x.TypeId,
x.Message,
x.File,
x.Line,
issueTypes[x.TypeId].Severity,
issueTypes[x.TypeId].CategoryId))
.Where(x => x.Severity == nameof(ReSharperSeverity.ERROR) ||
x.Severity == nameof(ReSharperSeverity.WARNING))
.OrderBy(x => x.File).ToList();
foreach (var issue in issues)
{
if (issue.Severity == nameof(ReSharperSeverity.WARNING) &&
!InspectCodeReportWarnings &&
!InspectCodeFailOnIssues.Contains(issue.TypeId) &&
!InspectCodeFailOnCategories.Contains(issue.CategoryId))
continue;
Log.Debug("[{File}:{Line}] {TypeId}: {Message}", issue.File, issue.Line, issue.TypeId, issue.Message);
}
if (InspectCodeReportIssueSummary)
InspectCodeWriteIssueSummary(issues);
ReportIssueCount(issues);
}
void InspectCodeWriteIssueSummary(List<(string TypeId, string Message, string File, string Line, string Severity, string CategoryId)> issues)
{
var indentation = issues.Count.ToString().Length + 2;
foreach (var issuesByCategory in issues.GroupBy(x => x.CategoryId).OrderBy(x => x.Key))
{
Log.Information("{IssueCategory} ({Number})", issuesByCategory.Key, issuesByCategory.Count());
foreach (var issuesByType in issuesByCategory.GroupBy(x => x.TypeId).OrderByDescending(x => x.Count()))
{
// if (issueTypes[issuesByType.Key].Severity == nameof(ReSharperSeverity.ERROR) && InspectCodeFailOnError ||
// issueTypes[issuesByType.Key].Severity == nameof(ReSharperSeverity.WARNING) &&
// (InspectCodeFailOnError)
Log.Information("{Count} {Type}", issuesByType.Count().ToString().PadLeft(indentation), issuesByType.Key);
}
}
}
sealed void ReportIssueCount(
List<(string TypeId, string Message, string File, string Line, string Severity, string CategoryId)> issues)
{
var errorCount = issues.Count(x => x.Severity == nameof(ReSharperSeverity.ERROR));
var warningCount = issues.Count(x => x.Severity == nameof(ReSharperSeverity.WARNING));
// TODO: logging
var summaryMessage = $"Found {errorCount} errors and {warningCount} warnings in {Solution}.";
if (InspectCodeFailOnError && errorCount > 0 ||
InspectCodeFailOnWarning && warningCount > 0 ||
issues.Any(x => InspectCodeFailOnIssues.Contains(x.TypeId)) ||
issues.Any(x => InspectCodeFailOnCategories.Contains(x.CategoryId)))
Assert.Fail(summaryMessage);
else if (errorCount > 0 || warningCount > 0)
Log.Warning(summaryMessage);
ReportSummary(_ => _
.When(errorCount > 0, _ => _
.AddPair("Errors", errorCount.ToString()))
.When(warningCount > 0, _ => _
.AddPair("Warnings", warningCount.ToString())));
}
}
|
IReportIssues
|
csharp
|
icsharpcode__ILSpy
|
ILSpy/Util/MessageBus.cs
|
{
"start": 2616,
"end": 2733
}
|
public class ____(PropertyChangedEventArgs e) : WrappedEventArgs<PropertyChangedEventArgs>(e);
|
SettingsChangedEventArgs
|
csharp
|
unoplatform__uno
|
src/SourceGenerators/Uno.UI.SourceGenerators.Tests/ImplementedRoutedEventsGeneratorTests/Given_ImplementedRoutedEventsGenerator.cs
|
{
"start": 1177,
"end": 1285
}
|
public partial class ____ : Control
{
}
";
const string expectedCode = @"// <auto-generated>
|
MyAwesomeControl
|
csharp
|
cake-build__cake
|
src/Cake.Common/Tools/NuGet/Push/NuGetPushSettings.cs
|
{
"start": 408,
"end": 2624
}
|
public sealed class ____ : ToolSettings
{
/// <summary>
/// Gets or sets the server URL.
/// When using NuGet pre 3.4.2, this value is optional
/// and nuget.org is used if omitted (unless DefaultPushSource
/// config value is set in the NuGet config file.
/// When using NuGet 3.4.2 (or more recent), this value is mandatory.
/// Starting with NuGet 2.5, if NuGet.exe identifies a UNC/folder source,
/// it will perform the file copy to the source.
/// </summary>
/// <value>The server URL.</value>
/// <remarks>
/// For your convenience, here is the URL for some of the most popular
/// public NuGet servers:
/// - NuGet Gallery: https://nuget.org/api/v2/package
/// - MyGet: https://www.myget.org/F/<your_username>/api/v2/package.
/// </remarks>
public string Source { get; set; }
/// <summary>
/// Gets or sets the API key for the server.
/// </summary>
/// <value>The API key for the server.</value>
public string ApiKey { get; set; }
/// <summary>
/// Gets or sets the timeout for pushing to a server.
/// Defaults to 300 seconds (5 minutes).
/// </summary>
/// <value>The timeout for pushing to a server.</value>
public TimeSpan? Timeout { get; set; }
/// <summary>
/// Gets or sets the verbosity.
/// </summary>
/// <value>The verbosity.</value>
public NuGetVerbosity? Verbosity { get; set; }
/// <summary>
/// Gets or sets the NuGet configuration file.
/// </summary>
/// <value>The NuGet configuration file.</value>
public FilePath ConfigFile { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to skip a package and continue with
/// the next package in the push, if any when a package with the same version
/// already exists.
/// </summary>
/// <value>
/// <c>true</c> if skipping duplicates; otherwise, <c>false</c>.
/// </value>
public bool SkipDuplicate { get; set; }
}
}
|
NuGetPushSettings
|
csharp
|
aspnetboilerplate__aspnetboilerplate
|
test/aspnet-core-demo/AbpAspNetCoreDemo/Pages/ResultFilterPageDemo.cshtml.cs
|
{
"start": 131,
"end": 351
}
|
public class ____ : AbpPageModel
{
public IActionResult OnGet()
{
return Content("OnGet");
}
public JsonResult OnPost()
{
return new JsonResult("OnPost");
}
}
|
ResultFilterPageDemoModel
|
csharp
|
AutoFixture__AutoFixture
|
Src/AutoFixtureUnitTest/TaggedNode.cs
|
{
"start": 117,
"end": 548
}
|
public class ____ : CompositeSpecimenBuilder
{
public TaggedNode(object tag, params ISpecimenBuilder[] builders)
: base(builders)
{
this.Tag = tag;
}
public override ISpecimenBuilderNode Compose(IEnumerable<ISpecimenBuilder> builders)
{
return new TaggedNode(this.Tag, builders.ToArray());
}
public object Tag { get; }
}
}
|
TaggedNode
|
csharp
|
getsentry__sentry-dotnet
|
test/Sentry.AspNetCore.Tests/IntegrationMockedBackgroundWorker.cs
|
{
"start": 564,
"end": 10872
}
|
public class ____ : SentrySdkTestFixture
{
private IBackgroundWorker Worker { get; set; } = Substitute.For<IBackgroundWorker>();
protected Action<SentryAspNetCoreOptions> Configure;
public IntegrationMockedBackgroundWorker(ITestOutputHelper output)
{
ConfigureWebHost = builder =>
{
_ = builder.UseSentry(options =>
{
options.Dsn = ValidDsn;
options.BackgroundWorker = Worker;
options.DiagnosticLogger = new TestOutputDiagnosticLogger(output);
Configure?.Invoke(options);
});
};
}
[Fact]
public async Task DisabledSdk_UnhandledException_NoEventCaptured()
{
Configure = o => o.InitializeSdk = false;
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.DidNotReceive().EnqueueEnvelope(Arg.Any<Envelope>());
Assert.False(ServiceProvider.GetRequiredService<IHub>().IsEnabled);
}
[Fact]
public void DisabledSdk_WithLogger_NoEventCaptured()
{
Configure = o => o.InitializeSdk = false;
Build();
var logger = ServiceProvider.GetRequiredService<ILogger<IntegrationMockedBackgroundWorker>>();
logger.LogCritical("test");
_ = Worker.DidNotReceive().EnqueueEnvelope(Arg.Any<Envelope>());
Assert.False(ServiceProvider.GetRequiredService<IHub>().IsEnabled);
}
[Fact]
public void LogError_ByDefault_EventCaptured()
{
const string expectedMessage = "test";
Build();
var logger = ServiceProvider.GetRequiredService<ILogger<IntegrationMockedBackgroundWorker>>();
logger.LogError(expectedMessage);
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Message
.Formatted == expectedMessage
));
}
[Fact]
public void LogError_WithFormat_EventCaptured()
{
const string expectedMessage = "Test {structured} log";
const int param = 10;
Build();
var logger = ServiceProvider.GetRequiredService<ILogger<IntegrationMockedBackgroundWorker>>();
logger.LogError(expectedMessage, param);
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Message
.Formatted == $"Test {param} log"
&&
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Message
.Message == expectedMessage
));
}
[Fact]
public void DiagnosticLogger_DebugEnabled_ReplacedWithMelLogger()
{
Configure = o => o.Debug = true;
Build();
var options = ServiceProvider.GetRequiredService<IOptions<SentryAspNetCoreOptions>>();
_ = Assert.IsType<MelDiagnosticLogger>(options.Value.DiagnosticLogger);
}
[Fact]
public void DiagnosticLogger_ByDefault_IsNull()
{
Build();
var options = ServiceProvider.GetRequiredService<IOptions<SentryAspNetCoreOptions>>();
Assert.Null(options.Value.DiagnosticLogger);
}
[Fact]
public void SentryClient_CaptureMessage_EventCaptured()
{
const string expectedMessage = "test";
Build();
var client = ServiceProvider.GetRequiredService<ISentryClient>();
_ = client.CaptureMessage(expectedMessage);
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Message
.Message == expectedMessage
));
}
[Fact]
public void Hub_CaptureMessage_EventCaptured()
{
const string expectedMessage = "test";
Build();
var client = ServiceProvider.GetRequiredService<IHub>();
_ = client.CaptureMessage(expectedMessage);
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Message
.Message == expectedMessage
));
}
[Fact]
public async Task SendDefaultPii_FalseWithoutUserInRequest_NoUserNameSent()
{
Configure = o => o.SendDefaultPii = false;
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.User
.Username == null
));
}
[Fact]
public async Task SendDefaultPii_TrueWithoutUserInRequest_NoUserNameSent()
{
Configure = o => o.SendDefaultPii = true; // Sentry package will set to Environment.UserName
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.User
.Username == null
));
}
[Fact]
public async Task SendDefaultPii_TrueWithUserInRequest_UserNameSent()
{
const string expectedName = "sentry user";
Configure = o => o.SendDefaultPii = true; // Sentry package will set to Environment.UserName
ConfigureApp = app =>
{
_ = app.Use(async (context, next) =>
{
context.User = new GenericPrincipal(new GenericIdentity(expectedName), Array.Empty<string>());
await next();
});
};
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.User
.Username == expectedName
));
}
[Fact]
public void AllSettingsViaJson()
{
ConfigureWebHost = b =>
{
_ = b.ConfigureAppConfiguration(c =>
{
_ = c.SetBasePath(Directory.GetCurrentDirectory()); // fails on net462 without this
_ = c.AddJsonFile("allsettings.json", optional: false);
});
_ = b.UseSentry(o => o.BackgroundWorker = Worker);
};
Build();
var options = ServiceProvider.GetRequiredService<IOptions<SentryAspNetCoreOptions>>().Value;
Assert.Equal("https://1@sentry.yo/1", options.Dsn);
Assert.Equal(RequestSize.Always, options.MaxRequestBodySize);
Assert.True(options.SendDefaultPii);
Assert.True(options.IncludeActivityData);
Assert.Equal(LogLevel.Error, options.MinimumBreadcrumbLevel);
Assert.Equal(LogLevel.Critical, options.MinimumEventLevel);
Assert.False(options.InitializeSdk);
Assert.Equal(999, options.MaxBreadcrumbs);
Assert.Equal(1, options.SampleRate);
Assert.Equal("7f5d9a1", options.Release);
Assert.Equal("Staging", options.Environment);
Assert.Equal(1, options.TracesSampleRate);
var targets = options.TracePropagationTargets.Select(t => t.ToString());
Assert.Equal(new[] { "foo", "bar", "^abc.*ghi$" }, targets);
}
[Fact]
public async Task Environment_OnOptions_ValueFromOptions()
{
const string expected = "environment";
Configure = o => o.Environment = expected;
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Environment == expected
));
}
[Fact]
public async Task Environment_NotOnOptions_ValueFromHostingEnvironment()
{
const string expected = "environment";
Build(environment: expected);
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Environment == expected
));
}
[Fact]
public async Task Environment_BothOnOptionsAndEnvVar_ValueFromOption()
{
const string expected = "environment";
const string other = "other";
Configure = o =>
{
o.Environment = expected;
o.FakeSettings().EnvironmentVariables["ASPNETCORE_ENVIRONMENT"] = other;
};
Build();
_ = await HttpClient.GetAsync("/throw");
_ = Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(e =>
e.Items
.Select(i => i.Payload)
.OfType<JsonSerializable>()
.Select(i => i.Source)
.OfType<SentryEvent>()
.Single()
.Environment == expected
));
}
}
|
IntegrationMockedBackgroundWorker
|
csharp
|
dotnet__aspire
|
src/Aspire.Hosting.Maui/MauiWindowsExtensions.cs
|
{
"start": 348,
"end": 4357
}
|
public static class ____
{
/// <summary>
/// Adds a Windows device resource to run the MAUI application on the Windows platform.
/// </summary>
/// <param name="builder">The MAUI project resource builder.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// This method creates a new Windows platform resource that will run the MAUI application
/// targeting the Windows platform using <c>dotnet run</c>. The resource does not auto-start
/// and must be explicitly started from the dashboard by clicking the start button.
/// <para>
/// The resource name will default to "{projectName}-windows".
/// </para>
/// </remarks>
/// <example>
/// Add a Windows device to a MAUI project:
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// var maui = builder.AddMauiProject("mauiapp", "../MyMauiApp/MyMauiApp.csproj");
/// var windowsDevice = maui.AddWindowsDevice();
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<MauiWindowsPlatformResource> AddWindowsDevice(
this IResourceBuilder<MauiProjectResource> builder)
{
ArgumentNullException.ThrowIfNull(builder);
var name = $"{builder.Resource.Name}-windows";
return builder.AddWindowsDevice(name);
}
/// <summary>
/// Adds a Windows device resource to run the MAUI application on the Windows platform with a specific name.
/// </summary>
/// <param name="builder">The MAUI project resource builder.</param>
/// <param name="name">The name of the Windows device resource.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// This method creates a new Windows platform resource that will run the MAUI application
/// targeting the Windows platform using <c>dotnet run</c>. The resource does not auto-start
/// and must be explicitly started from the dashboard by clicking the start button.
/// <para>
/// You can add multiple Windows device resources to a MAUI project by calling this method multiple times with different names.
/// </para>
/// </remarks>
/// <example>
/// Add multiple Windows devices to a MAUI project:
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// var maui = builder.AddMauiProject("mauiapp", "../MyMauiApp/MyMauiApp.csproj");
/// var windowsDevice1 = maui.AddWindowsDevice("windows-device-1");
/// var windowsDevice2 = maui.AddWindowsDevice("windows-device-2");
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<MauiWindowsPlatformResource> AddWindowsDevice(
this IResourceBuilder<MauiProjectResource> builder,
[ResourceName] string name)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
// Get the absolute project path and working directory
var (projectPath, workingDirectory) = MauiPlatformHelper.GetProjectPaths(builder);
var windowsResource = new MauiWindowsPlatformResource(name, builder.Resource);
var resourceBuilder = builder.ApplicationBuilder.AddResource(windowsResource)
.WithAnnotation(new MauiProjectMetadata(projectPath))
.WithAnnotation(new ExecutableAnnotation
{
Command = "dotnet",
WorkingDirectory = workingDirectory
});
// Configure the platform resource with common settings
MauiPlatformHelper.ConfigurePlatformResource(
resourceBuilder,
projectPath,
"windows",
"Windows",
"net10.0-windows10.0.19041.0",
OperatingSystem.IsWindows,
"Desktop");
return resourceBuilder;
}
}
|
MauiWindowsExtensions
|
csharp
|
AvaloniaUI__Avalonia
|
src/Avalonia.Base/VisualTree/IHostedVisualTreeRoot.cs
|
{
"start": 166,
"end": 408
}
|
public interface ____
{
/// <summary>
/// Gets the visual tree host.
/// </summary>
/// <value>
/// The visual tree host.
/// </value>
Visual? Host { get; }
}
}
|
IHostedVisualTreeRoot
|
csharp
|
abpframework__abp
|
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Card/AbpCardBackgroundTagHelperService.cs
|
{
"start": 194,
"end": 738
}
|
public class ____ : AbpTagHelperService<AbpCardBackgroundTagHelper>
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
SetBackground(context, output);
}
protected virtual void SetBackground(TagHelperContext context, TagHelperOutput output)
{
if (TagHelper.Background == AbpCardBackgroundType.Default)
{
return;
}
output.Attributes.AddClass("bg-" + TagHelper.Background.ToString().ToLowerInvariant());
}
}
|
AbpCardBackgroundTagHelperService
|
csharp
|
unoplatform__uno
|
src/Uno.UI/UI/Xaml/Controls/Popup/Popup.Base.cs
|
{
"start": 5647,
"end": 7314
}
|
internal interface ____
{
/// <summary>
/// Measure the content of the popup
/// </summary>
/// <param name="available">The available size to place to render the popup. This is expected to be the screen size.</param>
/// <param name="visibleSize">The size of the visible bounds of the window. This is expected to be AtMost the available.</param>
/// <returns>The desired size to render the content</returns>
Size Measure(Size available, Size visibleSize);
/// <summary>
/// Render the content of the popup at its final location
/// </summary>
/// <param name="finalSize">The final size available to render the view. This is expected to be the screen size.</param>
/// <param name="visibleBounds">The frame of the visible bounds of the window. This is expected to be AtMost the finalSize.</param>
/// <param name="desiredSize">The size at which the content expect to be rendered. This is the result of the last <see cref="Measure"/>.</param>
/// <param name="upperLeftOffset">Coordinate system adjustment, applied to the resulting frame computed from the popup content</param>
void Arrange(Size finalSize, Rect visibleBounds, Size desiredSize);
}
partial void OnIsLightDismissEnabledChangedPartial(bool oldIsLightDismissEnabled, bool newIsLightDismissEnabled)
{
}
event EventHandler<object> IPopup.Closed
{
add => Closed += value;
remove => Closed -= value;
}
event EventHandler<object> IPopup.Opened
{
add => Opened += value;
remove => Opened -= value;
}
bool IPopup.IsOpen
{
get => IsOpen;
set => IsOpen = value;
}
UIElement IPopup.Child
{
get => Child;
set => Child = value;
}
}
|
IDynamicPopupLayouter
|
csharp
|
dotnet__extensions
|
src/Libraries/Microsoft.Extensions.Http.Resilience/Resilience/ResilienceHttpClientBuilderExtensions.StandardResilience.cs
|
{
"start": 5045,
"end": 5199
}
|
private sealed record ____(string PipelineName, IServiceCollection Services) : IHttpStandardResiliencePipelineBuilder;
}
|
HttpStandardResiliencePipelineBuilder
|
csharp
|
grpc__grpc-dotnet
|
examples/Liber/Common/Name.cs
|
{
"start": 754,
"end": 1297
}
|
public partial class ____
{
public static Name Parse(string name)
{
var parts = name.Split(' ');
if (parts.Length != 3)
{
throw new ArgumentException("Name must have three parts.");
}
return new Name
{
FirstName = parts[0],
MiddleName = parts[1],
LastName = parts[2]
};
}
public string FullName => string.Join(" ", FirstName, MiddleName, LastName);
}
}
|
Name
|
csharp
|
nopSolutions__nopCommerce
|
src/Presentation/Nop.Web/Models/Catalog/VendorProductReviewsListModel.cs
|
{
"start": 69,
"end": 427
}
|
public partial record ____ : BaseNopModel
{
public int VendorId { get; set; }
public string VendorName { get; set; }
public string VendorUrl { get; set; }
public VendorReviewsPagingFilteringModel PagingFilteringContext { get; set; } = new();
public List<VendorProductReviewModel> Reviews { get; set; } = new();
}
|
VendorProductReviewsListModel
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Core/test/Types.Analyzers.Tests/ExtendObjectTypeAnalyzerTests.cs
|
{
"start": 1807,
"end": 2062
}
|
partial class ____
{
public static string GetDisplayName(Product product)
=> $"{product.Name} (ID: {product.Id})";
}
[ExtendObjectType<Brand>]
public static
|
ProductExtensions
|
csharp
|
dotnet__maui
|
src/Controls/tests/SourceGen.UnitTests/InitializeComponent/XStaticUnresolvedType.cs
|
{
"start": 5068,
"end": 5924
}
|
public static class ____
{
public static string AppName => "TestApp";
}
}
""";
var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml");
var expected =
$$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a .NET MAUI source generator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS0219 // Variable is assigned but its value is never used
namespace Test;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")]
|
AppConstants
|
csharp
|
nopSolutions__nopCommerce
|
src/Libraries/Nop.Services/Media/RoxyFileman/RoxyFilemanException.cs
|
{
"start": 213,
"end": 2290
}
|
public partial class ____ : Exception
{
#region Fields
protected static Dictionary<string, string> _languageResources;
#endregion
#region Ctor
private RoxyFilemanException() : base()
{
}
/// <summary>
/// Initializes a new instance of the RoxyFilemanException
/// </summary>
/// <param name="key">Roxy language resource key</param>
public RoxyFilemanException(string key) : base(GetLocalizedMessage(key))
{
}
/// <summary>
/// Initializes a new instance of the RoxyFilemanException
/// </summary>
/// <param name="key">Roxy language resource key</param>
/// <param name="innerException">The exception that is the cause of the current exception</param>
public RoxyFilemanException(string key, Exception innerException) : base(GetLocalizedMessage(key), innerException)
{
}
#endregion
#region Utilities
/// <summary>
/// Get the language resource value
/// </summary>
/// <param name="key">Language resource key</param>
/// <returns>
/// The language resource value
/// </returns>
protected static string GetLocalizedMessage(string key)
{
var fileProvider = EngineContext.Current.Resolve<INopFileProvider>();
var roxyConfig = Singleton<RoxyFilemanConfig>.Instance;
var languageFile = fileProvider.GetAbsolutePath($"{NopRoxyFilemanDefaults.LanguageDirectory}/{roxyConfig.LANG}.json");
if (!fileProvider.FileExists(languageFile))
languageFile = fileProvider.GetAbsolutePath($"{NopRoxyFilemanDefaults.LanguageDirectory}/en.json");
if (_languageResources is null)
{
var json = fileProvider.ReadAllTextAsync(languageFile, Encoding.UTF8).Result;
_languageResources = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
if (_languageResources is null)
return key;
if (_languageResources.TryGetValue(key, out var value))
return value;
return key;
}
#endregion
}
|
RoxyFilemanException
|
csharp
|
nunit__nunit
|
src/NUnitFramework/tests/Assertions/AssertThrowsTests.cs
|
{
"start": 249,
"end": 7472
}
|
public class ____
{
[Test]
public void ThrowsSucceedsWithDelegate()
{
Assert.Throws(typeof(ArgumentException), delegate { throw new ArgumentException(); });
}
[Test]
public void AssertThrowsDoesNotDiscardOutput()
{
Console.WriteLine(1);
Assert.Throws<Exception>(() =>
{
Console.WriteLine(2);
TestContext.Out.WriteLine(3);
throw new Exception("test");
});
Console.WriteLine(4);
var nl = Environment.NewLine;
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Output,
Is.EqualTo($"1{nl}2{nl}3{nl}4{nl}"));
}
[Test]
public void ThrowsConstraintDoesNotDiscardOutput()
{
Console.WriteLine(1);
Assert.That(() =>
{
Console.WriteLine(2);
TestContext.Out.WriteLine(3);
throw new Exception("test");
},
Throws.Exception);
Console.WriteLine(4);
var nl = Environment.NewLine;
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Output,
Is.EqualTo($"1{nl}2{nl}3{nl}4{nl}"));
}
[Test]
public void GenericThrowsSucceedsWithDelegate()
{
Assert.Throws<ArgumentException>(
delegate { throw new ArgumentException(); });
}
[Test]
public void ThrowsConstraintSucceedsWithDelegate()
{
// Without cast, delegate is ambiguous before C# 3.0.
Assert.That((TestDelegate)delegate { throw new ArgumentException(); },
Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
public void ThrowsSucceedsWithLambda()
{
Assert.Throws(typeof(ArgumentException), () => throw new ArgumentException());
}
[Test]
public void GenericThrowsSucceedsWithLambda()
{
Assert.Throws<ArgumentException>(() => throw new ArgumentException());
}
[Test]
public void ThrowsConstraintSucceedsWithLambda()
{
Assert.That(() => throw new ArgumentException(),
Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
public void GenericThrowsReturnsCorrectException()
{
var ex = Assert.Throws<ArgumentException>(
() => throw new ArgumentException("myMessage", "myParam")) as ArgumentException;
Assert.That(ex, Is.Not.Null, "No ArgumentException thrown");
Assert.Multiple(() =>
{
Assert.That(ex!.Message, Does.StartWith("myMessage"));
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
});
CheckForSpuriousAssertionResults();
}
[Test]
public void ThrowsReturnsCorrectException()
{
var ex = Assert.Throws(typeof(ArgumentException),
() => throw new ArgumentException("myMessage", "myParam")) as ArgumentException;
Assert.That(ex, Is.Not.Null, "No ArgumentException thrown");
Assert.Multiple(() =>
{
Assert.That(ex!.Message, Does.StartWith("myMessage"));
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
});
CheckForSpuriousAssertionResults();
}
[Test]
public void NoExceptionThrown()
{
var ex = CatchException(() =>
Assert.Throws<ArgumentException>(TestDelegates.ThrowsNothing));
Assert.That(ex, Is.Not.Null);
Assert.That(ex!.Message, Does.Contain(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: null" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void UnrelatedExceptionThrown()
{
var ex = CatchException(() =>
Assert.Throws<ArgumentException>(TestDelegates.ThrowsNullReferenceException));
Assert.That(ex, Is.Not.Null);
Assert.That(ex!.Message, Does.Contain(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.NullReferenceException: my message" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void BaseExceptionThrown()
{
var ex = CatchException(() =>
Assert.Throws<ArgumentException>(TestDelegates.ThrowsSystemException));
Assert.That(ex, Is.Not.Null);
Assert.That(ex!.Message, Does.Contain(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.Exception: my message" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test, SetUICulture("en-US")]
public void DerivedExceptionThrown()
{
var ex = CatchException(() =>
Assert.Throws<Exception>(TestDelegates.ThrowsArgumentException));
Assert.That(ex, Is.Not.Null);
Assert.That(ex!.Message, Does.Contain(
" Expected: <System.Exception>" + Environment.NewLine +
" But was: <System.ArgumentException: myMessage"));
CheckForSpuriousAssertionResults();
}
[Test]
public void AssertThrowsWrappingAssertFail()
{
Assert.Throws<AssertionException>(() => Assert.Fail());
CheckForSpuriousAssertionResults();
}
[Test]
public void ThrowsConstraintWrappingAssertFail()
{
Assert.That(() => Assert.Fail(),
Throws.Exception.TypeOf<AssertionException>());
CheckForSpuriousAssertionResults();
}
[Test]
public void AssertDoesNotThrowSucceeds()
{
Assert.DoesNotThrow(TestDelegates.ThrowsNothing);
}
[Test]
public void AssertDoesNotThrowFails()
{
var ex = CatchException(() =>
Assert.DoesNotThrow(TestDelegates.ThrowsArgumentException));
Assert.That(ex, Is.Not.Null.With.TypeOf<AssertionException>());
CheckForSpuriousAssertionResults();
}
private static void CheckForSpuriousAssertionResults()
{
var result = TestExecutionContext.CurrentContext.CurrentResult;
Assert.That(result.AssertionResults, Is.Empty,
"Spurious result left by Assert.Fail()");
}
private Exception? CatchException(TestDelegate del)
{
using (new TestExecutionContext.IsolatedContext())
{
try
{
del();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
}
}
|
AssertThrowsTests
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.Data/Commands/SavePredictorCommand.cs
|
{
"start": 814,
"end": 882
}
|
internal sealed class ____ : ICommand
{
|
SavePredictorCommand
|
csharp
|
aspnetboilerplate__aspnetboilerplate
|
src/Abp.EntityFrameworkCore/EntityFrameworkCore/AbpEntityFrameworkCoreModule.cs
|
{
"start": 1891,
"end": 2832
}
|
class ____ derived from AbpDbContext.");
return;
}
using (IScopedIocResolver scope = IocManager.CreateScope())
{
foreach (var dbContextType in dbContextTypes)
{
Logger.Debug("Registering DbContext: " + dbContextType.AssemblyQualifiedName);
scope.Resolve<IEfGenericRepositoryRegistrar>().RegisterForDbContext(dbContextType, IocManager, EfCoreAutoRepositoryTypes.Default);
IocManager.IocContainer.Register(
Component.For<ISecondaryOrmRegistrar>()
.Named(Guid.NewGuid().ToString("N"))
.Instance(new EfCoreBasedSecondaryOrmRegistrar(dbContextType, scope.Resolve<IDbContextEntityFinder>()))
.LifestyleTransient()
);
}
scope.Resolve<IDbContextTypeMatcher>().Populate(dbContextTypes);
}
}
}
|
found
|
csharp
|
pythonnet__pythonnet
|
src/runtime/PythonEngine.cs
|
{
"start": 23816,
"end": 23941
}
|
public enum ____ : int
{
Single = 256,
File = 257, /* Py_file_input */
Eval = 258
}
}
|
RunFlagType
|
csharp
|
mongodb__mongo-csharp-driver
|
tests/MongoDB.Driver.Tests/MongoServerAddressTests.cs
|
{
"start": 673,
"end": 4129
}
|
public class ____
{
[Theory]
[InlineData("host")]
[InlineData("192.168.0.1")]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]")]
public void TestConstructor_with_host(string host)
{
var address = new MongoServerAddress(host);
Assert.Equal(host, address.Host);
Assert.Equal(27017, address.Port);
}
[Theory]
[InlineData("host", 27017)]
[InlineData("host", 27018)]
[InlineData("192.168.0.1", 27017)]
[InlineData("192.168.0.1", 27018)]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]", 27017)]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]", 27018)]
public void TestConstructor_with_host_and_port(string host, int port)
{
var address = new MongoServerAddress(host, port);
Assert.Equal(host, address.Host);
Assert.Equal(port, address.Port);
}
[Fact]
public void TestEquals()
{
var a = new MongoServerAddress("host1");
var b = new MongoServerAddress("host1");
var c = new MongoServerAddress("host2");
var n = (MongoServerAddress)null;
Assert.True(object.Equals(a, b));
Assert.False(object.Equals(a, c));
Assert.False(a.Equals(n));
Assert.False(a.Equals(null));
Assert.True(a == b);
Assert.False(a == c);
Assert.False(a == null);
Assert.False(null == a);
Assert.True(n == null);
Assert.True(null == n);
Assert.False(a != b);
Assert.True(a != c);
Assert.True(a != null);
Assert.True(null != a);
Assert.False(n != null);
Assert.False(null != n);
}
[Theory]
[InlineData("host", 27017, "host")]
[InlineData("host", 27017, "host:27017")]
[InlineData("host", 27018, "host:27018")]
[InlineData("192.168.0.1", 27017, "192.168.0.1")]
[InlineData("192.168.0.1", 27017, "192.168.0.1:27017")]
[InlineData("192.168.0.1", 27018, "192.168.0.1:27018")]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]", 27017, "[2001:0db8:85a3:0042:0000:8a2e:0370:7334]")]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]", 27017, "[2001:0db8:85a3:0042:0000:8a2e:0370:7334]:27017")]
[InlineData("[2001:0db8:85a3:0042:0000:8a2e:0370:7334]", 27018, "[2001:0db8:85a3:0042:0000:8a2e:0370:7334]:27018")]
public void TestParse(string host, int port, string value)
{
var address = MongoServerAddress.Parse(value);
Assert.Equal(host, address.Host);
Assert.Equal(port, address.Port);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("abc:def")]
[InlineData("abc:123:456")]
[InlineData("[]")]
[InlineData("a[]")]
[InlineData("[]b")]
[InlineData("a[]b")]
public void TestParse_InvalidValue(string value)
{
var expection = Record.Exception(() => MongoServerAddress.Parse(value));
Assert.IsType<FormatException>(expection);
var expectedMessage = string.Format("'{0}' is not a valid server address.", value);
Assert.Equal(expectedMessage, expection.Message);
}
}
}
|
MongoServerAddressTests
|
csharp
|
App-vNext__Polly
|
src/Snippets/Docs/Hedging.cs
|
{
"start": 189,
"end": 4845
}
|
internal static class ____
{
public static void Usage()
{
#region hedging
// Hedging with default options.
// See https://www.pollydocs.org/strategies/hedging#defaults for defaults.
var optionsDefaults = new HedgingStrategyOptions<HttpResponseMessage>();
// A customized hedging strategy that retries up to 3 times if the execution
// takes longer than 1 second or if it fails due to an exception or returns an HTTP 500 Internal Server Error.
var optionsComplex = new HedgingStrategyOptions<HttpResponseMessage>
{
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<SomeExceptionType>()
.HandleResult(response => response.StatusCode == HttpStatusCode.InternalServerError),
MaxHedgedAttempts = 3,
Delay = TimeSpan.FromSeconds(1),
ActionGenerator = static args =>
{
Console.WriteLine("Preparing to execute hedged action.");
// Return a delegate function to invoke the original action with the action context.
// Optionally, you can also create a completely new action to be executed.
return () => args.Callback(args.ActionContext);
}
};
// Subscribe to hedging events.
var optionsOnHedging = new HedgingStrategyOptions<HttpResponseMessage>
{
OnHedging = static args =>
{
Console.WriteLine($"OnHedging: Attempt number {args.AttemptNumber}");
return default;
}
};
// Add a hedging strategy with a HedgingStrategyOptions<TResult> instance to the pipeline
new ResiliencePipelineBuilder<HttpResponseMessage>().AddHedging(optionsDefaults);
#endregion
}
public static void DynamicMode()
{
#region hedging-dynamic-mode
new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddHedging(new()
{
MaxHedgedAttempts = 3,
DelayGenerator = args =>
{
var delay = args.AttemptNumber switch
{
0 or 1 => TimeSpan.Zero, // Parallel mode
_ => TimeSpan.FromSeconds(-1) // switch to Fallback mode
};
return new ValueTask<TimeSpan>(delay);
}
});
#endregion
}
public static void ActionGenerator()
{
var customDataKey = new ResiliencePropertyKey<string>("my-key");
#region hedging-action-generator
new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddHedging(new()
{
ActionGenerator = args =>
{
// You can access data from the original (primary) context here
var customData = args.PrimaryContext.Properties.GetValue(customDataKey, "default-custom-data");
Console.WriteLine($"Hedging, Attempt: {args.AttemptNumber}, Custom Data: {customData}");
// Here, we can access the original callback and return it or return a completely new action
var callback = args.Callback;
// A function that returns a ValueTask<Outcome<HttpResponseMessage>> is required.
return async () =>
{
try
{
// A dedicated ActionContext is provided for each hedged action.
// It comes with a separate CancellationToken created specifically for this hedged attempt,
// which can be cancelled later if needed.
//
// Note that the "MyRemoteCallAsync" call won't have any additional resilience applied.
// You are responsible for wrapping it with any additional resilience pipeline.
var response = await MyRemoteCallAsync(args.ActionContext.CancellationToken);
return Outcome.FromResult(response);
}
catch (Exception e)
{
// Note: All exceptions should be caught and converted to Outcome.
return Outcome.FromException<HttpResponseMessage>(e);
}
};
}
});
#endregion
}
#region hedging-resilience-keys
|
Hedging
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdatePartEditorContext.cs
|
{
"start": 157,
"end": 391
}
|
public class ____ : BuildPartEditorContext
{
public UpdatePartEditorContext(ContentTypePartDefinition typePartDefinition, UpdateEditorContext context)
: base(typePartDefinition, context)
{
}
}
|
UpdatePartEditorContext
|
csharp
|
protobuf-net__protobuf-net
|
src/protobuf-net.Core/BufferPool.cs
|
{
"start": 88,
"end": 1985
}
|
internal static class ____
{
private static readonly ArrayPool<byte> _pool = ArrayPool<byte>.Shared;
internal const int BUFFER_LENGTH = 1024;
internal static byte[] GetBuffer() => GetBuffer(BUFFER_LENGTH);
internal static byte[] GetBuffer(int minSize)
{
byte[] cachedBuff = GetCachedBuffer(minSize);
return cachedBuff ?? new byte[minSize];
}
internal static byte[] GetCachedBuffer(int minSize) => _pool.Rent(minSize);
// https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element
private const int MaxByteArraySize = int.MaxValue - 56;
internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes)
{
Debug.Assert(buffer is not null);
Debug.Assert(toFitAtLeastBytes > buffer.Length);
Debug.Assert(copyFromIndex >= 0);
Debug.Assert(copyBytes >= 0);
int newLength = buffer.Length * 2;
if (newLength < 0)
{
newLength = MaxByteArraySize;
}
if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes;
if (copyBytes == 0)
{
ReleaseBufferToPool(ref buffer);
}
var newBuffer = GetCachedBuffer(newLength) ?? new byte[newLength];
if (copyBytes > 0)
{
Buffer.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes);
ReleaseBufferToPool(ref buffer);
}
buffer = newBuffer;
}
internal static void ReleaseBufferToPool(ref byte[] buffer)
{
var tmp = buffer;
buffer = null;
if (tmp is not null) _pool.Return(tmp);
}
}
}
|
BufferPool
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.OpenApi.Tests/GeneratedClient/Models/Authenticate.cs
|
{
"start": 429,
"end": 4869
}
|
public partial class ____
{
/// <summary>
/// Initializes a new instance of the Authenticate class.
/// </summary>
public Authenticate()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Authenticate class.
/// </summary>
public Authenticate(string provider = default(string), string state = default(string), string oauthToken = default(string), string oauthVerifier = default(string), string userName = default(string), string password = default(string), bool? rememberMe = default(bool?), string continueProperty = default(string), string nonce = default(string), string uri = default(string), string response = default(string), string qop = default(string), string nc = default(string), string cnonce = default(string), bool? useTokenCookie = default(bool?), string accessToken = default(string), string accessTokenSecret = default(string), IDictionary<string, string> meta = default(IDictionary<string, string>))
{
Provider = provider;
State = state;
OauthToken = oauthToken;
OauthVerifier = oauthVerifier;
UserName = userName;
Password = password;
RememberMe = rememberMe;
ContinueProperty = continueProperty;
Nonce = nonce;
Uri = uri;
Response = response;
Qop = qop;
Nc = nc;
Cnonce = cnonce;
UseTokenCookie = useTokenCookie;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSecret;
Meta = meta;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "provider")]
public string Provider { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "State")]
public string State { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "oauth_token")]
public string OauthToken { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "oauth_verifier")]
public string OauthVerifier { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "UserName")]
public string UserName { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Password")]
public string Password { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "RememberMe")]
public bool? RememberMe { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Continue")]
public string ContinueProperty { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "nonce")]
public string Nonce { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "uri")]
public string Uri { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "response")]
public string Response { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "qop")]
public string Qop { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "nc")]
public string Nc { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "cnonce")]
public string Cnonce { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "UseTokenCookie")]
public bool? UseTokenCookie { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "AccessToken")]
public string AccessToken { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "AccessTokenSecret")]
public string AccessTokenSecret { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Meta")]
public IDictionary<string, string> Meta { get; set; }
}
}
|
Authenticate
|
csharp
|
RicoSuter__NSwag
|
src/NSwag.CodeGeneration.TypeScript.Tests/AngularTests.cs
|
{
"start": 433,
"end": 873
}
|
public class ____ : Controller
{
[HttpPost]
public void AddMessage([FromBody, Required] Foo message)
{
}
[HttpPost]
public void GenericRequestTest1(GenericRequest1 request)
{
}
[HttpPost]
public void GenericRequestTest2(GenericRequest2 request)
{
}
}
|
DiscussionController
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/SimpleExpression.cs
|
{
"start": 414,
"end": 1634
}
|
class ____ a named
/// property and its value.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="value">The value for the property.</param>
/// <param name="operation">The SQL operation.</param>
public SimpleExpression(string propertyName, object value, string operation)
{
_propertyName = propertyName;
_value = value;
Operation = operation;
}
/// <summary>
/// Get the Sql operator to use for the specific
/// subclass of <see cref="SimpleExpression" />.
/// </summary>
protected virtual string Operation { get; }
public void SearchUsedAlias(IPredicateQuery predicateQuery)
{
predicateQuery.SearchUsedAlias(_propertyName);
}
/// <summary>
/// Converts the SimpleExpression to a SQL <see cref="string" />.
/// </summary>
/// <returns>A string that contains a valid Sql fragment.</returns>
public string ToSqlString(IPredicateQuery predicateQuery)
{
var columnName = predicateQuery.GetColumnName(_propertyName);
var parameter = predicateQuery.NewQueryParameter(_value);
return $"({columnName}{Operation}{parameter})";
}
}
|
for
|
csharp
|
dotnet__orleans
|
src/Orleans.Core/Providers/StorageSerializer/JsonGrainStorageSerializer.cs
|
{
"start": 172,
"end": 1025
}
|
public class ____ : IGrainStorageSerializer
{
private readonly OrleansJsonSerializer _orleansJsonSerializer;
/// <summary>
/// Initializes a new instance of the <see cref="JsonGrainStorageSerializer"/> class.
/// </summary>
public JsonGrainStorageSerializer(OrleansJsonSerializer orleansJsonSerializer)
{
_orleansJsonSerializer = orleansJsonSerializer;
}
/// <inheritdoc/>
public BinaryData Serialize<T>(T value)
{
var data = _orleansJsonSerializer.Serialize(value, typeof(T));
return new BinaryData(data);
}
/// <inheritdoc/>
public T Deserialize<T>(BinaryData input)
{
return (T)_orleansJsonSerializer.Deserialize(typeof(T), input.ToString());
}
}
}
|
JsonGrainStorageSerializer
|
csharp
|
unoplatform__uno
|
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ImageTests/Image_Margin_Large.xaml.cs
|
{
"start": 744,
"end": 869
}
|
partial class ____ : UserControl
{
public Image_Margin_Large()
{
this.InitializeComponent();
}
}
}
|
Image_Margin_Large
|
csharp
|
smartstore__Smartstore
|
test/Smartstore.Tests/PathUtilityTests.cs
|
{
"start": 145,
"end": 1868
}
|
public class ____
{
private static readonly List<string[]> _pathCombiners = new()
{
new[] { "/some/path/left", "../right/path/", "/some/path/right/path/" },
new[] { "some/path/left", "../../right/path/", "some/right/path/" },
new[] { "/some/path/left", "right/path/", "/some/path/left/right/path/" },
new[] { "/some/path/left", "/right/path/", "/right/path/" },
new[] { "/some/path/left/", "../../right/../path", "/some/path" },
new[] { "/some/path/left/", "right/../path", "/some/path/left/path" },
};
private static readonly List<string[]> _pathJoiners = new()
{
new[] { "/some/path/left", "/right/path/", "/some/path/left/right/path/" },
new[] { "some/path/left/", "right\\path/", "some/path/left/right/path/" },
new[] { "\\some/path/left/", "/right/path/", "/some/path/left/right/path/" }
};
[Test]
public void CanCombinePaths()
{
foreach (var combiner in _pathCombiners)
{
var path1 = combiner[0];
var path2 = combiner[1];
var combined = PathUtility.Combine(path1, path2);
Assert.That(combined, Is.EqualTo(combiner[2]));
}
}
[Test]
public void CanJoinPaths()
{
foreach (var combiner in _pathJoiners)
{
var path1 = combiner[0].AsSpan();
var path2 = combiner[1].AsSpan();
var combined = PathUtility.Join(path1, path2);
Assert.That(combined, Is.EqualTo(combiner[2]));
}
}
}
}
|
PathUtilityTests
|
csharp
|
RicoSuter__NJsonSchema
|
src/NJsonSchema.Tests/Generation/InheritanceTests.cs
|
{
"start": 12942,
"end": 13199
}
|
public class ____ : Fruit
{
public string Bar { get; set; }
}
[JsonInheritance("a", typeof(Apple))]
[JsonInheritance("o", typeof(Orange))]
[JsonConverter(typeof(JsonInheritanceConverter), "k")]
|
Orange
|
csharp
|
dotnet__aspire
|
src/Aspire.Hosting/api/Aspire.Hosting.cs
|
{
"start": 124774,
"end": 124925
}
|
partial record ____(string Name, object? Value)
{
public bool IsSensitive { get { throw null; } init { } }
}
|
ResourcePropertySnapshot
|
csharp
|
bitwarden__server
|
src/Core/Tools/SendFeatures/Services/AzureSendFileStorageService.cs
|
{
"start": 331,
"end": 4887
}
|
public class ____ : ISendFileStorageService
{
public const string FilesContainerName = "sendfiles";
private static readonly TimeSpan _downloadLinkLiveTime = TimeSpan.FromMinutes(1);
private readonly BlobServiceClient _blobServiceClient;
private readonly ILogger<AzureSendFileStorageService> _logger;
private BlobContainerClient _sendFilesContainerClient;
public FileUploadType FileUploadType => FileUploadType.Azure;
public static string SendIdFromBlobName(string blobName) => blobName.Split('/')[0];
public static string BlobName(Send send, string fileId) => $"{send.Id}/{fileId}";
public AzureSendFileStorageService(
GlobalSettings globalSettings,
ILogger<AzureSendFileStorageService> logger)
{
_blobServiceClient = new BlobServiceClient(globalSettings.Send.ConnectionString);
_logger = logger;
}
public async Task UploadNewFileAsync(Stream stream, Send send, string fileId)
{
await InitAsync();
var blobClient = _sendFilesContainerClient.GetBlobClient(BlobName(send, fileId));
var metadata = new Dictionary<string, string>();
if (send.UserId.HasValue)
{
metadata.Add("userId", send.UserId.Value.ToString());
}
else
{
metadata.Add("organizationId", send.OrganizationId.Value.ToString());
}
var headers = new BlobHttpHeaders
{
ContentDisposition = $"attachment; filename=\"{fileId}\""
};
await blobClient.UploadAsync(stream, new BlobUploadOptions { Metadata = metadata, HttpHeaders = headers });
}
public async Task DeleteFileAsync(Send send, string fileId) => await DeleteBlobAsync(BlobName(send, fileId));
public async Task DeleteBlobAsync(string blobName)
{
await InitAsync();
var blobClient = _sendFilesContainerClient.GetBlobClient(blobName);
await blobClient.DeleteIfExistsAsync();
}
public async Task DeleteFilesForOrganizationAsync(Guid organizationId)
{
await InitAsync();
}
public async Task DeleteFilesForUserAsync(Guid userId)
{
await InitAsync();
}
public async Task<string> GetSendFileDownloadUrlAsync(Send send, string fileId)
{
await InitAsync();
var blobClient = _sendFilesContainerClient.GetBlobClient(BlobName(send, fileId));
var sasUri = blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTime.UtcNow.Add(_downloadLinkLiveTime));
return sasUri.ToString();
}
public async Task<string> GetSendFileUploadUrlAsync(Send send, string fileId)
{
await InitAsync();
var blobClient = _sendFilesContainerClient.GetBlobClient(BlobName(send, fileId));
var sasUri = blobClient.GenerateSasUri(BlobSasPermissions.Create | BlobSasPermissions.Write, DateTime.UtcNow.Add(_downloadLinkLiveTime));
return sasUri.ToString();
}
public async Task<(bool, long)> ValidateFileAsync(Send send, string fileId, long minimum, long maximum)
{
await InitAsync();
var blobClient = _sendFilesContainerClient.GetBlobClient(BlobName(send, fileId));
try
{
var blobProperties = await blobClient.GetPropertiesAsync();
var metadata = blobProperties.Value.Metadata;
if (send.UserId.HasValue)
{
metadata["userId"] = send.UserId.Value.ToString();
}
else
{
metadata["organizationId"] = send.OrganizationId.Value.ToString();
}
await blobClient.SetMetadataAsync(metadata);
var headers = new BlobHttpHeaders
{
ContentDisposition = $"attachment; filename=\"{fileId}\""
};
await blobClient.SetHttpHeadersAsync(headers);
var length = blobProperties.Value.ContentLength;
var valid = minimum <= length || length <= maximum;
return (valid, length);
}
catch (Exception ex)
{
_logger.LogError(ex, $"A storage operation failed in {nameof(ValidateFileAsync)}");
return (false, -1);
}
}
private async Task InitAsync()
{
if (_sendFilesContainerClient == null)
{
_sendFilesContainerClient = _blobServiceClient.GetBlobContainerClient(FilesContainerName);
await _sendFilesContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, null, null);
}
}
}
|
AzureSendFileStorageService
|
csharp
|
FoundatioFx__Foundatio
|
src/Foundatio/Resilience/IResiliencePolicy.cs
|
{
"start": 250,
"end": 1647
}
|
public interface ____
{
/// <summary>
/// Executes the specified asynchronous action using the resilience policy.
/// </summary>
/// <param name="action">The asynchronous action to execute. The <see cref="CancellationToken"/> parameter allows the action to observe cancellation requests.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>
ValueTask ExecuteAsync(Func<CancellationToken, ValueTask> action, CancellationToken cancellationToken = default);
/// <summary>
/// Executes the specified asynchronous action using the resilience policy and returns a result.
/// </summary>
/// <typeparam name="T">The type of the result returned by the action.</typeparam>
/// <param name="action">The asynchronous action to execute. The <see cref="CancellationToken"/> parameter allows the action to observe cancellation requests.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>A <see cref="ValueTask{T}"/> representing the asynchronous operation and its result.</returns>
ValueTask<T> ExecuteAsync<T>(Func<CancellationToken, ValueTask<T>> action, CancellationToken cancellationToken = default);
}
|
IResiliencePolicy
|
csharp
|
bitwarden__server
|
src/Core/Repositories/Noop/InstallationDeviceRepository.cs
|
{
"start": 87,
"end": 504
}
|
public class ____ : IInstallationDeviceRepository
{
public Task UpsertAsync(InstallationDeviceEntity entity)
{
return Task.FromResult(0);
}
public Task UpsertManyAsync(IList<InstallationDeviceEntity> entities)
{
return Task.FromResult(0);
}
public Task DeleteAsync(InstallationDeviceEntity entity)
{
return Task.FromResult(0);
}
}
|
InstallationDeviceRepository
|
csharp
|
CommunityToolkit__WindowsCommunityToolkit
|
Microsoft.Toolkit.Uwp.UI.Controls.Primitives/DockPanel/DockPanel.Properties.cs
|
{
"start": 435,
"end": 3351
}
|
public partial class ____
{
/// <summary>
/// Gets or sets a value that indicates the position of a child element within a parent <see cref="DockPanel"/>.
/// </summary>
public static readonly DependencyProperty DockProperty = DependencyProperty.RegisterAttached(
"Dock",
typeof(Dock),
typeof(FrameworkElement),
new PropertyMetadata(Dock.Left, DockChanged));
/// <summary>
/// Gets DockProperty attached property
/// </summary>
/// <param name="obj">Target FrameworkElement</param>
/// <returns>Dock value</returns>
public static Dock GetDock(FrameworkElement obj)
{
return (Dock)obj.GetValue(DockProperty);
}
/// <summary>
/// Sets DockProperty attached property
/// </summary>
/// <param name="obj">Target FrameworkElement</param>
/// <param name="value">Dock Value</param>
public static void SetDock(FrameworkElement obj, Dock value)
{
obj.SetValue(DockProperty, value);
}
/// <summary>
/// Identifies the <see cref="LastChildFill"/> dependency property.
/// </summary>
public static readonly DependencyProperty LastChildFillProperty
= DependencyProperty.Register(
nameof(LastChildFill),
typeof(bool),
typeof(DockPanel),
new PropertyMetadata(true, LastChildFillChanged));
/// <summary>
/// Gets or sets a value indicating whether the last child element within a DockPanel stretches to fill the remaining available space.
/// </summary>
public bool LastChildFill
{
get { return (bool)GetValue(LastChildFillProperty); }
set { SetValue(LastChildFillProperty, value); }
}
/// <summary>
/// Identifies the Padding dependency property.
/// </summary>
/// <returns>The identifier for the <see cref="Padding"/> dependency property.</returns>
public static readonly DependencyProperty PaddingProperty =
DependencyProperty.Register(
nameof(Padding),
typeof(Thickness),
typeof(DockPanel),
new PropertyMetadata(default(Thickness), OnPaddingChanged));
/// <summary>
/// Gets or sets the distance between the border and its child object.
/// </summary>
/// <returns>
/// The dimensions of the space between the border and its child as a Thickness value.
/// Thickness is a structure that stores dimension values using pixel measures.
/// </returns>
public Thickness Padding
{
get { return (Thickness)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
}
}
|
DockPanel
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Text/tests/ServiceStack.Text.Tests/JsonTests/BasicPropertiesTests.cs
|
{
"start": 6493,
"end": 6912
}
|
public class ____
{
public HashSet<string> Set { get; set; }
}
[Test]
public void Can_deserialize_null_Nested_HashSet()
{
JsConfig.ThrowOnError = true;
string json = @"{""set"":null}";
var o = json.FromJson<ModelWithHashSet>();
Assert.That(o.Set, Is.Null);
JsConfig.Reset();
}
}
}
|
ModelWithHashSet
|
csharp
|
dotnet__aspnetcore
|
src/SignalR/samples/SocialWeather/FormatterResolver.cs
|
{
"start": 164,
"end": 1366
}
|
public class ____
{
private readonly IServiceProvider _serviceProvider;
private readonly Dictionary<string, Dictionary<Type, Type>> _formatters
= new Dictionary<string, Dictionary<Type, Type>>();
public FormatterResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void AddFormatter<T, TFormatterType>(string formatType)
where TFormatterType : IStreamFormatter<T>
{
Dictionary<Type, Type> typeFormatters;
if (!_formatters.TryGetValue(formatType, out typeFormatters))
{
typeFormatters = _formatters[formatType] = new Dictionary<Type, Type>();
}
typeFormatters[typeof(T)] = typeof(TFormatterType);
}
public IStreamFormatter<T> GetFormatter<T>(string formatType)
{
Dictionary<Type, Type> typeFormatters;
Type typeFormatterType;
if (_formatters.TryGetValue(formatType, out typeFormatters) &&
typeFormatters.TryGetValue(typeof(T), out typeFormatterType))
{
return (IStreamFormatter<T>)_serviceProvider.GetRequiredService(typeFormatterType);
}
return null;
}
}
|
FormatterResolver
|
csharp
|
abpframework__abp
|
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/Modularity/ModuleExtensionConfiguration.cs
|
{
"start": 113,
"end": 495
}
|
public class ____
{
[NotNull]
public EntityExtensionConfigurationDictionary Entities { get; }
[NotNull]
public Dictionary<string, object> Configuration { get; }
public ModuleExtensionConfiguration()
{
Entities = new EntityExtensionConfigurationDictionary();
Configuration = new Dictionary<string, object>();
}
}
|
ModuleExtensionConfiguration
|
csharp
|
dotnet__aspnetcore
|
src/Framework/AspNetCoreAnalyzers/test/Mvc/DetectAmbiguousActionRoutesTest.cs
|
{
"start": 13636,
"end": 14011
}
|
internal class ____
{
static void Main(string[] args)
{
}
}
";
// Act & Assert
await VerifyCS.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task ActionRouteToken_OnController_ActionNameOnBase_NoDiagnostics()
{
// Arrange
var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
|
Program
|
csharp
|
dotnet__maui
|
src/Core/src/Platform/iOS/Culture.cs
|
{
"start": 104,
"end": 763
}
|
public static class ____
{
static NSLocale? s_locale;
static CultureInfo? s_currentCulture;
public static CultureInfo CurrentCulture
{
get
{
if (s_locale == null || s_currentCulture == null || s_locale != NSLocale.CurrentLocale)
{
s_locale = NSLocale.CurrentLocale;
string countryCode = s_locale.CountryCode;
var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(c => c.Name.EndsWith("-" + countryCode)).FirstOrDefault();
if (cultureInfo == null)
cultureInfo = CultureInfo.InvariantCulture;
s_currentCulture = cultureInfo;
}
return s_currentCulture;
}
}
}
}
|
Culture
|
csharp
|
jellyfin__jellyfin
|
MediaBrowser.Providers/MediaInfo/LyricResolver.cs
|
{
"start": 524,
"end": 1419
}
|
class ____ external subtitle file processing.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="localizationManager">The localization manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="namingOptions">The <see cref="NamingOptions"/> object containing FileExtensions, MediaDefaultFlags, MediaForcedFlags and MediaFlagDelimiters.</param>
public LyricResolver(
ILogger<LyricResolver> logger,
ILocalizationManager localizationManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
NamingOptions namingOptions)
: base(
logger,
localizationManager,
mediaEncoder,
fileSystem,
namingOptions,
DlnaProfileType.Lyric)
{
}
}
|
for
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Projections.Core/Metrics/IProjectionStateSerializationTracker.cs
|
{
"start": 257,
"end": 456
}
|
public interface ____ {
public static IProjectionStateSerializationTracker NoOp { get; } = NoOpTracker.Instance;
public void StateSerialized(Instant start);
}
file
|
IProjectionStateSerializationTracker
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/UnitTestExample.cs
|
{
"start": 2133,
"end": 2928
}
|
public class ____ : Service
{
public IRockstarRepository RockstarRepository { get; set; }
public List<Rockstar> Get(FindRockstars request)
{
return request.Aged.HasValue
? Db.Select<Rockstar>(q => q.Age == request.Aged.Value)
: Db.Select<Rockstar>();
}
public RockstarStatus Get(GetStatus request)
{
var rockstar = RockstarRepository.GetByLastName(request.LastName);
if (rockstar == null)
throw HttpError.NotFound("'{0}' is not a Rockstar".Fmt(request.LastName));
var status = new RockstarStatus
{
Alive = RockstarRepository.IsAlive(request.LastName)
}.PopulateWith(rockstar); //Populates with matching fields
return status;
}
}
//Custom Repository
|
SimpleService
|
csharp
|
dotnetcore__Util
|
src/Util.Microservices.Dapr/Events/Filters/SubscriptionFilterAttribute.cs
|
{
"start": 142,
"end": 4077
}
|
public class ____ : ActionFilterAttribute {
/// <summary>
/// 执行
/// </summary>
public override async Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next ) {
if ( context == null )
return;
if ( next == null )
return;
if ( context.HttpContext.Request.ContentType != "application/cloudevents+json" )
return;
var log = context.HttpContext.RequestServices.GetService<ILogger<SubscriptionFilterAttribute>>() ?? NullLogger<SubscriptionFilterAttribute>.Instance;
try {
var body = await GetBodyJsonElement( context );
var routeUrl = context.HttpContext.Request.GetDisplayUrl();
var eventId = GetEventId( body );
if ( eventId.IsEmpty() ) {
log.LogError( "集成事件标识为空,body:{@body},routeUrl:{routeUrl}", body, routeUrl );
return;
}
log.LogTrace( "准备处理集成事件订阅,eventId={@eventId},routeUrl={routeUrl}", eventId, routeUrl );
var manager = context.HttpContext.RequestServices.GetRequiredService<IIntegrationEventManager>();
var eventLog = await GetEventLog( manager, eventId );
if ( eventLog == null ) {
log.LogError( "集成事件为空,eventId={@eventId},body:{@body},routeUrl:{routeUrl}", eventId, body, routeUrl );
return;
}
if ( manager.CanSubscription( eventLog ) == false ) {
log.LogDebug( "集成事件订阅无需处理,eventId={@eventId},body:{@body},routeUrl={routeUrl}", eventId, body, routeUrl );
if ( manager.IsSubscriptionSuccess( eventLog ) )
context.Result = PubsubResult.Success;
return;
}
var callback = context.HttpContext.RequestServices.GetRequiredService<IPubsubCallback>();
await callback.OnSubscriptionBefore( eventLog, routeUrl );
var executedContext = await next();
OnActionExecuted( executedContext );
if ( executedContext.Result is PubsubResult result ) {
await callback.OnSubscriptionAfter( eventId, result == PubsubResult.Success, result.Message );
return;
}
if ( executedContext.Exception != null ) {
await callback.OnSubscriptionAfter( eventId, false,Warning.GetMessage( executedContext.Exception ) );
return;
}
}
catch ( Exception exception ) {
log.LogError( exception, "集成事件订阅处理过滤器执行失败." );
throw;
}
}
/// <summary>
/// 获取请求正文Json元素
/// </summary>
protected async Task<JsonElement> GetBodyJsonElement( ActionExecutingContext context ) {
var body = await GetBody( context );
var client = context.HttpContext.RequestServices.GetService<DaprClient>();
return await Util.Helpers.Json.ToObjectAsync<JsonElement>( body, client?.JsonSerializerOptions );
}
/// <summary>
/// 获取请求正文
/// </summary>
protected async Task<byte[]> GetBody( ActionExecutingContext context ) {
context.HttpContext.Request.EnableBuffering();
return await Util.Helpers.File.ReadToBytesAsync( context.HttpContext.Request.Body );
}
/// <summary>
/// 获取集成事件标识
/// </summary>
protected string GetEventId( JsonElement body ) {
return body.TryGetProperty( "eventId", out var eventId ) ? eventId.Deserialize<string>() : null;
}
/// <summary>
/// 获取集成事件
/// </summary>
protected async Task<IntegrationEventLog> GetEventLog( IIntegrationEventManager manager,string eventId ) {
for ( var i = 0; i < 100; i++ ) {
var eventLog = await manager.GetAsync( eventId );
if ( eventLog != null )
return eventLog;
await Task.Delay( 100 );
}
return null;
}
}
|
SubscriptionFilterAttribute
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
|
{
"start": 318137,
"end": 318357
}
|
public class ____
{
public int Id { get; set; }
public RelatedEntity1460 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1462> ChildEntities { get; set; }
}
|
RelatedEntity1461
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/src/ServiceStack/Messaging/BackgroundMqService.cs
|
{
"start": 23446,
"end": 23703
}
|
public class ____(BackgroundMqClient mqClient) : IMessageFactory
{
public IMessageQueueClient CreateMessageQueueClient() => mqClient;
public IMessageProducer CreateMessageProducer() => mqClient;
public void Dispose() {}
}
|
BackgroundMqMessageFactory
|
csharp
|
dotnet__extensions
|
test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.LogProperties.cs
|
{
"start": 5610,
"end": 6015
}
|
partial class ____
{
[LoggerMessage(0, LogLevel.Debug, ""{param}"")]
static partial void M(ILogger logger, [LogProperties] MyClass /*0+*/param/*-0*/);
}";
await RunGenerator(Source, DiagDescriptors.LogPropertiesParameterSkipped);
}
[Fact]
public async Task SimpleNameCollision()
{
const string Source = @"
|
C
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.TimeSeries/IidSpikeDetector.cs
|
{
"start": 2986,
"end": 9017
}
|
private sealed class ____ : ArgumentsBase
{
public BaseArguments(Options options)
{
Source = options.Source;
Name = options.Name;
Side = options.Side;
WindowSize = options.PvalueHistoryLength;
AlertThreshold = 1 - options.Confidence / 100;
AlertOn = AlertingScore.PValueScore;
Martingale = MartingaleType.None;
}
public BaseArguments(IidSpikeDetector transform)
{
Source = transform.InternalTransform.InputColumnName;
Name = transform.InternalTransform.OutputColumnName;
Side = transform.InternalTransform.Side;
WindowSize = transform.InternalTransform.WindowSize;
AlertThreshold = transform.InternalTransform.AlertThreshold;
AlertOn = AlertingScore.PValueScore;
Martingale = MartingaleType.None;
}
}
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "ISPKTRNS",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(IidSpikeDetector).Assembly.FullName);
}
// Factory method for SignatureDataTransform.
private static IDataTransform Create(IHostEnvironment env, Options options, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(options, nameof(options));
env.CheckValue(input, nameof(input));
return new IidSpikeDetector(env, options).MakeDataTransform(input);
}
IStatefulTransformer IStatefulTransformer.Clone()
{
var clone = (IidSpikeDetector)MemberwiseClone();
clone.InternalTransform.StateRef = (IidAnomalyDetectionBase.State)clone.InternalTransform.StateRef.Clone();
clone.InternalTransform.StateRef.InitState(clone.InternalTransform, InternalTransform.Host);
return clone;
}
internal IidSpikeDetector(IHostEnvironment env, Options options)
: base(new BaseArguments(options), LoaderSignature, env)
{
// This constructor is empty.
}
// Factory method for SignatureLoadDataTransform.
private static IDataTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(ctx, nameof(ctx));
env.CheckValue(input, nameof(input));
return new IidSpikeDetector(env, ctx).MakeDataTransform(input);
}
// Factory method for SignatureLoadModel.
internal static IidSpikeDetector Create(IHostEnvironment env, ModelLoadContext ctx)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel(GetVersionInfo());
return new IidSpikeDetector(env, ctx);
}
private IidSpikeDetector(IHostEnvironment env, ModelLoadContext ctx)
: base(env, ctx, LoaderSignature)
{
// *** Binary format ***
// <base>
InternalTransform.Host.CheckDecode(InternalTransform.ThresholdScore == AlertingScore.PValueScore);
}
private IidSpikeDetector(IHostEnvironment env, IidSpikeDetector transform)
: base(new BaseArguments(transform), LoaderSignature, env)
{
}
private protected override void SaveModel(ModelSaveContext ctx)
{
InternalTransform.Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
InternalTransform.Host.Assert(InternalTransform.ThresholdScore == AlertingScore.PValueScore);
// *** Binary format ***
// <base>
base.SaveModel(ctx);
}
// Factory method for SignatureLoadRowMapper.
private static IRowMapper Create(IHostEnvironment env, ModelLoadContext ctx, DataViewSchema inputSchema)
=> Create(env, ctx).MakeRowMapper(inputSchema);
}
/// <summary>
/// Detect a signal spike on an
/// <a href="https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables"> independent identically distributed (i.i.d.)</a>
/// time series based on adaptive kernel density estimation.
/// </summary>
/// <remarks>
/// <format type="text/markdown"><).
///
/// [!include[io](~/../docs/samples/docs/api-reference/io-time-series-spike.md)]
///
/// ### Estimator Characteristics
/// | | |
/// | -- | -- |
/// | Does this estimator need to look at the data to train its parameters? | No |
/// | Input column data type | <xref:System.Single> |
/// | Output column data type | 3-element vector of<xref:System.Double> |
/// | Exportable to ONNX | No |
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-props.md)]
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-iid.md)]
///
/// [!include[io](~/../docs/samples/docs/api-reference/time-series-pvalue.md)]
///
/// Check the See Also section for links to usage examples.
/// ]]>
/// </format>
/// </remarks>
/// <seealso cref="Microsoft.ML.TimeSeriesCatalog.DetectIidSpike(Microsoft.ML.TransformsCatalog,System.String,System.String,System.Double,System.Int32,Microsoft.ML.Transforms.TimeSeries.AnomalySide)" />
|
BaseArguments
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.OpenApi.Tests/GeneratedClient/HelloZipOperations.cs
|
{
"start": 535,
"end": 27139
}
|
public partial class ____ : IServiceOperations<ServiceStackAutorestClient>, IHelloZipOperations
{
/// <summary>
/// Initializes a new instance of the HelloZipOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HelloZipOperations(ServiceStackAutorestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ServiceStackAutorestClient
/// </summary>
public ServiceStackAutorestClient Client { get; private set; }
/// <param name='name'>
/// </param>
/// <param name='test'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HelloZipResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<HelloZipResponse>> GetWithHttpMessagesAsync(string name = default(string), string test = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("name", name);
tracingParameters.Add("test", test);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "hellozip").ToString();
List<string> _queryParameters = new List<string>();
if (name != null)
{
_queryParameters.Add(string.Format("Name={0}", System.Uri.EscapeDataString(name)));
}
if (test != null)
{
_queryParameters.Add(string.Format("Test={0}", System.Uri.EscapeDataString(test)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.Accept != null)
{
if (_httpRequest.Headers.Contains("Accept"))
{
_httpRequest.Headers.Remove("Accept");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept", Client.Accept);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HelloZipResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
HelloZipResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<HelloZipResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='name'>
/// </param>
/// <param name='test'>
/// </param>
/// <param name='body'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HelloZipResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<HelloZipResponse>> CreateWithHttpMessagesAsync(string name = default(string), string test = default(string), HelloZip body = default(HelloZip), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("name", name);
tracingParameters.Add("test", test);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "hellozip").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.Accept != null)
{
if (_httpRequest.Headers.Contains("Accept"))
{
_httpRequest.Headers.Remove("Accept");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept", Client.Accept);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HelloZipResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
HelloZipResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<HelloZipResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='name'>
/// </param>
/// <param name='test'>
/// </param>
/// <param name='body'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HelloZipResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<HelloZipResponse>> PostWithHttpMessagesAsync(string name = default(string), string test = default(string), HelloZip body = default(HelloZip), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("name", name);
tracingParameters.Add("test", test);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "hellozip").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.Accept != null)
{
if (_httpRequest.Headers.Contains("Accept"))
{
_httpRequest.Headers.Remove("Accept");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept", Client.Accept);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HelloZipResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
HelloZipResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<HelloZipResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='name'>
/// </param>
/// <param name='test'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HelloZipResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<HelloZipResponse>> DeleteWithHttpMessagesAsync(string name = default(string), string test = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("name", name);
tracingParameters.Add("test", test);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "hellozip").ToString();
List<string> _queryParameters = new List<string>();
if (name != null)
{
_queryParameters.Add(string.Format("Name={0}", System.Uri.EscapeDataString(name)));
}
if (test != null)
{
_queryParameters.Add(string.Format("Test={0}", System.Uri.EscapeDataString(test)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.Accept != null)
{
if (_httpRequest.Headers.Contains("Accept"))
{
_httpRequest.Headers.Remove("Accept");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept", Client.Accept);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HelloZipResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
HelloZipResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<HelloZipResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<HelloZipResponse>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
|
HelloZipOperations
|
csharp
|
dotnet__efcore
|
src/EFCore.Proxies/Proxies/Internal/ProxyAnnotationNames.cs
|
{
"start": 646,
"end": 2827
}
|
public static class ____
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string Prefix = "Proxies:";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string LazyLoading = Prefix + "LazyLoading";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string ChangeTracking = Prefix + "ChangeTracking";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string CheckEquality = Prefix + "CheckEquality";
}
|
ProxyAnnotationNames
|
csharp
|
dotnet__aspnetcore
|
src/DataProtection/Cryptography.KeyDerivation/test/Pbkdf2Tests.cs
|
{
"start": 406,
"end": 11849
}
|
public class ____
{
// The 'numBytesRequested' parameters below are chosen to exercise code paths where
// this value straddles the digest length of the PRF. We only use 5 iterations so
// that our unit tests are fast.
// This provider is only available in .NET Core because .NET Standard only supports HMACSHA1
[Theory]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 - 1, "efmxNcKD/U1urTEDGvsThlPnHA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 0, "efmxNcKD/U1urTEDGvsThlPnHDI=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 1, "efmxNcKD/U1urTEDGvsThlPnHDLk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 - 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 0, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLo=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLpk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 - 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm9")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 0, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Q==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Wk=")]
public void RunTest_Normal_NetCore(string password, KeyDerivationPrf prf, int iterationCount, int numBytesRequested, string expectedValueAsBase64)
{
// Arrange
byte[] salt = new byte[256];
for (int i = 0; i < salt.Length; i++)
{
salt[i] = (byte)i;
}
// Act & assert
#if NETFRAMEWORK
TestProvider<ManagedPbkdf2Provider>(password, salt, prf, iterationCount, numBytesRequested, expectedValueAsBase64);
#elif NETCOREAPP
TestProvider<NetCorePbkdf2Provider>(password, salt, prf, iterationCount, numBytesRequested, expectedValueAsBase64);
#else
#error Update target frameworks
#endif
}
[Fact]
public void RunTest_WithLongPassword_NetCore_FallbackToManaged()
{
// salt is less than 8 bytes
byte[] salt = Encoding.UTF8.GetBytes("salt");
const string expectedDerivedKeyBase64 = "Sc+V/c3fiZq5Z5qH3iavAiojTsW97FAp2eBNmCQAwCNzA8hfhFFYyQLIMK65qPnBFHOHXQPwAxNQNhaEAH9hzfiaNBSRJpF9V4rpl02d5ZpI6cZbsQFF7TJW7XJzQVpYoPDgJlg0xVmYLhn1E9qMtUVUuXsBjOOdd7K1M+ZI00c=";
#if NETFRAMEWORK
RunTest_WithLongPassword_Impl<ManagedPbkdf2Provider>(salt, expectedDerivedKeyBase64);
#elif NETCOREAPP
RunTest_WithLongPassword_Impl<NetCorePbkdf2Provider>(salt, expectedDerivedKeyBase64);
#else
#error Update target frameworks
#endif
}
[Fact]
public void RunTest_WithLongPassword_NetCore()
{
// salt longer than 8 bytes
var salt = Encoding.UTF8.GetBytes("abcdefghijkl");
#if NETFRAMEWORK
RunTest_WithLongPassword_Impl<ManagedPbkdf2Provider>(salt, "NGJtFzYUaaSxu+3ZsMeZO5d/qPJDUYW4caLkFlaY0cLSYdh1PN4+nHUVp4pUUubJWu3UeXNMnHKNDfnn8GMfnDVrAGTv1lldszsvUJ0JQ6p4+daQEYBc//Tj/ejuB3luwW0IinyE7U/ViOQKbfi5pCZFMQ0FFx9I+eXRlyT+I74=");
#elif NETCOREAPP
RunTest_WithLongPassword_Impl<NetCorePbkdf2Provider>(salt, "NGJtFzYUaaSxu+3ZsMeZO5d/qPJDUYW4caLkFlaY0cLSYdh1PN4+nHUVp4pUUubJWu3UeXNMnHKNDfnn8GMfnDVrAGTv1lldszsvUJ0JQ6p4+daQEYBc//Tj/ejuB3luwW0IinyE7U/ViOQKbfi5pCZFMQ0FFx9I+eXRlyT+I74=");
#else
#error Update target frameworks
#endif
}
// The 'numBytesRequested' parameters below are chosen to exercise code paths where
// this value straddles the digest length of the PRF. We only use 5 iterations so
// that our unit tests are fast.
[Theory]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 - 1, "efmxNcKD/U1urTEDGvsThlPnHA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 0, "efmxNcKD/U1urTEDGvsThlPnHDI=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 1, "efmxNcKD/U1urTEDGvsThlPnHDLk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 - 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 0, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLo=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLpk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 - 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm9")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 0, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Q==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Wk=")]
public void RunTest_Normal_Managed(string password, KeyDerivationPrf prf, int iterationCount, int numBytesRequested, string expectedValueAsBase64)
{
// Arrange
byte[] salt = new byte[256];
for (int i = 0; i < salt.Length; i++)
{
salt[i] = (byte)i;
}
// Act & assert
TestProvider<ManagedPbkdf2Provider>(password, salt, prf, iterationCount, numBytesRequested, expectedValueAsBase64);
}
// The 'numBytesRequested' parameters below are chosen to exercise code paths where
// this value straddles the digest length of the PRF. We only use 5 iterations so
// that our unit tests are fast.
[ConditionalTheory]
[ConditionalRunTestOnlyOnWindows]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 - 1, "efmxNcKD/U1urTEDGvsThlPnHA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 0, "efmxNcKD/U1urTEDGvsThlPnHDI=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 1, "efmxNcKD/U1urTEDGvsThlPnHDLk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 - 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 0, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLo=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLpk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 - 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm9")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 0, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Q==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Wk=")]
public void RunTest_Normal_Win7(string password, KeyDerivationPrf prf, int iterationCount, int numBytesRequested, string expectedValueAsBase64)
{
// Arrange
byte[] salt = new byte[256];
for (int i = 0; i < salt.Length; i++)
{
salt[i] = (byte)i;
}
// Act & assert
TestProvider<Win7Pbkdf2Provider>(password, salt, prf, iterationCount, numBytesRequested, expectedValueAsBase64);
}
// The 'numBytesRequested' parameters below are chosen to exercise code paths where
// this value straddles the digest length of the PRF. We only use 5 iterations so
// that our unit tests are fast.
[ConditionalTheory]
[ConditionalRunTestOnlyOnWindows8OrLater]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 - 1, "efmxNcKD/U1urTEDGvsThlPnHA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 0, "efmxNcKD/U1urTEDGvsThlPnHDI=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA1, 5, 160 / 8 + 1, "efmxNcKD/U1urTEDGvsThlPnHDLk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 - 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRA==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 0, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLo=")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA256, 5, 256 / 8 + 1, "JRNz8bPKS02EG1vf7eWjA64IeeI+TI8gBEwb1oVvRLpk")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 - 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm9")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 0, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Q==")]
[InlineData("my-password", KeyDerivationPrf.HMACSHA512, 5, 512 / 8 + 1, "ZTallQJrFn0279xIzaiA1XqatVTGei+ZjKngA7bIMtKMDUw6YJeGUQpFG8iGTgN+ri3LNDktNbzwfcSyZmm90Wk=")]
public void RunTest_Normal_Win8(string password, KeyDerivationPrf prf, int iterationCount, int numBytesRequested, string expectedValueAsBase64)
{
// Arrange
byte[] salt = new byte[256];
for (int i = 0; i < salt.Length; i++)
{
salt[i] = (byte)i;
}
// Act & assert
TestProvider<Win8Pbkdf2Provider>(password, salt, prf, iterationCount, numBytesRequested, expectedValueAsBase64);
}
[Fact]
public void RunTest_WithLongPassword_Managed()
{
RunTest_WithLongPassword_Impl<ManagedPbkdf2Provider>();
}
[ConditionalFact]
[ConditionalRunTestOnlyOnWindows]
public void RunTest_WithLongPassword_Win7()
{
RunTest_WithLongPassword_Impl<Win7Pbkdf2Provider>();
}
[ConditionalFact]
[ConditionalRunTestOnlyOnWindows8OrLater]
public void RunTest_WithLongPassword_Win8()
{
RunTest_WithLongPassword_Impl<Win8Pbkdf2Provider>();
}
private static void RunTest_WithLongPassword_Impl<TProvider>()
where TProvider : IPbkdf2Provider, new()
{
byte[] salt = Encoding.UTF8.GetBytes("salt");
const string expectedDerivedKeyBase64 = "Sc+V/c3fiZq5Z5qH3iavAiojTsW97FAp2eBNmCQAwCNzA8hfhFFYyQLIMK65qPnBFHOHXQPwAxNQNhaEAH9hzfiaNBSRJpF9V4rpl02d5ZpI6cZbsQFF7TJW7XJzQVpYoPDgJlg0xVmYLhn1E9qMtUVUuXsBjOOdd7K1M+ZI00c=";
RunTest_WithLongPassword_Impl<TProvider>(salt, expectedDerivedKeyBase64);
}
private static void RunTest_WithLongPassword_Impl<TProvider>(byte[] salt, string expectedDerivedKeyBase64)
where TProvider : IPbkdf2Provider, new()
{
// Arrange
string password = new String('x', 50000); // 50,000 char password
const KeyDerivationPrf prf = KeyDerivationPrf.HMACSHA256;
const int iterationCount = 5;
const int numBytesRequested = 128;
// Act & assert
TestProvider<TProvider>(password, salt, prf, iterationCount, numBytesRequested, expectedDerivedKeyBase64);
}
private static void TestProvider<TProvider>(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested, string expectedDerivedKeyAsBase64)
where TProvider : IPbkdf2Provider, new()
{
byte[] derivedKey = new TProvider().DeriveKey(password, salt, prf, iterationCount, numBytesRequested);
Assert.Equal(numBytesRequested, derivedKey.Length);
Assert.Equal(expectedDerivedKeyAsBase64, Convert.ToBase64String(derivedKey));
}
}
|
Pbkdf2Tests
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticsearchResult.cs
|
{
"start": 468,
"end": 812
}
|
public class ____
{
public JsonObject Value { get; }
public IReadOnlyDictionary<string, IReadOnlyCollection<string>> Highlights { get; set; }
public double? Score { get; set; }
public ElasticsearchRecord(JsonObject value)
{
ArgumentNullException.ThrowIfNull(value);
Value = value;
}
}
|
ElasticsearchRecord
|
csharp
|
dotnetcore__FreeSql
|
FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectTest.cs
|
{
"start": 105404,
"end": 121903
}
|
public class ____
{
[Column(IsPrimary = true)]
public Guid pk1 { get; set; }
[Column(IsPrimary = true)]
public int pk2 { get; set; }
[Column(IsPrimary = true)]
public string pk3 { get; set; }
public string name { get; set; }
}
[Fact]
public void ToUpdate()
{
g.sqlserver.Select<ToUpd1Pk>().ToDelete().ExecuteAffrows();
Assert.Equal(0, g.sqlserver.Select<ToUpd1Pk>().Count());
g.sqlserver.Insert(new[] {
new ToUpd1Pk{ name = "name1"},
new ToUpd1Pk{ name = "name2"},
new ToUpd1Pk{ name = "nick1"},
new ToUpd1Pk{ name = "nick2"},
new ToUpd1Pk{ name = "nick3"}
}).ExecuteAffrows();
Assert.Equal(2, g.sqlserver.Select<ToUpd1Pk>().Where(a => a.name.StartsWith("name")).ToUpdate().Set(a => a.name, "nick?").ExecuteAffrows());
Assert.Equal(5, g.sqlserver.Select<ToUpd1Pk>().Count());
Assert.Equal(5, g.sqlserver.Select<ToUpd1Pk>().Where(a => a.name.StartsWith("nick")).Count());
g.sqlserver.Select<ToUpd2Pk>().ToDelete().ExecuteAffrows();
Assert.Equal(0, g.sqlserver.Select<ToUpd2Pk>().Count());
g.sqlserver.Insert(new[] {
new ToUpd2Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = "pk2", name = "name1"},
new ToUpd2Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = "pk2", name = "name2"},
new ToUpd2Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = "pk2", name = "nick1"},
new ToUpd2Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = "pk2", name = "nick2"},
new ToUpd2Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = "pk2", name = "nick3"}
}).ExecuteAffrows();
Assert.Equal(2, g.sqlserver.Select<ToUpd2Pk>().Where(a => a.name.StartsWith("name")).ToUpdate().Set(a => a.name, "nick?").ExecuteAffrows());
Assert.Equal(5, g.sqlserver.Select<ToUpd2Pk>().Count());
Assert.Equal(5, g.sqlserver.Select<ToUpd2Pk>().Where(a => a.name.StartsWith("nick")).Count());
g.sqlserver.Select<ToUpd3Pk>().ToDelete().ExecuteAffrows();
Assert.Equal(0, g.sqlserver.Select<ToUpd3Pk>().Count());
g.sqlserver.Insert(new[] {
new ToUpd3Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = 1, pk3 = "pk3", name = "name1"},
new ToUpd3Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = 1, pk3 = "pk3", name = "name2"},
new ToUpd3Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = 1, pk3 = "pk3", name = "nick1"},
new ToUpd3Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = 1, pk3 = "pk3", name = "nick2"},
new ToUpd3Pk{ pk1 = FreeUtil.NewMongodbId(), pk2 = 1, pk3 = "pk3", name = "nick3"}
}).ExecuteAffrows();
Assert.Equal(2, g.sqlserver.Select<ToUpd3Pk>().Where(a => a.name.StartsWith("name")).ToUpdate().Set(a => a.name, "nick?").ExecuteAffrows());
Assert.Equal(5, g.sqlserver.Select<ToUpd3Pk>().Count());
Assert.Equal(5, g.sqlserver.Select<ToUpd3Pk>().Where(a => a.name.StartsWith("nick")).Count());
}
[Fact]
public void WithLock()
{
var orm = g.sqlserver;
orm.Transaction(() =>
{
var sql = orm.Select<ToUpd1Pk>().WithLock().Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(NoLock)", sql);
orm.Select<ToUpd1Pk>().WithLock().Limit(1).ToList();
sql = orm.Select<ToUpd1Pk>().WithLock().WithIndex("idx_01").Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(index=idx_01, NoLock)", sql);
sql = orm.Select<ToUpd1Pk>().WithIndex("idx_01").WithLock().Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(NoLock, index=idx_01)", sql);
sql = orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.NoLock).Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(NoLock)", sql);
orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.NoLock).Limit(1).ToList();
sql = orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.NoLock | SqlServerLock.NoWait).Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(NoLock, NoWait)", sql);
orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.NoLock | SqlServerLock.NoWait).Limit(1).ToList();
sql = orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.UpdLock | SqlServerLock.RowLock | SqlServerLock.NoWait).Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(UpdLock, RowLock, NoWait)", sql);
orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.UpdLock | SqlServerLock.RowLock | SqlServerLock.NoWait).Limit(1).ToList();
sql = orm.Select<ToUpd1Pk>().WithLock(SqlServerLock.UpdLock | SqlServerLock.RowLock | SqlServerLock.NoWait).WithIndex("idx_01").Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(index=idx_01, UpdLock, RowLock, NoWait)", sql);
sql = orm.Select<ToUpd1Pk>().WithIndex("idx_01").WithLock(SqlServerLock.UpdLock | SqlServerLock.RowLock | SqlServerLock.NoWait).Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(UpdLock, RowLock, NoWait, index=idx_01)", sql);
});
var sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock()
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(NoLock)
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.WithSql("select * from topic with (nolock)")
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock()
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM ( select * from topic with (nolock) ) a
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock()
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(NoLock)
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock()
.WithIndex("idx_02")
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(index=idx_02, NoLock)
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock()
.WithIndex("idx_02", new Dictionary<Type, string>
{
[typeof(TestTypeInfo)] = "idx_03"
})
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(index=idx_02, NoLock)
INNER JOIN [TestTypeInfo] a__Type With(index=idx_03, NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock(SqlServerLock.NoLock, new Dictionary<Type, bool>
{
[typeof(TestTypeInfo)] = true
})
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock(SqlServerLock.NoLock)
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(NoLock)
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]", sql2);
sql2 = orm.Select<Topic>()
.InnerJoin(a => a.Type.Guid == a.Id)
.WithLock(SqlServerLock.NoLock)
.Where(a => orm.Select<TestTypeInfo>()
.WithLock(SqlServerLock.NoLock, null).Where(b => b.Guid == a.TypeGuid).Any())
.ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime]
FROM [tb_topic22] a With(NoLock)
INNER JOIN [TestTypeInfo] a__Type With(NoLock) ON a__Type.[Guid] = a.[Id]
WHERE (exists(SELECT TOP 1 1
FROM [TestTypeInfo] b With(NoLock)
WHERE (b.[Guid] = a.[TypeGuid])))", sql2);
}
[Fact]
public void ForUpdate()
{
var orm = g.sqlserver;
Assert.Equal("安全起见,请务必在事务开启之后,再使用 ForUpdate",
Assert.Throws<Exception>(() => orm.Select<ToUpd1Pk>().ForUpdate().Limit(1).ToList())?.Message);
orm.Transaction(() =>
{
var sql = orm.Select<ToUpd1Pk>().ForUpdate().Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(UpdLock, RowLock)", sql);
orm.Select<ToUpd1Pk>().ForUpdate().Limit(1).ToList();
sql = orm.Select<ToUpd1Pk>().ForUpdate(true).Limit(1).ToSql().Replace("\r\n", "");
Assert.Equal("SELECT TOP 1 a.[id], a.[name] FROM [ToUpd1Pk] a With(UpdLock, RowLock, NoWait)", sql);
orm.Select<ToUpd1Pk>().ForUpdate(true).Limit(1).ToList();
});
}
[Fact]
public void ToTreeList()
{
var fsql = g.sqlserver;
fsql.Delete<BaseDistrict>().Where("1=1").ExecuteAffrows();
var repo = fsql.GetRepository<VM_District_Child>();
repo.DbContextOptions.EnableCascadeSave = true;
repo.DbContextOptions.NoneParameter = true;
repo.Insert(new VM_District_Child
{
Code = "100000",
Name = "中国",
Childs = new List<VM_District_Child>(new[] {
new VM_District_Child
{
Code = "110000",
Name = "北京",
Childs = new List<VM_District_Child>(new[] {
new VM_District_Child{ Code="110100", Name = "北京市" },
new VM_District_Child{ Code="110101", Name = "东城区" },
})
}
})
});
var t1 = fsql.Select<VM_District_Parent>()
.InnerJoin(a => a.ParentCode == a.Parent.Code)
.Where(a => a.Code == "110101")
.ToList(true);
Assert.Single(t1);
Assert.Equal("110101", t1[0].Code);
Assert.NotNull(t1[0].Parent);
Assert.Equal("110000", t1[0].Parent.Code);
var t2 = fsql.Select<VM_District_Parent>()
.InnerJoin(a => a.ParentCode == a.Parent.Code)
.InnerJoin(a => a.Parent.ParentCode == a.Parent.Parent.Code)
.Where(a => a.Code == "110101")
.ToList(true);
Assert.Single(t2);
Assert.Equal("110101", t2[0].Code);
Assert.NotNull(t2[0].Parent);
Assert.Equal("110000", t2[0].Parent.Code);
Assert.NotNull(t2[0].Parent.Parent);
Assert.Equal("100000", t2[0].Parent.Parent.Code);
var t3 = fsql.Select<VM_District_Child>().ToTreeList();
Assert.Single(t3);
Assert.Equal("100000", t3[0].Code);
Assert.Single(t3[0].Childs);
Assert.Equal("110000", t3[0].Childs[0].Code);
Assert.Equal(2, t3[0].Childs[0].Childs.Count);
Assert.Equal("110100", t3[0].Childs[0].Childs[0].Code);
Assert.Equal("110101", t3[0].Childs[0].Childs[1].Code);
t3 = fsql.Select<VM_District_Child>().Where(a => a.Name == "中国").AsTreeCte().OrderBy(a => a.Code).ToTreeList();
Assert.Single(t3);
Assert.Equal("100000", t3[0].Code);
Assert.Single(t3[0].Childs);
Assert.Equal("110000", t3[0].Childs[0].Code);
Assert.Equal(2, t3[0].Childs[0].Childs.Count);
Assert.Equal("110100", t3[0].Childs[0].Childs[0].Code);
Assert.Equal("110101", t3[0].Childs[0].Childs[1].Code);
t3 = fsql.Select<VM_District_Child>().Where(a => a.Name == "中国").AsTreeCte().OrderBy(a => a.Code).ToList();
Assert.Equal(4, t3.Count);
Assert.Equal("100000", t3[0].Code);
Assert.Equal("110000", t3[1].Code);
Assert.Equal("110100", t3[2].Code);
Assert.Equal("110101", t3[3].Code);
t3 = fsql.Select<VM_District_Child>().Where(a => a.Name == "北京").AsTreeCte().OrderBy(a => a.Code).ToList();
Assert.Equal(3, t3.Count);
Assert.Equal("110000", t3[0].Code);
Assert.Equal("110100", t3[1].Code);
Assert.Equal("110101", t3[2].Code);
var t4 = fsql.Select<VM_District_Child>().Where(a => a.Name == "中国").AsTreeCte(a => a.Name).OrderBy(a => a.Code)
.ToList(a => new { item = a, level = Convert.ToInt32("a.cte_level"), path = "a.cte_path" });
Assert.Equal(4, t4.Count);
Assert.Equal("100000", t4[0].item.Code);
Assert.Equal("110000", t4[1].item.Code);
Assert.Equal("110100", t4[2].item.Code);
Assert.Equal("110101", t4[3].item.Code);
Assert.Equal("中国", t4[0].path);
Assert.Equal("中国 -> 北京", t4[1].path);
Assert.Equal("中国 -> 北京 -> 北京市", t4[2].path);
Assert.Equal("中国 -> 北京 -> 东城区", t4[3].path);
t4 = fsql.Select<VM_District_Child>().Where(a => a.Name == "中国").AsTreeCte(a => a.Name + "[" + a.Code + "]").OrderBy(a => a.Code)
.ToList(a => new { item = a, level = Convert.ToInt32("a.cte_level"), path = "a.cte_path" });
Assert.Equal(4, t4.Count);
Assert.Equal("100000", t4[0].item.Code);
Assert.Equal("110000", t4[1].item.Code);
Assert.Equal("110100", t4[2].item.Code);
Assert.Equal("110101", t4[3].item.Code);
Assert.Equal("中国[100000]", t4[0].path);
Assert.Equal("中国[100000] -> 北京[110000]", t4[1].path);
Assert.Equal("中国[100000] -> 北京[110000] -> 北京市[110100]", t4[2].path);
Assert.Equal("中国[100000] -> 北京[110000] -> 东城区[110101]", t4[3].path);
var select = fsql.Select<VM_District_Child>()
.Where(a => a.Name == "中国")
.AsTreeCte()
//.OrderBy("a.cte_level desc") //递归层级
;
// var list = select.ToList(); //自己调试看查到的数据
select.ToUpdate().Set(a => a.testint, 855).ExecuteAffrows();
Assert.Equal(855, fsql.Select<VM_District_Child>()
.Where(a => a.Name == "中国")
.AsTreeCte().Distinct().First(a => a.testint));
Assert.Equal(4, select.ToDelete().ExecuteAffrows());
Assert.False(fsql.Select<VM_District_Child>()
.Where(a => a.Name == "中国")
.AsTreeCte().Any());
}
[Table(Name = "D_District")]
|
ToUpd3Pk
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
|
{
"start": 199791,
"end": 200008
}
|
public class ____
{
public int Id { get; set; }
public RelatedEntity921 ParentEntity { get; set; }
public IEnumerable<RelatedEntity923> ChildEntities { get; set; }
}
|
RelatedEntity922
|
csharp
|
MassTransit__MassTransit
|
src/MassTransit/Scheduling/IScheduleTokenIdCache.cs
|
{
"start": 59,
"end": 432
}
|
public interface ____<in T>
where T : class
{
/// <summary>
/// Try to get the tokenId for the scheduler from the message
/// </summary>
/// <param name="message"></param>
/// <param name="tokenId"></param>
/// <returns></returns>
bool TryGetTokenId(T message, out Guid tokenId);
}
}
|
IScheduleTokenIdCache
|
csharp
|
dotnet__aspnetcore
|
src/Mvc/Mvc.TagHelpers/test/DefaultFileVersionProviderTest.cs
|
{
"start": 12842,
"end": 13199
}
|
private class ____ : MemoryStream
{
public TestableMemoryStream(byte[] buffer)
: base(buffer)
{
}
public bool Disposed { get; private set; }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Disposed = true;
}
}
}
|
TestableMemoryStream
|
csharp
|
dotnetcore__WTM
|
src/WalkingTec.Mvvm.TagHelpers.LayUI/TabTagHelper.cs
|
{
"start": 109,
"end": 242
}
|
public enum ____ { Default, Simple }
[HtmlTargetElement("wt:tab", TagStructure = TagStructure.NormalOrSelfClosing)]
|
TabStyleEnum
|
csharp
|
unoplatform__uno
|
src/Uno.UI/UI/Xaml/Media/Animation/DoubleKeyFrame.cs
|
{
"start": 153,
"end": 1715
}
|
partial class ____ : DependencyObject
{
public DoubleKeyFrame()
{
IsAutoPropertyInheritanceEnabled = false;
InitializeBinder();
}
public DoubleKeyFrame(double value) : this()
{
Value = value;
}
public DoubleKeyFrame(double value, KeyTime keyTime) : this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// The key frame's target value, which is the value of this key frame at its specified KeyTime. The default value is 0.
/// </summary>
public double Value
{
get { return (double)this.GetValue(ValueProperty); }
set { this.SetValue(ValueProperty, value); }
}
public static DependencyProperty ValueProperty { get; } =
DependencyProperty.Register("Value", typeof(double), typeof(DoubleKeyFrame), new FrameworkPropertyMetadata(0d));
/// <summary>
/// The time at which the key frame's current value should be equal to its Value property.
/// The default value should be Uniform, but it's not supported yet so it's default(KeyTime) for now.
/// </summary>
public KeyTime KeyTime
{
get { return (KeyTime)this.GetValue(KeyTimeProperty); }
set { this.SetValue(KeyTimeProperty, value); }
}
public static DependencyProperty KeyTimeProperty { get; } =
DependencyProperty.Register("KeyTime", typeof(KeyTime), typeof(DoubleKeyFrame), new FrameworkPropertyMetadata(default(KeyTime)));
internal abstract IEasingFunction GetEasingFunction();
public override string ToString()
{
return "KeyTime: {0}, Value: {1}".InvariantCultureFormat(KeyTime, Value);
}
}
}
|
DoubleKeyFrame
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.HostApp/Issues/Bugzilla/Bugzilla32206.cs
|
{
"start": 1615,
"end": 2195
}
|
public class ____ : ContentPage
{
public ContentPage32206()
{
Interlocked.Increment(ref LandingPage32206.Counter);
System.Diagnostics.Debug.WriteLine("Page: " + LandingPage32206.Counter);
Content = new ListView
{
ItemsSource = new List<string> { "Apple", "Banana", "Cherry" },
ItemTemplate = new DataTemplate(typeof(ViewCell32206)),
AutomationId = "ListView"
};
}
~ContentPage32206()
{
Interlocked.Decrement(ref LandingPage32206.Counter);
System.Diagnostics.Debug.WriteLine("Page: " + LandingPage32206.Counter);
}
}
|
ContentPage32206
|
csharp
|
LibreHardwareMonitor__LibreHardwareMonitor
|
LibreHardwareMonitorLib/Hardware/Motherboard/Lpc/EC/ChromeOSEmbeddedController.cs
|
{
"start": 377,
"end": 3982
}
|
public class ____ : EmbeddedController
{
private const byte EC_FAN_SPEED_ENTRIES = 4;
private const ushort EC_FAN_SPEED_NOT_PRESENT = 0xffff;
private const byte EC_MEMMAP_FAN = 0x10;
private const byte EC_MEMMAP_TEMP_SENSOR = 0x00;
private const byte EC_MEMMAP_TEMP_SENSOR_B = 0x18;
private const byte EC_TEMP_SENSOR_B_ENTRIES = 8;
private const byte EC_TEMP_SENSOR_ENTRIES = 16;
private const byte EC_TEMP_SENSOR_NOT_PRESENT = 0xff;
/*
* The offset of temperature value stored in mapped memory. This allows
* reporting a temperature range of 200K to 454K = -73C to 181C.
*/
private const byte EC_TEMP_SENSOR_OFFSET = 200;
public ChromeOSEmbeddedController(IEnumerable<EmbeddedControllerSource> sources, ISettings settings) : base(sources, settings)
{ }
public static ChromeOSEmbeddedController Create(ISettings settings)
{
List<EmbeddedControllerSource> sources = [];
using ChromeOSEmbeddedControllerIO embeddedControllerIO = new();
// Copy the first 0x20 bytes of the EC memory map
byte[] data = embeddedControllerIO.ReadMemmap(0x00, 0x20);
for (int i = 0; i < EC_TEMP_SENSOR_ENTRIES; i++)
{
byte temp = data[EC_MEMMAP_TEMP_SENSOR + i];
if (temp == EC_TEMP_SENSOR_NOT_PRESENT)
{
break;
}
string sensorName = embeddedControllerIO.TempSensorGetName((byte)i);
sources.Add(new EmbeddedControllerSource(sensorName,
SensorType.Temperature,
(ushort)(EC_MEMMAP_TEMP_SENSOR + i),
offset: EC_TEMP_SENSOR_OFFSET - 273,
blank: EC_TEMP_SENSOR_NOT_PRESENT));
}
for (int i = 0; i < EC_FAN_SPEED_ENTRIES; i++)
{
ushort fan = (ushort)(data[EC_MEMMAP_FAN + i * 2] | (data[EC_MEMMAP_FAN + i * 2 + 1] << 8));
if (fan == EC_FAN_SPEED_NOT_PRESENT)
{
break;
}
sources.Add(new EmbeddedControllerSource("Fan " + (i + 1),
SensorType.Fan,
(ushort)(EC_MEMMAP_FAN + i * 2),
2,
blank: EC_FAN_SPEED_NOT_PRESENT,
isLittleEndian: true));
}
for (int i = 0; i < EC_TEMP_SENSOR_B_ENTRIES; i++)
{
byte temp = data[EC_MEMMAP_TEMP_SENSOR_B + i];
if (temp == EC_TEMP_SENSOR_NOT_PRESENT)
{
break;
}
string sensorName = embeddedControllerIO.TempSensorGetName((byte)(i + EC_TEMP_SENSOR_ENTRIES));
sources.Add(new EmbeddedControllerSource(sensorName,
SensorType.Temperature,
(ushort)(EC_MEMMAP_TEMP_SENSOR_B + i),
offset: EC_TEMP_SENSOR_OFFSET - 273,
blank: EC_TEMP_SENSOR_NOT_PRESENT));
}
return new ChromeOSEmbeddedController(sources, settings);
}
protected override IEmbeddedControllerIO AcquireIOInterface()
{
return new ChromeOSEmbeddedControllerIO();
}
}
|
ChromeOSEmbeddedController
|
csharp
|
bitwarden__server
|
util/MySqlMigrations/Migrations/20220322191314_SelfHostF4E.cs
|
{
"start": 113,
"end": 6021
}
|
public partial class ____ : Migration
{
private const string _scriptLocationTemplate = "2022-03-01_00_{0}_MigrateOrganizationApiKeys.sql";
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrganizationSponsorship_Installation_InstallationId",
table: "OrganizationSponsorship");
migrationBuilder.DropIndex(
name: "IX_OrganizationSponsorship_InstallationId",
table: "OrganizationSponsorship");
migrationBuilder.DropColumn(
name: "InstallationId",
table: "OrganizationSponsorship");
migrationBuilder.DropColumn(
name: "TimesRenewedWithoutValidation",
table: "OrganizationSponsorship");
migrationBuilder.CreateTable(
name: "OrganizationApiKey",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
OrganizationId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
Type = table.Column<byte>(type: "tinyint unsigned", nullable: false),
ApiKey = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
RevisionDate = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrganizationApiKey", x => x.Id);
table.ForeignKey(
name: "FK_OrganizationApiKey_Organization_OrganizationId",
column: x => x.OrganizationId,
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.SqlResource(_scriptLocationTemplate);
migrationBuilder.DropColumn(
name: "ApiKey",
table: "Organization");
migrationBuilder.RenameColumn(
name: "SponsorshipLapsedDate",
table: "OrganizationSponsorship",
newName: "ValidUntil");
migrationBuilder.RenameColumn(
name: "CloudSponsor",
table: "OrganizationSponsorship",
newName: "ToDelete");
migrationBuilder.CreateTable(
name: "OrganizationConnection",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
Type = table.Column<byte>(type: "tinyint unsigned", nullable: false),
OrganizationId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
Enabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
Config = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_OrganizationConnection", x => x.Id);
table.ForeignKey(
name: "FK_OrganizationConnection_Organization_OrganizationId",
column: x => x.OrganizationId,
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_OrganizationApiKey_OrganizationId",
table: "OrganizationApiKey",
column: "OrganizationId");
migrationBuilder.CreateIndex(
name: "IX_OrganizationConnection_OrganizationId",
table: "OrganizationConnection",
column: "OrganizationId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ApiKey",
table: "Organization",
type: "varchar(30)",
maxLength: 30,
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.SqlResource(_scriptLocationTemplate);
migrationBuilder.DropTable(
name: "OrganizationApiKey");
migrationBuilder.DropTable(
name: "OrganizationConnection");
migrationBuilder.RenameColumn(
name: "ValidUntil",
table: "OrganizationSponsorship",
newName: "SponsorshipLapsedDate");
migrationBuilder.RenameColumn(
name: "ToDelete",
table: "OrganizationSponsorship",
newName: "CloudSponsor");
migrationBuilder.AddColumn<Guid>(
name: "InstallationId",
table: "OrganizationSponsorship",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
migrationBuilder.AddColumn<byte>(
name: "TimesRenewedWithoutValidation",
table: "OrganizationSponsorship",
type: "tinyint unsigned",
nullable: false,
defaultValue: (byte)0);
migrationBuilder.CreateIndex(
name: "IX_OrganizationSponsorship_InstallationId",
table: "OrganizationSponsorship",
column: "InstallationId");
migrationBuilder.AddForeignKey(
name: "FK_OrganizationSponsorship_Installation_InstallationId",
table: "OrganizationSponsorship",
column: "InstallationId",
principalTable: "Installation",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
|
SelfHostF4E
|
csharp
|
nopSolutions__nopCommerce
|
src/Tests/Nop.Tests/SqLiteNopDataProvider.cs
|
{
"start": 11143,
"end": 13316
}
|
record ____</typeparam>
/// <param name="procedureName">Procedure name</param>
/// <param name="parameters">Command parameters</param>
/// <returns>Returns collection of query result records</returns>
public override Task<IList<T>> QueryProcAsync<T>(string procedureName, params DataParameter[] parameters)
{
//stored procedure is not support by SqLite
return Task.FromResult<IList<T>>(new List<T>());
}
/// <summary>
/// Executes SQL command and returns results as collection of values of specified type
/// </summary>
/// <typeparam name="T">Type of result items</typeparam>
/// <param name="sql">SQL command text</param>
/// <param name="parameters">Parameters to execute the SQL command</param>
/// <returns>Collection of values of specified type</returns>
public override Task<IList<T>> QueryAsync<T>(string sql, params DataParameter[] parameters)
{
using (new ReaderWriteLockDisposable(_locker, ReaderWriteLockType.Read))
return Task.FromResult<IList<T>>(DataContext.Query<T>(sql, parameters).ToList());
}
/// <summary>
/// Executes command asynchronously and returns number of affected records
/// </summary>
/// <param name="sql">Command text</param>
/// <param name="dataParameters">Command parameters</param>
/// <returns>Number of records, affected by command execution.</returns>
public override Task<int> ExecuteNonQueryAsync(string sql, params DataParameter[] dataParameters)
{
using (new ReaderWriteLockDisposable(_locker, ReaderWriteLockType.Read))
{
using var dataConnection = CreateDataConnection(LinqToDbDataProvider);
var command = new CommandInfo(dataConnection, sql, dataParameters);
return command.ExecuteAsync();
}
}
/// <summary>
/// Creates a new temporary storage and populate it using data from provided query
/// </summary>
/// <param name="storeKey">Name of temporary storage</param>
/// <param name="query">Query to get records to populate created storage with initial data</param>
/// <typeparam name="TItem">Storage
|
type
|
csharp
|
FastEndpoints__FastEndpoints
|
Src/Generator/AccessControlGenerator.cs
|
{
"start": 6044,
"end": 11366
}
|
partial class ____
{
private static readonly Dictionary<string, string> _permNames = new();
private static readonly Dictionary<string, string> _permCodes = new();
static Allow()
{
foreach (var f in typeof(Allow).GetFields(BindingFlags.Public | BindingFlags.Static).Where(t => !t.IsDefined(typeof(HideFromDocsAttribute))))
{
var val = f.GetValue(null)?.ToString() ?? string.Empty;
_permNames[f.Name] = val;
_permCodes[val] = f.Name;
}
Groups();
Describe();
}
/// <summary>
/// implement this method to add custom permissions to the generated categories
/// </summary>
static partial void Groups();
/// <summary>
/// implement this method to add descriptions to your custom permissions
/// </summary>
static partial void Describe();
/// <summary>
/// gets a list of permission names for the given list of permission codes
/// </summary>
/// <param name="codes">the permission codes to get the permission names for</param>
public static IEnumerable<string> NamesFor(IEnumerable<string> codes)
{
foreach (var code in codes)
if (_permCodes.TryGetValue(code, out var name)) yield return name;
}
/// <summary>
/// get a list of permission codes for a given list of permission names
/// </summary>
/// <param name="names">the permission names to get the codes for</param>
public static IEnumerable<string> CodesFor(IEnumerable<string> names)
{
foreach (var name in names)
if (_permNames.TryGetValue(name, out var code)) yield return code;
}
/// <summary>
/// get the permission code for a given permission name
/// </summary>
/// <param name="permissionName">the name of the permission to get the code for</param>
public static string? PermissionCodeFor(string permissionName)
{
if (_permNames.TryGetValue(permissionName, out var code))
return code;
return null;
}
/// <summary>
/// get the permission name for a given permission code
/// </summary>
/// <param name="permissionCode">the permission code to get the name for</param>
public static string? PermissionNameFor(string permissionCode)
{
if (_permCodes.TryGetValue(permissionCode, out var name))
return name;
return null;
}
/// <summary>
/// get a permission tuple using it's name. returns null if not found
/// </summary>
/// <param name="permissionName">name of the permission</param>
public static (string PermissionName, string PermissionCode)? PermissionFromName(string permissionName)
{
if (_permNames.TryGetValue(permissionName, out var code))
return new(permissionName, code);
return null;
}
/// <summary>
/// get the permission tuple using it's code. returns null if not found
/// </summary>
/// <param name="permissionCode">code of the permission to get</param>
public static (string PermissionName, string PermissionCode)? PermissionFromCode(string permissionCode)
{
if (_permCodes.TryGetValue(permissionCode, out var name))
return new(name, permissionCode);
return null;
}
/// <summary>
/// get a list of all permission names
/// </summary>
public static IEnumerable<string> AllNames()
=> _permNames.Keys;
/// <summary>
/// get a list of all permission codes
/// </summary>
public static IEnumerable<string> AllCodes()
=> _permNames.Values;
/// <summary>
/// get a list of all the defined permissions
/// </summary>
public static IEnumerable<(string PermissionName, string PermissionCode)> AllPermissions()
=> _permNames.Select(kv => new ValueTuple<string, string>(kv.Key, kv.Value));
}
""";
readonly
|
Allow
|
csharp
|
mongodb__mongo-csharp-driver
|
src/MongoDB.Driver/Search/SearchFacetBuilder.cs
|
{
"start": 11573,
"end": 12349
}
|
internal sealed class ____<TDocument> : SearchFacet<TDocument>
{
private readonly int? _numBuckets;
private readonly SearchPathDefinition<TDocument> _path;
public StringSearchFacet(string name, SearchPathDefinition<TDocument> path, int? numBuckets = null)
: base(name)
{
_path = Ensure.IsNotNull(path, nameof(path));
_numBuckets = Ensure.IsNullOrBetween(numBuckets, 1, 1000, nameof(numBuckets));
}
public override BsonDocument Render(RenderArgs<TDocument> args) =>
new()
{
{ "type", "string" },
{ "path", _path.Render(args) },
{ "numBuckets", _numBuckets, _numBuckets != null }
};
}
}
|
StringSearchFacet
|
csharp
|
dotnet__efcore
|
test/EFCore.SqlServer.FunctionalTests/Types/Numeric/SqlServerByteTypeTest.cs
|
{
"start": 5151,
"end": 5488
}
|
public class ____ : SqlServerTypeFixture<byte>
{
public override byte Value { get; } = byte.MinValue;
public override byte OtherValue { get; } = byte.MaxValue;
}
[ConditionalFact]
public virtual void Check_all_tests_overridden()
=> TestHelpers.AssertAllMethodsOverridden(GetType());
}
|
ByteTypeFixture
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Core/Messages/ClusterInfoDto.cs
|
{
"start": 316,
"end": 944
}
|
public class ____ {
public MemberInfoDto[] Members { get; set; }
public string ServerIp { get; set; }
public int ServerPort { get; set; }
public ClusterInfoDto() {
}
public ClusterInfoDto(ClusterInfo clusterInfo, EndPoint serverEndPoint) {
Members = clusterInfo.Members.Select(x => new MemberInfoDto(x)).ToArray();
ServerIp = serverEndPoint.GetHost();
ServerPort = serverEndPoint.GetPort();
}
public override string ToString() {
return string.Format("Server: {0}:{1}, Members: [{2}]",
ServerIp, ServerPort,
Members != null ? string.Join(",", Members.Select(m => m.ToString())) : "null");
}
}
|
ClusterInfoDto
|
csharp
|
dotnet__aspire
|
src/Aspire.Hosting/ApplicationModel/ResourceReadyEvent.cs
|
{
"start": 601,
"end": 987
}
|
public class ____(IResource resource, IServiceProvider services) : IDistributedApplicationResourceEvent
{
/// <summary>
/// The resource that is in a healthy state.
/// </summary>
public IResource Resource => resource;
/// <summary>
/// The service provider for the app host.
/// </summary>
public IServiceProvider Services => services;
}
|
ResourceReadyEvent
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Aws/src/ServiceStack.Aws/Sqs/SqsQueueName.cs
|
{
"start": 674,
"end": 1840
}
|
public class ____ : IEquatable<SqsQueueName>
{
public SqsQueueName(string originalQueueName, string awsQueueAccountId = null)
{
QueueName = originalQueueName;
AwsQueueName = originalQueueName.ToValidQueueName();
AwsQueueAccountId = awsQueueAccountId;
}
public string QueueName { get; }
public string AwsQueueName { get; private set; }
public string AwsQueueAccountId { get; set; }
public bool Equals(SqsQueueName other)
{
return other != null &&
QueueName.Equals(other.QueueName, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (ReferenceEquals(this, obj))
return true;
return obj is SqsQueueName asQueueName && Equals(asQueueName);
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return QueueName;
}
}
}
|
SqsQueueName
|
csharp
|
dotnet__extensions
|
test/Libraries/Microsoft.AspNetCore.Diagnostics.Middleware.Tests/Buffering/PerIncomingRequestLoggingBuilderExtensionsTests.cs
|
{
"start": 894,
"end": 5992
}
|
public class ____
{
[Fact]
public void WhenLogLevelProvided_RegistersInDI()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder =>
{
builder.AddPerIncomingRequestBuffer(LogLevel.Warning);
});
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var buffer = serviceProvider.GetService<PerRequestLogBuffer>();
Assert.NotNull(buffer);
Assert.IsAssignableFrom<PerRequestLogBufferManager>(buffer);
}
[Fact]
public void WhenArgumentNull_Throws()
{
ILoggingBuilder? builder = null;
IConfiguration? configuration = null;
Assert.Throws<ArgumentNullException>(() => builder!.AddPerIncomingRequestBuffer(LogLevel.Warning));
Assert.Throws<ArgumentNullException>(() => builder!.AddPerIncomingRequestBuffer(configuration!));
}
[Fact]
public void WhenIConfigurationProvided_RegistersInDI()
{
List<LogBufferingFilterRule> expectedData =
[
new(categoryName: "Program.MyLogger", logLevel: LogLevel.Information, eventId: 1, eventName: "number one"),
new(logLevel: LogLevel.Information),
];
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile("appsettings.json");
IConfigurationRoot configuration = configBuilder.Build();
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(b => b.AddPerIncomingRequestBuffer(configuration));
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var options = serviceProvider.GetService<IOptionsMonitor<PerRequestLogBufferingOptions>>();
Assert.NotNull(options);
Assert.NotNull(options.CurrentValue);
Assert.Equivalent(expectedData, options.CurrentValue.Rules);
}
[Fact]
public void WhenConfigurationActionProvided_RegistersInDI()
{
List<LogBufferingFilterRule> expectedData =
[
new(categoryName: "Program.MyLogger", logLevel: LogLevel.Information, eventId: 1, eventName: "number one"),
new(logLevel: LogLevel.Information),
];
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(b => b.AddPerIncomingRequestBuffer(options =>
{
options.Rules.Add(new LogBufferingFilterRule(categoryName: "Program.MyLogger",
logLevel: LogLevel.Information, eventId: 1, eventName: "number one"));
options.Rules.Add(new LogBufferingFilterRule(logLevel: LogLevel.Information));
}));
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var options = serviceProvider.GetService<IOptionsMonitor<PerRequestLogBufferingOptions>>();
Assert.NotNull(options);
Assert.NotNull(options.CurrentValue);
Assert.Equivalent(expectedData, options.CurrentValue.Rules);
}
[Fact]
public async Task WhenConfigUpdated_PicksUpConfigChanges()
{
List<LogBufferingFilterRule> initialData =
[
new(categoryName: "Program.MyLogger", logLevel: LogLevel.Information, eventId: 1, eventName: "number one"),
new(logLevel : LogLevel.Information),
];
List<LogBufferingFilterRule> updatedData =
[
new(logLevel: LogLevel.Information),
];
string jsonConfig =
@"
{
""PerIncomingRequestLogBuffering"": {
""Rules"": [
{
""CategoryName"": ""Program.MyLogger"",
""LogLevel"": ""Information"",
""EventId"": 1,
""EventName"": ""number one"",
},
{
""LogLevel"": ""Information"",
},
]
}
}
";
using ConfigurationRoot config = TestConfiguration.Create(() => jsonConfig);
using IHost host = await FakeHost.CreateBuilder()
.ConfigureWebHost(builder => builder
.UseTestServer()
.ConfigureServices(x => x.AddRouting())
.ConfigureLogging(loggingBuilder => loggingBuilder
.AddPerIncomingRequestBuffer(config))
.Configure(app => app.UseRouting()))
.StartAsync();
IOptionsMonitor<PerRequestLogBufferingOptions>? options = host.Services.GetService<IOptionsMonitor<PerRequestLogBufferingOptions>>();
Assert.NotNull(options);
Assert.NotNull(options.CurrentValue);
Assert.Equivalent(initialData, options.CurrentValue.Rules);
jsonConfig =
@"
{
""PerIncomingRequestLogBuffering"": {
""Rules"": [
{
""LogLevel"": ""Information"",
},
]
}
}
";
config.Reload();
var bufferManager = host.Services.GetRequiredService<PerRequestLogBuffer>() as PerRequestLogBufferManager;
Assert.NotNull(bufferManager);
Assert.Equivalent(updatedData, bufferManager.Options.CurrentValue.Rules, strict: true);
await host.StopAsync();
}
}
#endif
|
PerIncomingRequestLoggingBuilderExtensionsTests
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/TestModels/ConferencePlanner/EntityExtensions.cs
|
{
"start": 309,
"end": 2143
}
|
public static class ____
{
public static SessionResponse MapSessionResponse(this Session session)
=> new()
{
Id = session.Id,
Title = session.Title,
StartTime = session.StartTime,
EndTime = session.EndTime,
Speakers = session.SessionSpeakers?
.Select(ss => new ConferenceDTO.Speaker { Id = ss.SpeakerId, Name = ss.Speaker.Name })
.ToList(),
TrackId = session.TrackId,
Track = new ConferenceDTO.Track { Id = session?.TrackId ?? 0, Name = session.Track?.Name },
Abstract = session.Abstract
};
public static SpeakerResponse MapSpeakerResponse(this Speaker speaker)
=> new()
{
Id = speaker.Id,
Name = speaker.Name,
Bio = speaker.Bio,
WebSite = speaker.WebSite,
Sessions = speaker.SessionSpeakers?
.Select(ss =>
new ConferenceDTO.Session { Id = ss.SessionId, Title = ss.Session.Title })
.ToList()
};
public static AttendeeResponse MapAttendeeResponse(this Attendee attendee)
=> new()
{
Id = attendee.Id,
FirstName = attendee.FirstName,
LastName = attendee.LastName,
UserName = attendee.UserName,
EmailAddress = attendee.EmailAddress,
Sessions = attendee.SessionsAttendees?
.Select(sa =>
new ConferenceDTO.Session
{
Id = sa.SessionId,
Title = sa.Session.Title,
StartTime = sa.Session.StartTime,
EndTime = sa.Session.EndTime
})
.ToList()
};
}
|
EntityExtensions
|
csharp
|
pythonnet__pythonnet
|
src/embed_tests/Codecs.cs
|
{
"start": 9249,
"end": 12666
}
|
class ____ throw a python exception when it tries to access any element.
//TryDecode is a lossless conversion so there will be no exception at that point
//interestingly, since the size of the python sequence can be queried without any conversion,
//the IList will report a Count of 3.
ICollection<string> stringCollection2 = null;
Assert.DoesNotThrow(() => { codec.TryDecode(pyTuple, out stringCollection2); });
Assert.AreEqual(3, stringCollection2.Count());
Assert.Throws(typeof(InvalidCastException), () => {
string[] array = new string[3];
stringCollection2.CopyTo(array, 0);
});
Runtime.CheckExceptionOccurred();
}
[Test]
public void IterableDecoderTest()
{
var codec = IterableDecoder.Instance;
var items = new List<PyObject>() { new PyInt(1), new PyInt(2), new PyInt(3) };
var pyList = new PyList(items.ToArray());
var pyListType = pyList.GetPythonType();
Assert.IsFalse(codec.CanDecode(pyListType, typeof(IList<bool>)));
Assert.IsTrue(codec.CanDecode(pyListType, typeof(System.Collections.IEnumerable)));
Assert.IsTrue(codec.CanDecode(pyListType, typeof(IEnumerable<int>)));
Assert.IsFalse(codec.CanDecode(pyListType, typeof(ICollection<float>)));
Assert.IsFalse(codec.CanDecode(pyListType, typeof(bool)));
//ensure a PyList can be converted to a plain IEnumerable
System.Collections.IEnumerable plainEnumerable1 = null;
Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out plainEnumerable1); });
CollectionAssert.AreEqual(plainEnumerable1.Cast<PyInt>().Select(i => i.ToInt32()), new List<object> { 1, 2, 3 });
//can convert to any generic ienumerable. If the type is not assignable from the python element
//it will lead to an empty iterable when decoding. TODO - should it throw?
Assert.IsTrue(codec.CanDecode(pyListType, typeof(IEnumerable<int>)));
Assert.IsTrue(codec.CanDecode(pyListType, typeof(IEnumerable<double>)));
Assert.IsTrue(codec.CanDecode(pyListType, typeof(IEnumerable<string>)));
IEnumerable<int> intEnumerable = null;
Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out intEnumerable); });
CollectionAssert.AreEqual(intEnumerable, new List<object> { 1, 2, 3 });
Runtime.CheckExceptionOccurred();
IEnumerable<double> doubleEnumerable = null;
Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out doubleEnumerable); });
CollectionAssert.AreEqual(doubleEnumerable, new List<object> { 1, 2, 3 });
Runtime.CheckExceptionOccurred();
IEnumerable<string> stringEnumerable = null;
Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out stringEnumerable); });
Assert.Throws(typeof(InvalidCastException), () => {
foreach (string item in stringEnumerable)
{
var x = item;
}
});
Assert.Throws(typeof(InvalidCastException), () => {
stringEnumerable.Count();
});
Runtime.CheckExceptionOccurred();
//ensure a python
|
will
|
csharp
|
microsoft__PowerToys
|
src/common/LanguageModelProvider/ILanguageModelProvider.cs
|
{
"start": 250,
"end": 555
}
|
public interface ____
{
string Name { get; }
string ProviderDescription { get; }
Task<IEnumerable<ModelDetails>> GetModelsAsync(CancellationToken cancelationToken = default);
IChatClient? GetIChatClient(string modelId);
string GetIChatClientString(string url);
}
|
ILanguageModelProvider
|
csharp
|
dotnet__orleans
|
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestBasicClassWithAnnotatedFields.verified.cs
|
{
"start": 10706,
"end": 11211
}
|
internal sealed class ____ : global::Orleans.Serialization.Configuration.TypeManifestProviderBase
{
protected override void ConfigureInner(global::Orleans.Serialization.Configuration.TypeManifestOptions config)
{
config.Serializers.Add(typeof(OrleansCodeGen.TestProject.Codec_DemoDataWithFields));
config.Copiers.Add(typeof(OrleansCodeGen.TestProject.Copier_DemoDataWithFields));
}
}
}
#pragma warning restore CS1591, RS0016, RS0041
|
Metadata_TestProject
|
csharp
|
DapperLib__Dapper
|
tests/Dapper.Tests/MiscTests.cs
|
{
"start": 43454,
"end": 43563
}
|
public class ____
{
public StatusType Status { get; set; }
}
|
Issue142_Status
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.Server.Tests/Messaging/MqServerIntroTests.cs
|
{
"start": 2508,
"end": 2690
}
|
public class ____ : IHasBearerToken, IReturn<MqAuthOnlyResponse>
{
public string Name { get; set; }
public string BearerToken { get; set; }
}
|
MqAuthOnlyToken
|
csharp
|
dotnet__maui
|
src/Core/src/LifecycleEvents/Android/AndroidLifecycleExtensions.cs
|
{
"start": 60,
"end": 362
}
|
public static class ____
{
public static ILifecycleBuilder AddAndroid(this ILifecycleBuilder builder, Action<IAndroidLifecycleBuilder> configureDelegate)
{
var lifecycle = new LifecycleBuilder(builder);
configureDelegate?.Invoke(lifecycle);
return builder;
}
|
AndroidLifecycleExtensions
|
csharp
|
neuecc__MessagePack-CSharp
|
tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/MessagePack.GeneratedMessagePackResolver.g.cs
|
{
"start": 1230,
"end": 1872
}
|
private static class ____
{
private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1)
{
{ typeof(global::Test3), 0 },
};
internal static object GetFormatter(global::System.Type t)
{
if (closedTypeLookup.TryGetValue(t, out int closedKey))
{
switch (closedKey)
{
case 0: return new global::MessagePack.GeneratedMessagePackResolver.Test3Formatter();
default: return null; // unreachable
};
}
return null;
}
}
}
}
|
GeneratedMessagePackResolverGetFormatterHelper
|
csharp
|
ChilliCream__graphql-platform
|
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
|
{
"start": 2125560,
"end": 2128716
}
|
public partial class ____ : global::System.IEquatable<OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange>, IOnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange
{
public OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity severity, global::System.String coordinate, global::System.String typeName, global::System.String fieldName)
{
this.__typename = __typename;
Severity = severity;
Coordinate = coordinate;
TypeName = typeName;
FieldName = fieldName;
}
/// <summary>
/// The name of the current Object type at runtime.
/// </summary>
public global::System.String __typename { get; }
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity Severity { get; }
public global::System.String Coordinate { get; }
public global::System.String TypeName { get; }
public global::System.String FieldName { get; }
public virtual global::System.Boolean Equals(OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (__typename.Equals(other.__typename)) && Severity.Equals(other.Severity) && Coordinate.Equals(other.Coordinate) && TypeName.Equals(other.TypeName) && FieldName.Equals(other.FieldName);
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * __typename.GetHashCode();
hash ^= 397 * Severity.GetHashCode();
hash ^= 397 * Coordinate.GetHashCode();
hash ^= 397 * TypeName.GetHashCode();
hash ^= 397 * FieldName.GetHashCode();
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
|
OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_FieldAddedChange
|
csharp
|
protobuf-net__protobuf-net
|
src/protobuf-net.Core/Serializers/MapSerializer.Immutable.cs
|
{
"start": 1716,
"end": 3467
}
|
sealed class ____<TKey, TValue> : MapSerializer<ImmutableDictionary<TKey, TValue>, TKey, TValue>
{
protected override ImmutableDictionary<TKey, TValue> Clear(ImmutableDictionary<TKey, TValue> values, ISerializationContext context)
=> values.Clear();
protected override ImmutableDictionary<TKey, TValue> Initialize(ImmutableDictionary<TKey, TValue> values, ISerializationContext context)
=> values ?? ImmutableDictionary<TKey, TValue>.Empty;
protected override ImmutableDictionary<TKey, TValue> AddRange(ImmutableDictionary<TKey, TValue> values, ref ArraySegment<KeyValuePair<TKey, TValue>> newValues, ISerializationContext context)
{
if (newValues.Count == 1)
{
var pair = newValues.Singleton();
return values.Add(pair.Key, pair.Value);
}
return values.AddRange(newValues);
}
protected override ImmutableDictionary<TKey, TValue> SetValues(ImmutableDictionary<TKey, TValue> values, ref ArraySegment<KeyValuePair<TKey, TValue>> newValues, ISerializationContext context)
{
if (newValues.Count == 1)
{
var pair = newValues.Singleton();
return values.SetItem(pair.Key, pair.Value);
}
return values.SetItems(newValues);
}
internal override void Write(ref ProtoWriter.State state, int fieldNumber, WireType wireType, ImmutableDictionary<TKey, TValue> values, in KeyValuePairSerializer<TKey, TValue> pairSerializer)
{
var iter = values.GetEnumerator();
Write(ref state, fieldNumber, wireType, ref iter, pairSerializer);
}
}
|
ImmutableDictionarySerializer
|
csharp
|
dotnet__aspire
|
tests/Aspire.Hosting.Analyzers.Tests/EndpointNameAnalyzerTests.cs
|
{
"start": 3611,
"end": 4067
}
|
public static class ____
{
public static IResourceBuilder<ContainerResource> WithEndpoints(
this IResourceBuilder<ContainerResource> builder,
[EndpointName] string param1Name,
[EndpointName] string param2Name)
{
return builder;
}
}
""", []);
await test.RunAsync();
}
}
|
TestExtensions
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.HostApp/Issues/Issue25671.xaml.cs
|
{
"start": 2895,
"end": 3474
}
|
public class ____ : Grid
{
public static long MeasurePasses = 0;
public static long ArrangePasses = 0;
protected override Size ArrangeOverride(Rect bounds)
{
Interlocked.Increment(ref Issue25671.ArrangePasses);
Interlocked.Increment(ref ArrangePasses);
return base.ArrangeOverride(bounds);
}
protected override Size MeasureOverride(double widthConstraint, double heightConstraint)
{
Interlocked.Increment(ref Issue25671.MeasurePasses);
Interlocked.Increment(ref MeasurePasses);
return base.MeasureOverride(widthConstraint, heightConstraint);
}
}
|
Issue25671Grid
|
csharp
|
unoplatform__uno
|
src/Uno.UI.Tests/Windows_UI_Xaml_Data/xBindTests/Controls/Binding_Event.xaml.cs
|
{
"start": 751,
"end": 1123
}
|
partial class ____ : Page
{
public Binding_Event()
{
this.InitializeComponent();
}
public int CheckedRaised { get; private set; }
public int UncheckedRaised { get; private set; }
private void OnCheckedRaised()
{
CheckedRaised++;
}
private void OnUncheckedRaised(object sender, RoutedEventArgs args)
{
UncheckedRaised++;
}
}
}
|
Binding_Event
|
csharp
|
dotnet__efcore
|
test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs
|
{
"start": 25380,
"end": 25681
}
|
protected class ____
{
public int Id { get; set; }
public PrincipalComposite Principal { get; set; } = null!;
public long PrincipalId1 { get; set; }
public Guid PrincipalId2 { get; set; }
public int PrincipalId3 { get; set; }
}
|
RequiredSingleComposite
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.