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 | AutoFixture__AutoFixture | Src/AutoFixtureDocumentationTest/Simple/Filter.cs | {
"start": 68,
"end": 750
} | public class ____
{
private int max;
private int min;
public int Max
{
get => this.max;
set
{
if (value < this.Min)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
this.max = value;
}
}
public int Min
{
get => this.min;
set
{
if (value > this.Max)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
this.min = value;
}
}
}
}
| Filter |
csharp | files-community__Files | src/Files.App/Data/Enums/WindowsCompatibilityModes.cs | {
"start": 613,
"end": 779
} | public enum ____
{
[Description("")]
None,
[Description("256COLOR")]
Color8Bit,
[Description("16BITCOLOR")]
Color16Bit
}
| WindowsCompatReducedColorModeKind |
csharp | dotnet__machinelearning | src/Microsoft.ML.FastTree/Training/Applications/GradientWrappers.cs | {
"start": 312,
"end": 363
} | class ____ the targets.
/// </summary>
| holding |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Range.cs | {
"start": 2396,
"end": 3013
} | internal sealed class ____ : Producer<int, RangeLongRunning.RangeSink>
{
private readonly int _start;
private readonly int _count;
private readonly ISchedulerLongRunning _scheduler;
public RangeLongRunning(int start, int count, ISchedulerLongRunning scheduler)
{
_start = start;
_count = count;
_scheduler = scheduler;
}
protected override RangeSink CreateSink(IObserver<int> observer) => new(_start, _count, observer);
protected override void Run(RangeSink sink) => sink.Run(_scheduler);
| RangeLongRunning |
csharp | dotnet__extensions | test/Libraries/Microsoft.Extensions.AI.OpenAI.Tests/ThrowUserAgentExceptionHandler.cs | {
"start": 267,
"end": 568
} | internal sealed class ____ : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
throw new InvalidOperationException($"User-Agent header: {request.Headers.UserAgent}");
}
| ThrowUserAgentExceptionHandler |
csharp | unoplatform__uno | src/SolutionTemplate/UnoAppWinUI/UnoAppWinUI.Server/Controllers/WeatherForecastController.cs | {
"start": 223,
"end": 921
} | public class ____ : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
=> Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
| WeatherForecastController |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Oracle.Tests/OracleParamTests.cs | {
"start": 43111,
"end": 43362
} | public class ____ : Param<ParamSize>
{
public int Size { get; set; }
public override void SetValue(int value) { Size = value; }
public override ParamSize GetObject() { return this; }
}
| ParamSize |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/MessageUrnSpecs.cs | {
"start": 4226,
"end": 4291
} | public class ____
{
}
[MessageUrn(null)]
| Attributed |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Abstractions/Modules/Services/TimeZoneSelectorResult.cs | {
"start": 32,
"end": 165
} | public class ____
{
public int Priority { get; set; }
public Func<Task<string>> TimeZoneId { get; set; }
}
| TimeZoneSelectorResult |
csharp | Xabaril__AspNetCore.Diagnostics.HealthChecks | test/HealthChecks.Sqlite.Tests/Functional/SqliteHealthCheckTests.cs | {
"start": 68,
"end": 2543
} | public class ____
{
[Fact]
public async Task be_healthy_when_sqlite_is_available()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddSqlite($"Data Source=sqlite.db", healthQuery: "select name from sqlite_master where type='table'", tags: ["sqlite"]);
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("sqlite")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact]
public async Task be_unhealthy_when_sqlite_is_unavailable()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddSqlite($"Data Source=fake.db", healthQuery: "select * from Users", tags: ["sqlite"]);
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("sqlite")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
}
[Fact]
public async Task be_unhealthy_when_sqlquery_is_not_valid()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddSqlite($"Data Source=sqlite.db", healthQuery: "select name from invaliddb", tags: ["sqlite"]);
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("sqlite")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
}
}
| sqlite_healthcheck_should |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Validation/Errors/ArgumentsOfCorrectTypeError.cs | {
"start": 133,
"end": 851
} | public class ____ : ValidationError
{
internal const string NUMBER = "5.6.1";
/// <summary>
/// Initializes a new instance with the specified properties.
/// </summary>
public ArgumentsOfCorrectTypeError(ValidationContext context, GraphQLArgument node, string verboseErrors)
: base(context.Document.Source, NUMBER, BadValueMessage(node.Name.StringValue, verboseErrors), node)
{
}
internal static string BadValueMessage(string argName, string verboseErrors)
{
return string.IsNullOrEmpty(verboseErrors)
? $"Argument '{argName}' has invalid value."
: $"Argument '{argName}' has invalid value. {verboseErrors}";
}
}
| ArgumentsOfCorrectTypeError |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/DragDrop/DropCompletedEventArgs.cs | {
"start": 155,
"end": 684
} | public partial class ____ : RoutedEventArgs
{
internal DropCompletedEventArgs(UIElement originalSource, CoreDragInfo info, DataPackageOperation result)
: base(originalSource)
{
Info = info;
DropResult = result;
CanBubbleNatively = false;
}
/// <summary>
/// Get access to the shared data, for internal usage only.
/// This has to be treated as readonly for drop completed.
/// </summary>
internal CoreDragInfo Info { get; }
public DataPackageOperation DropResult { get; }
}
}
| DropCompletedEventArgs |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.LogProperties.cs | {
"start": 4533,
"end": 4568
} | struct ____ {{ }}
| MyStruct |
csharp | MonoGame__MonoGame | MonoGame.Framework/Content/ContentReaders/SByteReader.cs | {
"start": 364,
"end": 632
} | internal class ____ : ContentTypeReader<sbyte>
{
public SByteReader()
{
}
protected internal override sbyte Read(ContentReader input, sbyte existingInstance)
{
return input.ReadSByte();
}
}
}
| SByteReader |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/TrainCatalog.cs | {
"start": 7116,
"end": 16138
} | public sealed class ____ : CatalogInstantiatorBase
{
internal BinaryClassificationTrainers(BinaryClassificationCatalog catalog)
: base(catalog)
{
}
}
/// <summary>
/// Evaluates scored binary classification data.
/// </summary>
/// <param name="data">The scored data.</param>
/// <param name="labelColumnName">The name of the label column in <paramref name="data"/>.</param>
/// <param name="scoreColumnName">The name of the score column in <paramref name="data"/>.</param>
/// <param name="probabilityColumnName">The name of the probability column in <paramref name="data"/>, the calibrated version of <paramref name="scoreColumnName"/>.</param>
/// <param name="predictedLabelColumnName">The name of the predicted label column in <paramref name="data"/>.</param>
/// <returns>The evaluation results for these calibrated outputs.</returns>
public CalibratedBinaryClassificationMetrics Evaluate(IDataView data, string labelColumnName = DefaultColumnNames.Label, string scoreColumnName = DefaultColumnNames.Score,
string probabilityColumnName = DefaultColumnNames.Probability, string predictedLabelColumnName = DefaultColumnNames.PredictedLabel)
{
Environment.CheckValue(data, nameof(data));
Environment.CheckNonEmpty(labelColumnName, nameof(labelColumnName));
Environment.CheckNonEmpty(scoreColumnName, nameof(scoreColumnName));
Environment.CheckNonEmpty(probabilityColumnName, nameof(probabilityColumnName));
Environment.CheckNonEmpty(predictedLabelColumnName, nameof(predictedLabelColumnName));
var eval = new BinaryClassifierEvaluator(Environment, new BinaryClassifierEvaluator.Arguments() { });
return eval.Evaluate(data, labelColumnName, scoreColumnName, probabilityColumnName, predictedLabelColumnName);
}
/// <summary>
/// Evaluates scored binary classification data, without probability-based metrics.
/// </summary>
/// <param name="data">The scored data.</param>
/// <param name="labelColumnName">The name of the label column in <paramref name="data"/>.</param>
/// <param name="scoreColumnName">The name of the score column in <paramref name="data"/>.</param>
/// <param name="predictedLabelColumnName">The name of the predicted label column in <paramref name="data"/>.</param>
/// <returns>The evaluation results for these uncalibrated outputs.</returns>
public BinaryClassificationMetrics EvaluateNonCalibrated(IDataView data, string labelColumnName = DefaultColumnNames.Label, string scoreColumnName = DefaultColumnNames.Score,
string predictedLabelColumnName = DefaultColumnNames.PredictedLabel)
{
Environment.CheckValue(data, nameof(data));
Environment.CheckNonEmpty(labelColumnName, nameof(labelColumnName));
Environment.CheckNonEmpty(predictedLabelColumnName, nameof(predictedLabelColumnName));
var eval = new BinaryClassifierEvaluator(Environment, new BinaryClassifierEvaluator.Arguments() { });
return eval.Evaluate(data, labelColumnName, scoreColumnName, predictedLabelColumnName);
}
/// <summary>
/// Run cross-validation over <paramref name="numberOfFolds"/> folds of <paramref name="data"/>, by fitting <paramref name="estimator"/>,
/// and respecting <paramref name="samplingKeyColumnName"/> if provided.
/// Then evaluate each sub-model against <paramref name="labelColumnName"/> and return a <see cref="BinaryClassificationMetrics"/> object, which
/// do not include probability-based metrics, for each sub-model. Each sub-model is evaluated on the cross-validation fold that it did not see during training.
/// </summary>
/// <param name="data">The data to run cross-validation on.</param>
/// <param name="estimator">The estimator to fit.</param>
/// <param name="numberOfFolds">Number of cross-validation folds.</param>
/// <param name="labelColumnName">The label column (for evaluation).</param>
/// <param name="samplingKeyColumnName">Name of a column to use for grouping rows. If two examples share the same value of the <paramref name="samplingKeyColumnName"/>,
/// they are guaranteed to appear in the same subset (train or test). This can be used to ensure no label leakage from the train to the test set.
/// If <see langword="null"/> no row grouping will be performed.</param>
/// <param name="seed">Seed for the random number generator used to select rows for cross-validation folds.</param>
/// <returns>Per-fold results: metrics, models, scored datasets.</returns>
public IReadOnlyList<CrossValidationResult<BinaryClassificationMetrics>> CrossValidateNonCalibrated(
IDataView data, IEstimator<ITransformer> estimator, int numberOfFolds = 5, string labelColumnName = DefaultColumnNames.Label,
string samplingKeyColumnName = null, int? seed = null)
{
Environment.CheckNonEmpty(labelColumnName, nameof(labelColumnName));
var result = CrossValidateTrain(data, estimator, numberOfFolds, samplingKeyColumnName, seed);
return result.Select(x => new CrossValidationResult<BinaryClassificationMetrics>(x.Model,
EvaluateNonCalibrated(x.Scores, labelColumnName), x.Scores, x.Fold)).ToArray();
}
/// <summary>
/// Run cross-validation over <paramref name="numberOfFolds"/> folds of <paramref name="data"/>, by fitting <paramref name="estimator"/>,
/// and respecting <paramref name="samplingKeyColumnName"/> if provided.
/// Then evaluate each sub-model against <paramref name="labelColumnName"/> and return a <see cref="CalibratedBinaryClassificationMetrics"/> object, which
/// includes probability-based metrics, for each sub-model. Each sub-model is evaluated on the cross-validation fold that it did not see during training.
/// </summary>
/// <param name="data">The data to run cross-validation on.</param>
/// <param name="estimator">The estimator to fit.</param>
/// <param name="numberOfFolds">Number of cross-validation folds.</param>
/// <param name="labelColumnName">The label column (for evaluation).</param>
/// <param name="samplingKeyColumnName">Name of a column to use for grouping rows. If two examples share the same value of the <paramref name="samplingKeyColumnName"/>,
/// they are guaranteed to appear in the same subset (train or test). This can be used to ensure no label leakage from the train to the test set.
/// If <see langword="null"/> no row grouping will be performed.</param>
/// <param name="seed">Seed for the random number generator used to select rows for cross-validation folds.</param>
/// <returns>Per-fold results: metrics, models, scored datasets.</returns>
public IReadOnlyList<CrossValidationResult<CalibratedBinaryClassificationMetrics>> CrossValidate(
IDataView data, IEstimator<ITransformer> estimator, int numberOfFolds = 5, string labelColumnName = DefaultColumnNames.Label,
string samplingKeyColumnName = null, int? seed = null)
{
Environment.CheckNonEmpty(labelColumnName, nameof(labelColumnName));
var result = CrossValidateTrain(data, estimator, numberOfFolds, samplingKeyColumnName, seed);
return result.Select(x => new CrossValidationResult<CalibratedBinaryClassificationMetrics>(x.Model,
Evaluate(x.Scores, labelColumnName), x.Scores, x.Fold)).ToArray();
}
/// <summary>
/// Method to modify the threshold to existing model and return modified model.
/// </summary>
/// <typeparam name="TModel">The type of the model parameters.</typeparam>
/// <param name="model">Existing model to modify threshold.</param>
/// <param name="threshold">New threshold.</param>
/// <returns>New model with modified threshold.</returns>
public BinaryPredictionTransformer<TModel> ChangeModelThreshold<TModel>(BinaryPredictionTransformer<TModel> model, float threshold)
where TModel : class
{
if (model.Threshold == threshold)
return model;
return new BinaryPredictionTransformer<TModel>(Environment, model.Model, model.TrainSchema, model.FeatureColumnName, threshold, model.ThresholdColumn);
}
/// <summary>
/// The list of calibrators for performing binary classification.
/// </summary>
public CalibratorsCatalog Calibrators { get; }
/// <summary>
/// Class used by <see cref="MLContext"/> to create instances of binary classification calibrators.
/// </summary>
| BinaryClassificationTrainers |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsCodegen.cs | {
"start": 77572,
"end": 77986
} | partial class ____ : ObservableObject
{
[ObservableProperty]
[property: DefaultValue(NegativeEnum1.Problem)]
[property: DefaultValue(NegativeEnum2.Problem)]
[property: DefaultValue(NegativeEnum3.Problem)]
[property: DefaultValue(NegativeEnum4.Problem)]
private object? a;
}
| MyViewModel |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/QueryLanguage_.cs | {
"start": 243,
"end": 311
} | internal partial class ____ : IQueryLanguage
{
}
}
| QueryLanguage |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Execution/Processing/SelectionSetOptimizerContext.cs | {
"start": 295,
"end": 5198
} | struct ____
{
private readonly OperationCompiler _compiler;
private readonly OperationCompiler.CompilerContext _compilerContext;
private readonly Dictionary<Selection, OperationCompiler.SelectionSetInfo[]> _selectionLookup;
private readonly CreateFieldPipeline _createFieldPipeline;
/// <summary>
/// Initializes a new instance of <see cref="SelectionSetOptimizerContext"/>
/// </summary>
internal SelectionSetOptimizerContext(
OperationCompiler compiler,
OperationCompiler.CompilerContext compilerContext,
Dictionary<Selection, OperationCompiler.SelectionSetInfo[]> selectionLookup,
Dictionary<string, object?> contextData,
CreateFieldPipeline createFieldPipeline,
SelectionPath path)
{
_compiler = compiler;
_compilerContext = compilerContext;
_selectionLookup = selectionLookup;
_createFieldPipeline = createFieldPipeline;
ContextData = contextData;
Path = path;
}
/// <summary>
/// Gets the schema for which the query is compiled.
/// </summary>
public Schema Schema
=> _compilerContext.Schema;
/// <summary>
/// Gets the type context of the current selection-set.
/// </summary>
public ObjectType Type
=> _compilerContext.Type;
/// <summary>
/// Gets the selections of this selection set.
/// </summary>
public IReadOnlyDictionary<string, Selection> Selections
=> _compilerContext.Fields;
/// <summary>
/// The context data dictionary can be used by middleware components and
/// resolvers to store and retrieve data during execution.
/// </summary>
public IDictionary<string, object?> ContextData { get; }
/// <summary>
/// Gets the current selection path.
/// </summary>
public SelectionPath Path { get; }
/// <summary>
/// Gets the next operation unique selection id.
/// </summary>
public int GetNextSelectionId()
=> _compiler.GetNextSelectionId();
/// <summary>
/// Sets the resolvers on the specified <paramref name="selection"/>.
/// </summary>
/// <param name="selection">
/// The selection to set the resolvers on.
/// </param>
/// <param name="resolverPipeline">
/// The async resolver pipeline.
/// </param>
/// <param name="pureResolver">
/// The pure resolver.
/// </param>
public void SetResolver(
Selection selection,
FieldDelegate? resolverPipeline = null,
PureFieldDelegate? pureResolver = null)
=> selection.SetResolvers(resolverPipeline, pureResolver);
/// <summary>
/// Allows to compile the field resolver pipeline for a field.
/// </summary>
/// <param name="field">The field.</param>
/// <param name="selection">The selection of the field.</param>
/// <returns>
/// Returns a <see cref="FieldDelegate" /> representing the field resolver pipeline.
/// </returns>
public FieldDelegate CompileResolverPipeline(ObjectField field, FieldNode selection)
=> _createFieldPipeline(Schema, field, selection);
/// <summary>
/// Adds an additional selection for internal purposes.
/// </summary>
/// <param name="newSelection">
/// The new optimized selection.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="newSelection"/> is <c>null</c>.
/// </exception>
public void AddSelection(Selection newSelection)
{
ArgumentNullException.ThrowIfNull(newSelection);
_compilerContext.Fields.Add(newSelection.ResponseName, newSelection);
_compiler.RegisterNewSelection(newSelection);
}
/// <summary>
/// Replaces an existing selection with an optimized version.
/// </summary>
/// <param name="newSelection">
/// The new optimized selection.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="newSelection"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// - There is no existing selection with the specified
/// <paramref name="newSelection"/>.ResponseName.
/// </exception>
public void ReplaceSelection(Selection newSelection)
{
ArgumentNullException.ThrowIfNull(newSelection);
if (!_compilerContext.Fields.TryGetValue(
newSelection.ResponseName,
out var currentSelection))
{
throw new ArgumentException($"The `{newSelection.ResponseName}` does not exist.");
}
_compilerContext.Fields[newSelection.ResponseName] = newSelection;
if (_selectionLookup.TryGetValue(currentSelection, out var selectionSetInfos))
{
_selectionLookup.Remove(currentSelection);
_selectionLookup.Add(newSelection, selectionSetInfos);
}
}
}
| SelectionSetOptimizerContext |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver.Encryption/StatusSafeHandle.cs | {
"start": 916,
"end": 1748
} | internal class ____ : SafeHandle
{
private StatusSafeHandle()
: base(IntPtr.Zero, true)
{
}
private StatusSafeHandle(IntPtr ptr)
: base(ptr, false)
{
}
public static StatusSafeHandle FromIntPtr(IntPtr ptr)
{
return new StatusSafeHandle(ptr);
}
public override bool IsInvalid
{
get
{
return handle == IntPtr.Zero;
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
// Here, we must obey all rules for constrained execution regions.
Library.mongocrypt_status_destroy(handle);
return true;
}
}
}
| StatusSafeHandle |
csharp | unoplatform__uno | src/Uno.Foundation/Uno.Core.Extensions/Uno.Core.Extensions.Equality/IKeyEquatable.cs | {
"start": 1046,
"end": 1702
} | internal interface ____
{
/// <summary>
/// Gets the hash code of the key of this object.
/// </summary>
/// <returns>A hash code for the current object's key.</returns>
int GetKeyHashCode();
/// <summary>
/// Indicates whether the key of current object is equal to another object's key of the same type.
/// </summary>
/// <param name="other">The object to compare with this object.</param>
/// <returns>True is the current object is another version of the <paramref name="other"/> parameter; otherwise false</returns>
bool KeyEquals(object other);
}
/// <summary>
/// Defines a generalized method that a value type or | IKeyEquatable |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Localization.Core/LocalizationPermissions.cs | {
"start": 78,
"end": 232
} | public static class ____
{
public static readonly Permission ManageCultures = new("ManageCultures", "Manage supported culture");
}
| LocalizationPermissions |
csharp | microsoft__garnet | libs/server/Resp/IRespSerializable.cs | {
"start": 239,
"end": 508
} | public interface ____
{
/// <summary>
/// Serializes the current object to RESP format
/// </summary>
/// <returns>Serialized value in RESP format</returns>
void ToRespFormat(ref RespMemoryWriter writer);
}
} | IRespSerializable |
csharp | ShareX__ShareX | ShareX.UploadersLib/Controls/AccountTypeControl.Designer.cs | {
"start": 37,
"end": 2554
} | partial class ____
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AccountTypeControl));
this.lblAccountType = new System.Windows.Forms.Label();
this.cbAccountType = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// lblAccountType
//
resources.ApplyResources(this.lblAccountType, "lblAccountType");
this.lblAccountType.Name = "lblAccountType";
//
// cbAccountType
//
this.cbAccountType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbAccountType.FormattingEnabled = true;
this.cbAccountType.Items.AddRange(new object[] {
resources.GetString("cbAccountType.Items"),
resources.GetString("cbAccountType.Items1")});
resources.ApplyResources(this.cbAccountType, "cbAccountType");
this.cbAccountType.Name = "cbAccountType";
//
// AccountTypeControl
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.cbAccountType);
this.Controls.Add(this.lblAccountType);
this.Name = "AccountTypeControl";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblAccountType;
private System.Windows.Forms.ComboBox cbAccountType;
}
}
| AccountTypeControl |
csharp | unoplatform__uno | src/SamplesApp/SamplesApp.UITests/Windows_UI_Xaml_Media_Animation/SetTarget_After_Start.cs | {
"start": 342,
"end": 2680
} | public partial class ____ : SampleControlUITestBase
{
[Test]
[AutoRetry]
public void When_Target_Is_Set_After_Start()
{
Run("UITests.Shared.Windows_UI_Xaml_Media_Animation.SetTargetProperty");
var playBtn = _app.Marked("playButton");
var animatedRect = _app.Query("AnimatedRect");
var animatedRectRect = animatedRect.Single().Rect.ToRectangle();
var container = _app.Query("Container");
var containerRect = container.Single().Rect.ToRectangle();
const int Tolerance = 7;
Assert.AreEqual(animatedRectRect.X, containerRect.X, Tolerance);
Assert.AreEqual(animatedRectRect.Y, containerRect.Y, Tolerance);
playBtn.FastTap();
_app.WaitForDependencyPropertyValue(_app.Marked("AnimationState"), "Text", "Completed!");
animatedRectRect = _app.Query("AnimatedRect").Single().Rect.ToRectangle();
// The rect should move horizontally.
Assert.AreEqual(animatedRectRect.Right, containerRect.Right, Tolerance);
Assert.AreEqual(animatedRectRect.Y, containerRect.Y, Tolerance);
// Change the direction
_app.Marked("IsDirectionHorizontalToggle").SetDependencyPropertyValue("IsOn", "True");
_app.WaitForDependencyPropertyValue(_app.Marked("AnimationState"), "Text", "Completed!");
animatedRectRect = _app.Query("AnimatedRect").Single().Rect.ToRectangle();
// The rect should move vertically.
Assert.AreEqual(animatedRectRect.Right, containerRect.Right, Tolerance);
Assert.AreEqual(animatedRectRect.Bottom, containerRect.Bottom, Tolerance);
// Toggle the rect
var animatedRect2 = _app.Query("AnimatedRect2");
var animatedRect2Rect = animatedRect2.Single().Rect.ToRectangle();
var container2 = _app.Query("Container2");
var container2Rect = container2.Single().Rect.ToRectangle();
Assert.AreEqual(animatedRect2Rect.X, container2Rect.X, Tolerance);
Assert.AreEqual(animatedRect2Rect.Y, container2Rect.Y, Tolerance);
_app.Marked("AnimatedRectSwitch").SetDependencyPropertyValue("IsOn", "True");
_app.WaitForDependencyPropertyValue(_app.Marked("AnimationState"), "Text", "Completed!");
animatedRect2Rect = _app.Query("AnimatedRect2").Single().Rect.ToRectangle();
Assert.AreEqual(animatedRect2Rect.X, container2Rect.X, Tolerance);
Assert.AreEqual(animatedRect2Rect.Bottom, container2Rect.Bottom, Tolerance);
}
}
}
| SetTarget_After_Start |
csharp | unoplatform__uno | src/Uno.UI.Tests/BinderTests/Given_Binder.TargetNullValue.cs | {
"start": 3172,
"end": 3615
} | public class ____ : TestConverter
{
public const string ConverterNullReplacement = "converted from null";
public override object Convert(object value, Type targetType, object parameter, string culture)
{
ConvertHitCount++;
return value ?? ConverterNullReplacement;
}
public override object ConvertBack(object value, Type targetType, object parameter, string culture)
{
return value;
}
}
| NeverNullConverter |
csharp | dotnet__aspire | src/Aspire.Hosting.Docker/api/Aspire.Hosting.Docker.cs | {
"start": 26646,
"end": 26985
} | partial class ____
{
[YamlDotNet.Serialization.YamlMember(Alias = "hard")]
public int? Hard { get { throw null; } set { } }
[YamlDotNet.Serialization.YamlMember(Alias = "soft")]
public int? Soft { get { throw null; } set { } }
}
[YamlDotNet.Serialization.YamlSerializable]
public sealed | Ulimit |
csharp | dotnet__aspnetcore | src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs | {
"start": 130574,
"end": 130760
} | private class ____
{
[ModelBinder(typeof(SuccessfulModelBinder))]
public bool IsBound { get; set; }
public LoopyModel2 Inner { get; set; }
}
| LoopyModel1 |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/RazorPagesWebSite/ModelWithPageFilter.cs | {
"start": 599,
"end": 1040
} | public class ____ : Attribute, IPageFilter
{
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
context.HandlerMethod = context.ActionDescriptor.HandlerMethods.First(m => m.Name == "Edit");
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
}
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
}
}
| HandlerChangingPageFilterAttribute |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1160286,
"end": 1160872
} | public partial interface ____
{
/// <summary>
/// A cursor for use in pagination.
/// </summary>
public global::System.String Cursor { get; }
/// <summary>
/// The item at the end of the edge.
/// </summary>
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListMockCommandQuery_ApiById_MockSchemas_Edges_Node Node { get; }
}
/// <summary>
/// An edge in a connection.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IListMockCommand_MockEdge |
csharp | dotnet__efcore | src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs | {
"start": 544,
"end": 5339
} | public class ____ : SqlExpression
{
private static ConstructorInfo? _quotingConstructor;
/// <summary>
/// Creates a new instance of the <see cref="ColumnExpression" /> class.
/// </summary>
/// <param name="name">The name of the column.</param>
/// <param name="tableAlias">The alias of the table to which this column refers.</param>
/// <param name="type">The <see cref="System.Type" /> of the expression.</param>
/// <param name="typeMapping">The <see cref="RelationalTypeMapping" /> associated with the expression.</param>
/// <param name="nullable">Whether this expression represents a nullable column.</param>
public ColumnExpression(
string name,
string tableAlias,
Type type,
RelationalTypeMapping? typeMapping,
bool nullable)
: this(name, tableAlias, column: null, type, typeMapping, nullable)
{
}
/// <summary>
/// Creates a new instance of the <see cref="ColumnExpression" /> class.
/// </summary>
/// <param name="name">The name of the column.</param>
/// <param name="tableAlias">The alias of the table to which this column refers.</param>
/// <param name="column">An optional <see cref="IColumnBase" /> associated with this column expression.</param>
/// <param name="type">The <see cref="System.Type" /> of the expression.</param>
/// <param name="typeMapping">The <see cref="RelationalTypeMapping" /> associated with the expression.</param>
/// <param name="nullable">Whether this expression represents a nullable column.</param>
public ColumnExpression(
string name,
string tableAlias,
IColumnBase? column,
Type type,
RelationalTypeMapping? typeMapping,
bool nullable)
: base(type, typeMapping)
{
Name = name;
TableAlias = tableAlias;
Column = column;
IsNullable = nullable;
}
/// <summary>
/// The name of the column.
/// </summary>
public virtual string Name { get; }
/// <summary>
/// The alias of the table from which column is being referenced.
/// </summary>
public virtual string TableAlias { get; }
/// <summary>
/// The bool value indicating if this column can have null values.
/// </summary>
public virtual bool IsNullable { get; }
/// <summary>
/// The <see cref="IColumnBase" /> associated with this column expression.
/// </summary>
public virtual IColumnBase? Column { get; }
/// <inheritdoc />
protected override Expression VisitChildren(ExpressionVisitor visitor)
=> this;
/// <summary>
/// Makes this column nullable.
/// </summary>
/// <returns>A new expression which has <see cref="IsNullable" /> property set to true.</returns>
public virtual ColumnExpression MakeNullable()
=> IsNullable ? this : new ColumnExpression(Name, TableAlias, Type, TypeMapping, true);
/// <summary>
/// Applies supplied type mapping to this expression.
/// </summary>
/// <param name="typeMapping">A relational type mapping to apply.</param>
/// <returns>A new expression which has supplied type mapping.</returns>
public virtual SqlExpression ApplyTypeMapping(RelationalTypeMapping? typeMapping)
=> new ColumnExpression(Name, TableAlias, Type, typeMapping, IsNullable);
/// <inheritdoc />
public override Expression Quote()
=> New(
_quotingConstructor ??= typeof(ColumnExpression).GetConstructor(
[typeof(string), typeof(string), typeof(Type), typeof(RelationalTypeMapping), typeof(bool)])!,
Constant(Name),
Constant(TableAlias),
Constant(Type),
RelationalExpressionQuotingUtilities.QuoteTypeMapping(TypeMapping),
Constant(IsNullable));
/// <inheritdoc />
protected override void Print(ExpressionPrinter expressionPrinter)
=> expressionPrinter.Append(TableAlias).Append(".").Append(Name);
/// <inheritdoc />
public override string ToString()
=> $"{TableAlias}.{Name}";
/// <inheritdoc />
public override bool Equals(object? obj)
=> obj != null
&& (ReferenceEquals(this, obj)
|| obj is ColumnExpression columnExpression
&& Equals(columnExpression));
private bool Equals(ColumnExpression columnExpression)
=> base.Equals(columnExpression)
&& Name == columnExpression.Name
&& TableAlias == columnExpression.TableAlias
&& IsNullable == columnExpression.IsNullable;
/// <inheritdoc />
public override int GetHashCode()
=> HashCode.Combine(base.GetHashCode(), Name, TableAlias, IsNullable);
}
| ColumnExpression |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/ExpressionTrees.cs | {
"start": 1765,
"end": 1934
} | internal class ____<T>
{
public GenericClassWithMultipleCtors()
{
}
public GenericClassWithMultipleCtors(int x)
{
}
}
| GenericClassWithMultipleCtors |
csharp | domaindrivendev__Swashbuckle.AspNetCore | test/Swashbuckle.AspNetCore.TestSupport/Fixtures/Enums.cs | {
"start": 208,
"end": 242
} | public enum ____:int
{
}
| EmptyIntEnum |
csharp | pythonnet__pythonnet | src/embed_tests/Events.cs | {
"start": 856,
"end": 1240
} | public class ____
{
internal static int alive;
public event EventHandler LeakEvent;
private Array arr; // dummy array to exacerbate memory leak
public ClassWithEventHandler()
{
Interlocked.Increment(ref alive);
this.arr = new int[800];
}
~ClassWithEventHandler()
{
Interlocked.Decrement(ref alive);
}
}
| ClassWithEventHandler |
csharp | unoplatform__uno | src/SourceGenerators/Uno.UI.SourceGenerators/BindableTypeProviders/BindableTypeProvidersGenerationTask.cs | {
"start": 7501,
"end": 7987
} | private class ____ : IEqualityComparer<IPropertySymbol>
{
public bool Equals(IPropertySymbol? x, IPropertySymbol? y)
{
return x?.Name == y?.Name;
}
public int GetHashCode(IPropertySymbol obj)
{
return obj.Name.GetHashCode();
}
}
private void GenerateMetadata(IndentedStringBuilder writer, IEnumerable<INamedTypeSymbol> types)
{
foreach (var type in types)
{
GenerateType(writer, type);
}
}
| PropertyNameEqualityComparer |
csharp | smartstore__Smartstore | src/Smartstore.Web/Areas/Admin/Models/Messages/QueuedEmailModel.cs | {
"start": 285,
"end": 1765
} | public class ____ : EntityModelBase
{
[LocalizedDisplay("*Id")]
public override int Id { get; set; }
[LocalizedDisplay("*Priority")]
public int Priority { get; set; }
[LocalizedDisplay("*From")]
public string From { get; set; }
[LocalizedDisplay("*To")]
public string To { get; set; }
[LocalizedDisplay("*CC")]
public string CC { get; set; }
[LocalizedDisplay("*Bcc")]
public string Bcc { get; set; }
[LocalizedDisplay("*Subject")]
public string Subject { get; set; }
[UIHint("Html")]
[LocalizedDisplay("*Body")]
public string Body { get; set; }
[LocalizedDisplay("Common.CreatedOn")]
public DateTime CreatedOn { get; set; }
[LocalizedDisplay("*SentTries")]
public int SentTries { get; set; }
[LocalizedDisplay("*SentOn")]
public DateTime? SentOn { get; set; }
[LocalizedDisplay("*EmailAccountName")]
public string EmailAccountName { get; set; }
[LocalizedDisplay("*SendManually")]
public bool SendManually { get; set; }
[LocalizedDisplay("*Attachments")]
public int AttachmentsCount { get; set; }
public string ViewUrl { get; set; }
[LocalizedDisplay("*Attachments")]
public ICollection<QueuedEmailAttachmentModel> Attachments { get; set; } = new List<QueuedEmailAttachmentModel>();
| QueuedEmailModel |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/ItemsStackPanel/IVirtualizingPanel.cs | {
"start": 380,
"end": 625
} | internal interface ____
{
/// <summary>
/// Get a native layout object with the same layout configuration as the panel and is databound to the panel's properties.
/// </summary>
VirtualizingPanelLayout GetLayouter();
}
}
| IVirtualizingPanel |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/Host/Handlers/GenericHandler.cs | {
"start": 218,
"end": 4716
} | public class ____ : ServiceStackHandlerBase, IRequestHttpHandler
{
public GenericHandler(string contentType, RequestAttributes handlerAttributes, Feature format)
{
this.HandlerContentType = contentType;
this.ContentTypeAttribute = ContentFormat.GetEndpointAttributes(contentType);
this.HandlerAttributes = handlerAttributes;
this.format = format;
}
private readonly Feature format;
public string HandlerContentType { get; set; }
public RequestAttributes ContentTypeAttribute { get; set; }
public async Task<object> CreateRequestAsync(IRequest req, string operationName)
{
var requestType = GetOperationType(operationName);
AssertOperationExists(operationName, requestType);
using var step = Profiler.Current.Step("Deserialize Request");
var requestDto = GetCustomRequestFromBinder(req, requestType)
?? (await DeserializeHttpRequestAsync(requestType, req, HandlerContentType).ConfigAwaitNetCore()
?? requestType.CreateInstance());
// Override Default Request DTO Properties with any QueryString Params
if (req.QueryString.Count > 0 && HttpUtils.HasRequestBody(req.Verb))
{
var typeSerializer = KeyValueDataContractDeserializer.Instance.GetOrAddStringMapTypeDeserializer(requestType);
foreach (var key in req.QueryString.AllKeys)
{
if (key == null) continue; //.NET Framework NameValueCollection can contain null keys
var value = req.QueryString[key];
if (string.IsNullOrEmpty(value)) continue;
var propSerializer = typeSerializer.GetPropertySerializer(key);
if (propSerializer is { PropertyGetFn: not null, PropertySetFn: not null, PropertyParseStringFn: not null })
{
var dtoValue = propSerializer.PropertyGetFn(requestDto);
if (dtoValue == null || dtoValue.Equals(propSerializer.PropertyType.GetDefaultValue()))
{
var qsValue = propSerializer.PropertyParseStringFn(value);
propSerializer.PropertySetFn(requestDto, qsValue);
}
}
}
}
HostContext.AppHost.OnAfterAwait(req);
var ret = await appHost.ApplyRequestConvertersAsync(req, requestDto).ConfigAwaitNetCore();
HostContext.AppHost.OnAfterAwait(req);
return ret;
}
public override bool RunAsAsync() => true;
public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
{
try
{
appHost.AssertFeatures(format);
httpReq.ResponseContentType = httpReq.GetQueryStringContentType() ?? this.HandlerContentType;
if (appHost.ApplyPreRequestFilters(httpReq, httpRes))
return;
var request = httpReq.Dto = await CreateRequestAsync(httpReq, operationName).ConfigAwaitNetCore();
HostContext.AppHost.OnAfterAwait(httpReq);
await appHost.ApplyRequestFiltersAsync(httpReq, httpRes, request).ConfigAwaitNetCore();
HostContext.AppHost.OnAfterAwait(httpReq);
if (httpRes.IsClosed)
return;
httpReq.RequestAttributes |= HandlerAttributes;
var rawResponse = await GetResponseAsync(httpReq, request).ConfigAwaitNetCore();
HostContext.AppHost.OnAfterAwait(httpReq);
if (httpRes.IsClosed)
return;
await HandleResponse(httpReq, httpRes, rawResponse).ConfigAwaitNetCore();
HostContext.AppHost.OnAfterAwait(httpReq);
}
//sync with RestHandler
catch (TaskCanceledException)
{
httpRes.StatusCode = (int)HttpStatusCode.PartialContent;
httpRes.EndRequest();
}
catch (Exception ex)
{
if (!HostContext.Config.WriteErrorsToResponse)
{
await HostContext.AppHost.ApplyResponseConvertersAsync(httpReq, ex).ConfigAwait();
}
else
{
var useEx = await HostContext.AppHost.ApplyResponseConvertersAsync(httpReq, ex).ConfigAwait() as Exception ?? ex;
await HandleException(httpReq, httpRes, operationName, useEx).ConfigAwait();
}
}
}
} | GenericHandler |
csharp | dotnet__machinelearning | src/Microsoft.ML.Transforms/OneHotHashEncoding.cs | {
"start": 3507,
"end": 3694
} | class ____ a merger of <see cref="HashingTransformer.Options"/> and <see cref="KeyToVectorMappingTransformer.Options"/>
/// with join option removed
/// </summary>
| is |
csharp | LibreHardwareMonitor__LibreHardwareMonitor | LibreHardwareMonitor/UI/NodeToolTipProvider.cs | {
"start": 381,
"end": 542
} | internal class ____ : IToolTipProvider
{
public string GetToolTip(TreeNodeAdv node, NodeControl nodeControl) => (node.Tag as Node)?.ToolTip;
} | NodeToolTipProvider |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/ColorProfiles/YccKTests.cs | {
"start": 276,
"end": 1246
} | public class ____
{
[Fact]
public void YccKConstructorAssignsFields()
{
const float y = .75F;
const float cb = .5F;
const float cr = .25F;
const float k = .125F;
YccK ycckValue = new(y, cb, cr, k);
Assert.Equal(y, ycckValue.Y);
Assert.Equal(cb, ycckValue.Cb);
Assert.Equal(cr, ycckValue.Cr);
Assert.Equal(k, ycckValue.K);
}
[Fact]
public void YccKEquality()
{
YccK x = default;
YccK y = new(1F, 1F, 1F, 1F);
Assert.True(default == default(YccK));
Assert.False(default != default(YccK));
Assert.Equal(default, default(YccK));
Assert.Equal(new YccK(1, 1, 1, 1), new YccK(1, 1, 1, 1));
Assert.Equal(new YccK(.5F, .5F, .5F, .5F), new YccK(.5F, .5F, .5F, .5F));
Assert.False(x.Equals(y));
Assert.False(x.Equals((object)y));
Assert.False(x.GetHashCode().Equals(y.GetHashCode()));
}
}
| YccKTests |
csharp | Humanizr__Humanizer | src/Humanizer/DateTimeHumanizeStrategy/IDateOnlyHumanizeStrategy.cs | {
"start": 208,
"end": 487
} | public interface ____
{
/// <summary>
/// Calculates the distance of time in words between two provided dates used for DateOnly.Humanize
/// </summary>
string Humanize(DateOnly input, DateOnly comparisonBase, CultureInfo? culture);
}
#endif
| IDateOnlyHumanizeStrategy |
csharp | neuecc__MessagePack-CSharp | tests/MessagePack.SourceGenerator.Tests/StringKeyedFormatterTests.cs | {
"start": 5113,
"end": 5695
} | public class ____
{
public int A { get; set; }
public string B { get; set; }
public MyMessagePackObject(int a, string b)
{
A = a;
B = b;
}
}
}
""";
await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource);
}
[Fact]
public async Task PropertiesGetterSetterWithParameterizedConstructorPartially()
{
string testSource = """
using System;
using System.Collections.Generic;
using MessagePack;
namespace TempProject
{
[MessagePackObject(true)]
| MyMessagePackObject |
csharp | getsentry__sentry-dotnet | src/Sentry/StringOrRegex.cs | {
"start": 238,
"end": 1939
} | public class ____
{
internal readonly Regex? _regex;
internal readonly string? _string;
/// <summary>
/// Constructs a <see cref="StringOrRegex"/> instance.
/// </summary>
/// <param name="stringOrRegex">The prefix or regular expression pattern to match on.</param>
public StringOrRegex(string stringOrRegex)
{
_string = stringOrRegex;
}
/// <summary>
/// Constructs a <see cref="StringOrRegex"/> instance.
/// </summary>
/// <param name="regex"></param>
/// <remarks>
/// Use this constructor when you want the match to be performed using a regular expression.
/// </remarks>
public StringOrRegex(Regex regex) => _regex = regex;
/// <summary>
/// Implicitly converts a <see cref="string"/> to a <see cref="StringOrRegex"/>.
/// </summary>
/// <param name="stringOrRegex"></param>
public static implicit operator StringOrRegex(string stringOrRegex)
{
return new StringOrRegex(stringOrRegex);
}
/// <summary>
/// Implicitly converts a <see cref="Regex"/> to a <see cref="StringOrRegex"/>.
/// </summary>
/// <param name="regex"></param>
public static implicit operator StringOrRegex(Regex regex)
{
return new StringOrRegex(regex);
}
/// <inheritdoc />
public override string ToString() => _string ?? _regex?.ToString() ?? "";
/// <inheritdoc />
public override bool Equals(object? obj)
{
return
(obj is StringOrRegex pattern)
&& pattern.ToString() == ToString();
}
/// <inheritdoc />
public override int GetHashCode()
{
return ToString().GetHashCode();
}
}
| StringOrRegex |
csharp | MassTransit__MassTransit | tests/MassTransit.EntityFrameworkIntegration.Tests/ChoirStatePessimisticSagaDbContext.cs | {
"start": 180,
"end": 556
} | class ____ : SagaDbContext
{
public ChoirStatePessimisticSagaDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected override IEnumerable<ISagaClassMap> Configurations
{
get { yield return new EntityFrameworkChoirStateMap(); }
}
| ChoirStatePessimisticSagaDbContext |
csharp | EventStore__EventStore | src/KurrentDB.Native/TransactionLog/Unbuffered/INativeFile.cs | {
"start": 325,
"end": 978
} | public interface ____ {
uint GetDriveSectorSize(string path);
long GetPageSize(string path);
void SetFileSize(SafeFileHandle handle, long count);
unsafe void Write(SafeFileHandle handle, byte* buffer, uint count, ref int written);
unsafe int Read(SafeFileHandle handle, byte* buffer, int offset, int count);
long GetFileSize(SafeFileHandle handle);
SafeFileHandle Create(string path, FileAccess acc, FileShare readWrite, FileMode mode, int flags);
SafeFileHandle CreateUnbufferedRW(string path, FileAccess acc, FileShare share, FileMode mode,
bool writeThrough);
void Seek(SafeFileHandle handle, long position, SeekOrigin origin);
}
| INativeFile |
csharp | dotnet__aspnetcore | src/Shared/ServerInfrastructure/MemoryPoolExtensions.cs | {
"start": 290,
"end": 845
} | internal static class ____
{
/// <summary>
/// Computes a minimum segment size
/// </summary>
/// <param name="pool"></param>
/// <returns></returns>
public static int GetMinimumSegmentSize(this MemoryPool<byte> pool)
{
if (pool == null)
{
return 4096;
}
return Math.Min(4096, pool.MaxBufferSize);
}
public static int GetMinimumAllocSize(this MemoryPool<byte> pool)
{
// 1/2 of a segment
return pool.GetMinimumSegmentSize() / 2;
}
}
| MemoryPoolExtensions |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/TestModels/ChangedChangingMonsterContext.cs | {
"start": 36127,
"end": 37363
} | public class ____ : NotificationEntity, ISupplier
{
private int _supplierId;
private string _name;
private ICollection<IProduct> _products;
private ISupplierLogo _logo;
private ICollection<IBackOrderLine> _backOrderLines;
public void InitializeCollections()
{
Products ??= new ObservableCollection<IProduct>();
BackOrderLines = new ObservableCollection<IBackOrderLine>();
}
public int SupplierId
{
get => _supplierId;
set => SetWithNotify(value, ref _supplierId);
}
public string Name
{
get => _name;
set => SetWithNotify(value, ref _name);
}
public virtual ICollection<IProduct> Products
{
get => _products;
set => SetWithNotify(value, ref _products);
}
public virtual ICollection<IBackOrderLine> BackOrderLines
{
get => _backOrderLines;
set => SetWithNotify(value, ref _backOrderLines);
}
public virtual ISupplierLogo Logo
{
get => _logo;
set => SetWithNotify(value, ref _logo);
}
}
| Supplier |
csharp | ServiceStack__ServiceStack.Text | src/ServiceStack.Text/AutoMappingUtils.cs | {
"start": 48238,
"end": 50600
} | internal static class ____
{
public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType)
{
if (fromType == toType)
return null;
var converter = AutoMappingUtils.GetConverter(fromType, toType);
if (converter != null)
return converter;
if (fromType == typeof(string))
return fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType);
if (toType == typeof(string))
return o => TypeSerializer.SerializeToString(o).StripQuotes();
var underlyingToType = Nullable.GetUnderlyingType(toType) ?? toType;
var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType;
if (underlyingToType.IsEnum)
{
if (underlyingFromType.IsEnum || fromType == typeof(string))
return fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true);
if (underlyingFromType.IsIntegerType())
return fromValue => Enum.ToObject(underlyingToType, fromValue);
}
else if (underlyingFromType.IsEnum)
{
if (underlyingToType.IsIntegerType())
return fromValue => Convert.ChangeType(fromValue, underlyingToType, null);
}
else if (typeof(IEnumerable).IsAssignableFrom(fromType) && underlyingToType != typeof(string))
{
return fromValue => AutoMappingUtils.TryConvertCollections(fromType, underlyingToType, fromValue);
}
else if (underlyingToType.IsValueType)
{
return fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType);
}
else
{
return fromValue =>
{
if (fromValue == null)
return fromValue;
if (toType == typeof(string))
return fromValue.ToJsv();
var toValue = toType.CreateInstance();
toValue.PopulateWith(fromValue);
return toValue;
};
}
return null;
}
}
}
| TypeConverter |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Correctness/MemberLookup.cs | {
"start": 1211,
"end": 1509
} | public class ____
{
static readonly Action delegateConstruction = (new Child1() as Base1).TestAction;
public static int Main()
{
Console.WriteLine((new Child1() as Base1).Field);
Child1.Test();
delegateConstruction();
new Child2b().CallTestMethod();
return 0;
}
| MemberLookup |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 826536,
"end": 828121
} | public partial class ____ : global::System.IEquatable<ListClientCommandQuery_Node_GraphQLOutputFieldDefinition>, IListClientCommandQuery_Node_GraphQLOutputFieldDefinition
{
public ListClientCommandQuery_Node_GraphQLOutputFieldDefinition()
{
}
public virtual global::System.Boolean Equals(ListClientCommandQuery_Node_GraphQLOutputFieldDefinition? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return true;
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ListClientCommandQuery_Node_GraphQLOutputFieldDefinition)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| ListClientCommandQuery_Node_GraphQLOutputFieldDefinition |
csharp | microsoft__PowerToys | src/modules/MouseWithoutBorders/App/Class/MyKnownBitmap.cs | {
"start": 890,
"end": 1078
} | internal class ____
{
private const int BITMAP_FILE_HEADER_SIZE = 14;
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = BITMAP_FILE_HEADER_SIZE)]
| MyKnownBitmap |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core.Tests/Services/core_projection/checkpoint_manager/multi_stream/when_starting_with_prerecorded_events_after_the_last_checkpoint.cs | {
"start": 645,
"end": 5632
} | public class ____<TLogFormat, TStreamId> :
TestFixtureWithMultiStreamCheckpointManager<TLogFormat, TStreamId> {
private readonly CheckpointTag _tag1 =
CheckpointTag.FromStreamPositions(0, new Dictionary<string, long> { { "a", 0 }, { "b", 0 }, { "c", 1 } });
private readonly CheckpointTag _tag2 =
CheckpointTag.FromStreamPositions(0, new Dictionary<string, long> { { "a", 1 }, { "b", 0 }, { "c", 1 } });
private readonly CheckpointTag _tag3 =
CheckpointTag.FromStreamPositions(0, new Dictionary<string, long> { { "a", 1 }, { "b", 1 }, { "c", 1 } });
protected override void Given() {
base.Given();
ExistingEvent(
"$projections-projection-checkpoint", ProjectionEventTypes.ProjectionCheckpoint,
@"{""s"": {""a"": 0, ""b"": 0, ""c"": 0}}", "{}");
ExistingEvent("a", "StreamCreated", "", "");
ExistingEvent("b", "StreamCreated", "", "");
ExistingEvent("c", "StreamCreated", "", "");
ExistingEvent("d", "StreamCreated", "", "");
ExistingEvent("a", "Event", "", @"{""data"":""a""");
ExistingEvent("b", "Event", "bb", @"{""data"":""b""");
ExistingEvent("c", "$>", "{$o:\"org\"}", @"1@d");
ExistingEvent("d", "Event", "dd", @"{""data"":""d""");
ExistingEvent(
"$projections-projection-order", "$>", @"{""s"": {""a"": 0, ""b"": 0, ""c"": 0}}", "0@c");
ExistingEvent(
"$projections-projection-order", "$>", @"{""s"": {""a"": 0, ""b"": 0, ""c"": 1}}", "1@c");
ExistingEvent(
"$projections-projection-order", "$>", @"{""s"": {""a"": 1, ""b"": 0, ""c"": 1}}", "1@a");
ExistingEvent(
"$projections-projection-order", "$>", @"{""s"": {""a"": 1, ""b"": 1, ""c"": 1}}", "1@b");
}
protected override void When() {
base.When();
_checkpointReader.BeginLoadState();
var checkpointLoaded =
_consumer.HandledMessages.OfType<CoreProjectionProcessingMessage.CheckpointLoaded>().First();
_checkpointWriter.StartFrom(checkpointLoaded.CheckpointTag, checkpointLoaded.CheckpointEventNumber);
_manager.BeginLoadPrerecordedEvents(checkpointLoaded.CheckpointTag);
}
[Test]
public void sends_correct_checkpoint_loaded_message() {
Assert.AreEqual(1, _projection._checkpointLoadedMessages.Count);
Assert.AreEqual(
CheckpointTag.FromStreamPositions(0, new Dictionary<string, long> { { "a", 0 }, { "b", 0 }, { "c", 0 } }),
_projection._checkpointLoadedMessages.Single().CheckpointTag);
Assert.AreEqual("{}", _projection._checkpointLoadedMessages.Single().CheckpointData);
}
[Test]
public void sends_correct_preprecoded_events_loaded_message() {
Assert.AreEqual(1, _projection._prerecordedEventsLoadedMessages.Count);
Assert.AreEqual(
CheckpointTag.FromStreamPositions(0, new Dictionary<string, long> { { "a", 1 }, { "b", 1 }, { "c", 1 } }),
_projection._prerecordedEventsLoadedMessages.Single().CheckpointTag);
}
[Test]
public void sends_committed_event_received_messages_in_correct_order() {
var messages = HandledMessages.OfType<EventReaderSubscriptionMessage.CommittedEventReceived>().ToList();
Assert.AreEqual(3, messages.Count);
var message1 = messages[0];
var message2 = messages[1];
var message3 = messages[2];
Assert.AreEqual(_tag1, message1.CheckpointTag);
Assert.AreEqual(_tag2, message2.CheckpointTag);
Assert.AreEqual(_tag3, message3.CheckpointTag);
}
[Test]
public void sends_correct_committed_event_received_messages() {
var messages = HandledMessages.OfType<EventReaderSubscriptionMessage.CommittedEventReceived>().ToList();
Assert.AreEqual(3, messages.Count);
var message1 = messages[0];
var message2 = messages[1];
var message3 = messages[2];
Assert.AreEqual(@"{""data"":""d""", message1.Data.Data);
Assert.AreEqual(@"{""data"":""a""", message2.Data.Data);
Assert.AreEqual(@"{""data"":""b""", message3.Data.Data);
Assert.AreEqual(@"dd", message1.Data.Metadata);
Assert.IsNull(message2.Data.Metadata);
Assert.AreEqual(@"bb", message3.Data.Metadata);
Assert.AreEqual("{$o:\"org\"}", message1.Data.PositionMetadata);
Assert.IsNull(message2.Data.PositionMetadata);
Assert.IsNull(message3.Data.PositionMetadata);
Assert.AreEqual("Event", message1.Data.EventType);
Assert.AreEqual("Event", message2.Data.EventType);
Assert.AreEqual("Event", message3.Data.EventType);
Assert.AreEqual("c", message1.Data.PositionStreamId);
Assert.AreEqual("a", message2.Data.PositionStreamId);
Assert.AreEqual("b", message3.Data.PositionStreamId);
Assert.AreEqual("d", message1.Data.EventStreamId);
Assert.AreEqual("a", message2.Data.EventStreamId);
Assert.AreEqual("b", message3.Data.EventStreamId);
Assert.AreEqual(_projectionCorrelationId, message1.SubscriptionId);
Assert.AreEqual(_projectionCorrelationId, message2.SubscriptionId);
Assert.AreEqual(_projectionCorrelationId, message3.SubscriptionId);
Assert.AreEqual(true, message1.Data.ResolvedLinkTo);
Assert.AreEqual(false, message2.Data.ResolvedLinkTo);
Assert.AreEqual(false, message3.Data.ResolvedLinkTo);
}
}
| when_starting_with_prerecorded_events_after_the_last_checkpoint |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Widgets/Volo/Abp/AspNetCore/Mvc/UI/Widgets/AbpViewComponentHelper.cs | {
"start": 420,
"end": 2733
} | public class ____ : IViewComponentHelper, IViewContextAware, ITransientDependency
{
protected AbpWidgetOptions Options { get; }
protected IPageWidgetManager PageWidgetManager { get; }
protected DefaultViewComponentHelper DefaultViewComponentHelper { get; }
public AbpViewComponentHelper(
DefaultViewComponentHelper defaultViewComponentHelper,
IOptions<AbpWidgetOptions> widgetOptions,
IPageWidgetManager pageWidgetManager)
{
DefaultViewComponentHelper = defaultViewComponentHelper;
PageWidgetManager = pageWidgetManager;
Options = widgetOptions.Value;
}
public virtual async Task<IHtmlContent> InvokeAsync(string name, object? arguments)
{
var widget = Options.Widgets.Find(name);
if (widget == null)
{
return await DefaultViewComponentHelper.InvokeAsync(name, arguments);
}
return await InvokeWidgetAsync(arguments, widget);
}
public virtual async Task<IHtmlContent> InvokeAsync(Type componentType, object? arguments)
{
var widget = Options.Widgets.Find(componentType);
if (widget == null)
{
return await DefaultViewComponentHelper.InvokeAsync(componentType, arguments);
}
return await InvokeWidgetAsync(arguments, widget);
}
public virtual void Contextualize(ViewContext viewContext)
{
DefaultViewComponentHelper.Contextualize(viewContext);
}
protected virtual async Task<IHtmlContent> InvokeWidgetAsync(object? arguments, WidgetDefinition widget)
{
PageWidgetManager.TryAdd(widget);
var wrapperAttributesBuilder = new StringBuilder($"class=\"abp-widget-wrapper\" data-widget-name=\"{widget.Name}\"");
if (widget.RefreshUrl != null)
{
wrapperAttributesBuilder.Append($" data-refresh-url=\"{widget.RefreshUrl}\"");
}
if (widget.AutoInitialize)
{
wrapperAttributesBuilder.Append(" data-widget-auto-init=\"true\"");
}
return new HtmlContentBuilder()
.AppendHtml($"<div {wrapperAttributesBuilder}>")
.AppendHtml(await DefaultViewComponentHelper.InvokeAsync(widget.ViewComponentType, arguments))
.AppendHtml("</div>");
}
}
| AbpViewComponentHelper |
csharp | dotnet__extensions | test/Libraries/Microsoft.AspNetCore.Testing.Tests/TestResources/Startup.cs | {
"start": 910,
"end": 937
} | class ____ testing
}
}
| for |
csharp | AutoMapper__AutoMapper | src/UnitTests/BidirectionalRelationships.cs | {
"start": 11762,
"end": 12329
} | public class ____ : IEquatable<Parent>
{
public Guid Id { get; private set; }
public string Name { get; set; }
public List<Child> Children { get; set; }
public Parent()
{
Id = Guid.NewGuid();
Children = new List<Child>();
}
public bool Equals(Parent other) => throw new NotImplementedException();
public override bool Equals(object obj) => throw new NotImplementedException();
public override int GetHashCode() => throw new NotImplementedException();
}
| Parent |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/BaseWithContract.cs | {
"start": 1269,
"end": 1690
} | public class ____
{
[DataMember(Name = "VirtualWithDataMemberBase")]
public virtual string VirtualWithDataMember { get; set; }
[DataMember]
public virtual string Virtual { get; set; }
[DataMember(Name = "WithDataMemberBase")]
public string WithDataMember { get; set; }
[DataMember]
public string JustAProperty { get; set; }
}
}
#endif | BaseWithContract |
csharp | smartstore__Smartstore | src/Smartstore.Core/Checkout/Payment/Domain/PaymentMethod.cs | {
"start": 365,
"end": 1802
} | internal class ____ : IEntityTypeConfiguration<PaymentMethod>
{
public void Configure(EntityTypeBuilder<PaymentMethod> builder)
{
builder
.HasMany(c => c.RuleSets)
.WithMany(c => c.PaymentMethods)
.UsingEntity<Dictionary<string, object>>(
"RuleSet_PaymentMethod_Mapping",
c => c
.HasOne<RuleSetEntity>()
.WithMany()
.HasForeignKey("RuleSetEntity_Id")
.HasConstraintName("FK_dbo.RuleSet_PaymentMethod_Mapping_dbo.RuleSet_RuleSetEntity_Id")
.OnDelete(DeleteBehavior.Cascade),
c => c
.HasOne<PaymentMethod>()
.WithMany()
.HasForeignKey("PaymentMethod_Id")
.HasConstraintName("FK_dbo.RuleSet_PaymentMethod_Mapping_dbo.PaymentMethod_PaymentMethod_Id")
.OnDelete(DeleteBehavior.Cascade),
c =>
{
c.HasIndex("PaymentMethod_Id");
c.HasKey("PaymentMethod_Id", "RuleSetEntity_Id");
});
}
}
/// <summary>
/// Represents a payment method.
/// </summary>
[CacheableEntity]
[Index(nameof(PaymentMethodSystemName))]
| PaymentMethodMap |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Internal/Either.Generic.cs | {
"start": 301,
"end": 789
} | internal abstract class ____<TLeft, TRight>
{
private Either()
{
}
public static Either<TLeft, TRight> CreateLeft(TLeft value) => new Left(value);
public static Either<TLeft, TRight> CreateRight(TRight value) => new Right(value);
public abstract TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight);
public abstract void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight);
| Either |
csharp | dotnet__maui | src/Controls/src/Core/SwipeView/SwipeEventArgs.cs | {
"start": 759,
"end": 1209
} | public class ____ : EventArgs
{
public OpenRequestedEventArgs(OpenSwipeItem openSwipeItem, bool animated)
{
OpenSwipeItem = openSwipeItem;
Animated = animated;
}
public OpenSwipeItem OpenSwipeItem { get; set; }
public bool Animated { get; set; }
}
/// <include file="../../docs/Microsoft.Maui.Controls/SwipeStartedEventArgs.xml" path="Type[@FullName='Microsoft.Maui.Controls.SwipeStartedEventArgs']/Docs/*" />
| OpenRequestedEventArgs |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Visual.cs | {
"start": 998,
"end": 29641
} | public partial class ____ : StyledElement, IAvaloniaListItemValidator<Visual>
{
internal static int RootedVisualChildrenCount { get; private set; }
/// <summary>
/// Defines the <see cref="Bounds"/> property.
/// </summary>
public static readonly DirectProperty<Visual, Rect> BoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, Rect>(nameof(Bounds), o => o.Bounds);
/// <summary>
/// Defines the <see cref="ClipToBounds"/> property.
/// </summary>
public static readonly StyledProperty<bool> ClipToBoundsProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(ClipToBounds));
/// <summary>
/// Defines the <see cref="Clip"/> property.
/// </summary>
public static readonly StyledProperty<Geometry?> ClipProperty =
AvaloniaProperty.Register<Visual, Geometry?>(nameof(Clip));
/// <summary>
/// Defines the <see cref="IsVisible"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsVisibleProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(IsVisible), true);
/// <summary>
/// Defines the <see cref="Opacity"/> property.
/// </summary>
public static readonly StyledProperty<double> OpacityProperty =
AvaloniaProperty.Register<Visual, double>(nameof(Opacity), 1);
/// <summary>
/// Defines the <see cref="OpacityMask"/> property.
/// </summary>
public static readonly StyledProperty<IBrush?> OpacityMaskProperty =
AvaloniaProperty.Register<Visual, IBrush?>(nameof(OpacityMask));
/// <summary>
/// Defines the <see cref="Effect"/> property.
/// </summary>
public static readonly StyledProperty<IEffect?> EffectProperty =
AvaloniaProperty.Register<Visual, IEffect?>(nameof(Effect));
/// <summary>
/// Defines the <see cref="HasMirrorTransform"/> property.
/// </summary>
public static readonly DirectProperty<Visual, bool> HasMirrorTransformProperty =
AvaloniaProperty.RegisterDirect<Visual, bool>(nameof(HasMirrorTransform), o => o.HasMirrorTransform);
/// <summary>
/// Defines the <see cref="RenderTransform"/> property.
/// </summary>
public static readonly StyledProperty<ITransform?> RenderTransformProperty =
AvaloniaProperty.Register<Visual, ITransform?>(nameof(RenderTransform));
/// <summary>
/// Defines the <see cref="RenderTransformOrigin"/> property.
/// </summary>
public static readonly StyledProperty<RelativePoint> RenderTransformOriginProperty =
AvaloniaProperty.Register<Visual, RelativePoint>(nameof(RenderTransformOrigin), defaultValue: RelativePoint.Center);
/// <summary>
/// Defines the <see cref="FlowDirection"/> property.
/// </summary>
public static readonly AttachedProperty<FlowDirection> FlowDirectionProperty =
AvaloniaProperty.RegisterAttached<Visual, Visual, FlowDirection>(
nameof(FlowDirection),
inherits: true);
/// <summary>
/// Defines the <see cref="VisualParent"/> property.
/// </summary>
public static readonly DirectProperty<Visual, Visual?> VisualParentProperty =
AvaloniaProperty.RegisterDirect<Visual, Visual?>(nameof(VisualParent), o => o._visualParent);
/// <summary>
/// Defines the <see cref="ZIndex"/> property.
/// </summary>
public static readonly StyledProperty<int> ZIndexProperty =
AvaloniaProperty.Register<Visual, int>(nameof(ZIndex));
private static readonly WeakEvent<IAffectsRender, EventArgs> InvalidatedWeakEvent =
WeakEvent.Register<IAffectsRender>(
(s, h) => s.Invalidated += h,
(s, h) => s.Invalidated -= h);
private Rect _bounds;
private IRenderRoot? _visualRoot;
private Visual? _visualParent;
private bool _hasMirrorTransform;
private TargetWeakEventSubscriber<Visual, EventArgs>? _affectsRenderWeakSubscriber;
/// <summary>
/// Initializes static members of the <see cref="Visual"/> class.
/// </summary>
static Visual()
{
AffectsRender<Visual>(
BoundsProperty,
ClipProperty,
ClipToBoundsProperty,
IsVisibleProperty,
OpacityProperty,
OpacityMaskProperty,
EffectProperty,
HasMirrorTransformProperty);
RenderTransformProperty.Changed.Subscribe(RenderTransformChanged);
ZIndexProperty.Changed.Subscribe(ZIndexChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref="Visual"/> class.
/// </summary>
public Visual()
{
_visualRoot = this as IRenderRoot;
// Disable transitions until we're added to the visual tree.
DisableTransitions();
var visualChildren = new AvaloniaList<Visual>();
visualChildren.ResetBehavior = ResetBehavior.Remove;
visualChildren.Validator = this;
visualChildren.CollectionChanged += VisualChildrenChanged;
VisualChildren = visualChildren;
}
/// <summary>
/// Raised when the control is attached to a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs>? AttachedToVisualTree;
/// <summary>
/// Raised when the control is detached from a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs>? DetachedFromVisualTree;
/// <summary>
/// Gets the bounds of the control relative to its parent.
/// </summary>
public Rect Bounds
{
get { return _bounds; }
protected set { SetAndRaise(BoundsProperty, ref _bounds, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control should be clipped to its bounds.
/// </summary>
public bool ClipToBounds
{
get { return GetValue(ClipToBoundsProperty); }
set { SetValue(ClipToBoundsProperty, value); }
}
/// <summary>
/// Gets or sets the geometry clip for this visual.
/// </summary>
public Geometry? Clip
{
get { return GetValue(ClipProperty); }
set { SetValue(ClipProperty, value); }
}
/// <summary>
/// Gets a value indicating whether this control and all its parents are visible.
/// </summary>
public bool IsEffectivelyVisible { get; private set; } = true;
/// <summary>
/// Updates the <see cref="IsEffectivelyVisible"/> property based on the parent's
/// <see cref="IsEffectivelyVisible"/>.
/// </summary>
/// <param name="parentState">The effective visibility of the parent control.</param>
private void UpdateIsEffectivelyVisible(bool parentState)
{
var isEffectivelyVisible = parentState && IsVisible;
if (IsEffectivelyVisible == isEffectivelyVisible)
return;
IsEffectivelyVisible = isEffectivelyVisible;
// PERF-SENSITIVE: This is called on entire hierarchy and using foreach or LINQ
// will cause extra allocations and overhead.
var children = VisualChildren;
// ReSharper disable once ForCanBeConvertedToForeach
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
child.UpdateIsEffectivelyVisible(isEffectivelyVisible);
}
}
/// <summary>
/// Gets or sets a value indicating whether this control is visible.
/// </summary>
public bool IsVisible
{
get { return GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
/// <summary>
/// Gets or sets the opacity of the control.
/// </summary>
public double Opacity
{
get { return GetValue(OpacityProperty); }
set { SetValue(OpacityProperty, value); }
}
/// <summary>
/// Gets or sets the opacity mask of the control.
/// </summary>
public IBrush? OpacityMask
{
get { return GetValue(OpacityMaskProperty); }
set { SetValue(OpacityMaskProperty, value); }
}
/// <summary>
/// Gets or sets the effect of the control.
/// </summary>
public IEffect? Effect
{
get => GetValue(EffectProperty);
set => SetValue(EffectProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether to apply mirror transform on this control.
/// </summary>
public bool HasMirrorTransform
{
get { return _hasMirrorTransform; }
protected set { SetAndRaise(HasMirrorTransformProperty, ref _hasMirrorTransform, value); }
}
/// <summary>
/// Gets or sets the render transform of the control.
/// </summary>
public ITransform? RenderTransform
{
get { return GetValue(RenderTransformProperty); }
set { SetValue(RenderTransformProperty, value); }
}
/// <summary>
/// Gets or sets the transform origin of the control.
/// </summary>
public RelativePoint RenderTransformOrigin
{
get { return GetValue(RenderTransformOriginProperty); }
set { SetValue(RenderTransformOriginProperty, value); }
}
/// <summary>
/// Gets or sets the text flow direction.
/// </summary>
public FlowDirection FlowDirection
{
get => GetValue(FlowDirectionProperty);
set => SetValue(FlowDirectionProperty, value);
}
/// <summary>
/// Gets or sets the Z index of the control.
/// </summary>
/// <remarks>
/// Controls with a higher <see cref="ZIndex"/> will appear in front of controls with
/// a lower ZIndex. If two controls have the same ZIndex then the control that appears
/// later in the containing element's children collection will appear on top.
/// </remarks>
public int ZIndex
{
get { return GetValue(ZIndexProperty); }
set { SetValue(ZIndexProperty, value); }
}
/// <summary>
/// Gets the control's child visuals.
/// </summary>
protected internal IAvaloniaList<Visual> VisualChildren { get; }
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
protected internal IRenderRoot? VisualRoot => _visualRoot;
internal RenderOptions RenderOptions { get; set; }
internal bool HasNonUniformZIndexChildren { get; private set; }
/// <summary>
/// Gets a value indicating whether this control is attached to a visual root.
/// </summary>
internal bool IsAttachedToVisualTree => VisualRoot != null;
/// <summary>
/// Gets the control's parent visual.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("AvaloniaProperty", "AVP1032", Justification = "GetVisualParent extension method is supposed to be used instead.")]
internal Visual? VisualParent => _visualParent;
/// <summary>
/// Gets a value indicating whether control bypass FlowDirecton policies.
/// </summary>
/// <remarks>
/// Related to FlowDirection system and returns false as default, so if
/// <see cref="FlowDirection"/> is RTL then control will get a mirror presentation.
/// For controls that want to avoid this behavior, override this property and return true.
/// </remarks>
protected virtual bool BypassFlowDirectionPolicies => false;
/// <summary>
/// Gets the value of the attached <see cref="FlowDirectionProperty"/> on a control.
/// </summary>
/// <param name="visual">The control.</param>
/// <returns>The flow direction.</returns>
public static FlowDirection GetFlowDirection(Visual visual)
{
return visual.GetValue(FlowDirectionProperty);
}
/// <summary>
/// Sets the value of the attached <see cref="FlowDirectionProperty"/> on a control.
/// </summary>
/// <param name="visual">The control.</param>
/// <param name="value">The property value to set.</param>
public static void SetFlowDirection(Visual visual, FlowDirection value)
{
visual.SetValue(FlowDirectionProperty, value);
}
/// <summary>
/// Invalidates the visual and queues a repaint.
/// </summary>
public void InvalidateVisual()
{
VisualRoot?.Renderer.AddDirty(this);
}
/// <summary>
/// Renders the visual to a <see cref="DrawingContext"/>.
/// </summary>
/// <param name="context">The drawing context.</param>
public virtual void Render(DrawingContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <typeparam name="T">The control which the property affects.</typeparam>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
protected static void AffectsRender<T>(params AvaloniaProperty[] properties)
where T : Visual
{
var invalidateObserver = new AnonymousObserver<AvaloniaPropertyChangedEventArgs>(
static e =>
{
if (e.Sender is T sender)
{
sender.InvalidateVisual();
}
});
var invalidateAndSubscribeObserver = new AnonymousObserver<AvaloniaPropertyChangedEventArgs>(
static e =>
{
if (e.Sender is T sender)
{
if (e.OldValue is IAffectsRender oldValue)
{
if (sender._affectsRenderWeakSubscriber != null)
{
InvalidatedWeakEvent.Unsubscribe(oldValue, sender._affectsRenderWeakSubscriber);
}
}
if (e.NewValue is IAffectsRender newValue)
{
if (sender._affectsRenderWeakSubscriber == null)
{
sender._affectsRenderWeakSubscriber = new TargetWeakEventSubscriber<Visual, EventArgs>(
sender, static (target, _, _, _) =>
{
target.InvalidateVisual();
});
}
InvalidatedWeakEvent.Subscribe(newValue, sender._affectsRenderWeakSubscriber);
}
sender.InvalidateVisual();
}
});
foreach (var property in properties)
{
if (property.CanValueAffectRender())
{
property.Changed.Subscribe(invalidateAndSubscribeObserver);
}
else
{
property.Changed.Subscribe(invalidateObserver);
}
}
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == IsVisibleProperty)
{
UpdateIsEffectivelyVisible(VisualParent?.IsEffectivelyVisible ?? true);
}
else if (change.Property == FlowDirectionProperty)
{
InvalidateMirrorTransform();
foreach (var child in VisualChildren)
{
child.InvalidateMirrorTransform();
}
}
}
protected override void LogicalChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
base.LogicalChildrenCollectionChanged(sender, e);
VisualRoot?.Renderer.RecalculateChildren(this);
}
/// <summary>
/// Calls the <see cref="OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Attached to visual tree");
_visualRoot = e.Root;
RootedVisualChildrenCount++;
if (_visualParent is null)
{
throw new InvalidOperationException("Visual was attached to the root without being added to the visual parent first.");
}
if (RenderTransform is IMutableTransform mutableTransform)
{
mutableTransform.Changed += RenderTransformChanged;
}
EnableTransitions();
if (_visualRoot.Renderer is IRendererWithCompositor compositingRenderer)
{
AttachToCompositor(compositingRenderer.Compositor);
}
InvalidateMirrorTransform();
UpdateIsEffectivelyVisible(_visualParent.IsEffectivelyVisible);
OnAttachedToVisualTree(e);
AttachedToVisualTree?.Invoke(this, e);
InvalidateVisual();
_visualRoot.Renderer.RecalculateChildren(_visualParent);
if (ZIndex != 0)
_visualParent.HasNonUniformZIndexChildren = true;
var visualChildren = VisualChildren;
var visualChildrenCount = visualChildren.Count;
for (var i = 0; i < visualChildrenCount; i++)
{
if (visualChildren[i] is { } child && child._visualRoot != e.Root) // child may already have been attached within an event handler
{
child.OnAttachedToVisualTreeCore(e);
}
}
}
/// <summary>
/// Calls the <see cref="OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Detached from visual tree");
_visualRoot = this as IRenderRoot;
RootedVisualChildrenCount--;
if (RenderTransform is IMutableTransform mutableTransform)
{
mutableTransform.Changed -= RenderTransformChanged;
}
DisableTransitions();
UpdateIsEffectivelyVisible(true);
OnDetachedFromVisualTree(e);
DetachFromCompositor();
DetachedFromVisualTree?.Invoke(this, e);
e.Root.Renderer.AddDirty(this);
var visualChildren = VisualChildren;
var visualChildrenCount = visualChildren.Count;
for (var i = 0; i < visualChildrenCount; i++)
{
if (visualChildren[i] is { } child)
{
child.OnDetachedFromVisualTreeCore(e);
}
}
}
/// <summary>
/// Called when the control is added to a rooted visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control is removed from a rooted visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control's visual parent changes.
/// </summary>
/// <param name="oldParent">The old visual parent.</param>
/// <param name="newParent">The new visual parent.</param>
protected virtual void OnVisualParentChanged(Visual? oldParent, Visual? newParent)
{
RaisePropertyChanged(VisualParentProperty, oldParent, newParent);
}
/// <summary>
/// Called when a visual's <see cref="RenderTransform"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void RenderTransformChanged(AvaloniaPropertyChangedEventArgs<ITransform?> e)
{
var sender = e.Sender as Visual;
if (sender?.VisualRoot != null)
{
var (oldValue, newValue) = e.GetOldAndNewValue<ITransform?>();
if (oldValue is Transform oldTransform)
{
oldTransform.Changed -= sender.RenderTransformChanged;
}
if (newValue is Transform newTransform)
{
newTransform.Changed += sender.RenderTransformChanged;
}
sender.InvalidateVisual();
}
}
/// <summary>
/// Ensures a visual child is not null and not already parented.
/// </summary>
/// <param name="item">The visual child.</param>
void IAvaloniaListItemValidator<Visual>.Validate(Visual item)
{
if (item is null)
{
throw new ArgumentNullException(nameof(item), $"Cannot add null to {nameof(VisualChildren)}.");
}
if (item.VisualParent is { } parent)
{
throw new InvalidOperationException(
$"The control {item.DebugDisplay} already has a visual parent {parent.GetDebugDisplay(false)} " +
$"while trying to add it as a child of {GetDebugDisplay(false)}.");
}
}
/// <summary>
/// Called when the <see cref="ZIndex"/> property changes on any control.
/// </summary>
/// <param name="e">The event args.</param>
private static void ZIndexChanged(AvaloniaPropertyChangedEventArgs e)
{
var sender = e.Sender as Visual;
var parent = sender?.VisualParent;
if (sender?.ZIndex != 0 && parent is Visual parentVisual)
parentVisual.HasNonUniformZIndexChildren = true;
sender?.InvalidateVisual();
parent?.VisualRoot?.Renderer.RecalculateChildren(parent);
}
/// <summary>
/// Called when the <see cref="RenderTransform"/>'s <see cref="Transform.Changed"/> event
/// is fired.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void RenderTransformChanged(object? sender, EventArgs e)
{
InvalidateVisual();
}
/// <summary>
/// Sets the visual parent of the Visual.
/// </summary>
/// <param name="value">The visual parent.</param>
private void SetVisualParent(Visual? value)
{
if (_visualParent == value)
{
return;
}
var old = _visualParent;
_visualParent = value;
if (_visualRoot is not null && old is not null)
{
var e = new VisualTreeAttachmentEventArgs(old, _visualRoot);
OnDetachedFromVisualTreeCore(e);
}
if (_visualParent is IRenderRoot || _visualParent?.IsAttachedToVisualTree == true)
{
var root = this.FindAncestorOfType<IRenderRoot>() ??
throw new AvaloniaInternalException("Visual is atached to visual tree but root could not be found.");
var e = new VisualTreeAttachmentEventArgs(_visualParent, root);
OnAttachedToVisualTreeCore(e);
}
OnVisualParentChanged(old, value);
}
/// <summary>
/// Called when the <see cref="VisualChildren"/> collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void VisualChildrenChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SetVisualParent(e.NewItems!, this);
break;
case NotifyCollectionChangedAction.Remove:
SetVisualParent(e.OldItems!, null);
break;
case NotifyCollectionChangedAction.Replace:
SetVisualParent(e.OldItems!, null);
SetVisualParent(e.NewItems!, this);
break;
}
}
private static void SetVisualParent(IList children, Visual? parent)
{
var count = children.Count;
for (var i = 0; i < count; i++)
{
var visual = (Visual) children[i]!;
visual.SetVisualParent(parent);
}
}
internal override void OnTemplatedParentControlThemeChanged()
{
base.OnTemplatedParentControlThemeChanged();
var count = VisualChildren.Count;
var templatedParent = TemplatedParent;
for (var i = 0; i < count; ++i)
{
if (VisualChildren[i] is StyledElement child &&
child.TemplatedParent == templatedParent)
{
child.OnTemplatedParentControlThemeChanged();
}
}
}
/// <summary>
/// Computes the <see cref="HasMirrorTransform"/> value according to the
/// <see cref="FlowDirection"/> and <see cref="BypassFlowDirectionPolicies"/>
/// </summary>
protected internal virtual void InvalidateMirrorTransform()
{
var flowDirection = this.FlowDirection;
var parentFlowDirection = FlowDirection.LeftToRight;
bool bypassFlowDirectionPolicies = BypassFlowDirectionPolicies;
bool parentBypassFlowDirectionPolicies = false;
var parent = VisualParent;
if (parent != null)
{
parentFlowDirection = parent.FlowDirection;
parentBypassFlowDirectionPolicies = parent.BypassFlowDirectionPolicies;
}
bool thisShouldBeMirrored = flowDirection == FlowDirection.RightToLeft && !bypassFlowDirectionPolicies;
bool parentShouldBeMirrored = parentFlowDirection == FlowDirection.RightToLeft && !parentBypassFlowDirectionPolicies;
bool shouldApplyMirrorTransform = thisShouldBeMirrored != parentShouldBeMirrored;
HasMirrorTransform = shouldApplyMirrorTransform;
}
}
}
| Visual |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Services/Default/KeyManagement/X509KeyContainer.cs | {
"start": 516,
"end": 4664
} | public class ____ : KeyContainer
#pragma warning restore CA1001
{
private const string ServerAuthenticationOid = "1.3.6.1.5.5.7.3.1";
/// <summary>
/// Constructor for X509KeyContainer.
/// </summary>
public X509KeyContainer() => HasX509Certificate = true;
/// <summary>
/// Constructor for X509KeyContainer.
/// </summary>
public X509KeyContainer(RsaSecurityKey key, string algorithm, DateTime created, TimeSpan certAge, string issuer = "OP")
: base(key.KeyId, algorithm, created)
{
HasX509Certificate = true;
var distinguishedName = new X500DistinguishedName($"CN={issuer}");
var request = new CertificateRequest(
distinguishedName, key.Rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid(ServerAuthenticationOid) }, false));
_cert = request.CreateSelfSigned(
new DateTimeOffset(created, TimeSpan.Zero),
new DateTimeOffset(created.Add(certAge), TimeSpan.Zero));
CertificateRawData = Convert.ToBase64String(_cert.Export(X509ContentType.Pfx));
}
/// <summary>
/// Constructor for X509KeyContainer.
/// </summary>
public X509KeyContainer(ECDsaSecurityKey key, string algorithm, DateTime created, TimeSpan certAge, string issuer = "OP")
: base(key.KeyId, algorithm, created)
{
HasX509Certificate = true;
var distinguishedName = new X500DistinguishedName($"CN={issuer}");
//var ec = ECDsa.Create(key.ECDsa.par)
var request = new CertificateRequest(distinguishedName, key.ECDsa, HashAlgorithmName.SHA256);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid(ServerAuthenticationOid) }, false));
_cert = request.CreateSelfSigned(
new DateTimeOffset(created, TimeSpan.Zero),
new DateTimeOffset(created.Add(certAge), TimeSpan.Zero));
CertificateRawData = Convert.ToBase64String(_cert.Export(X509ContentType.Pfx));
}
private X509Certificate2 _cert;
/// <summary>
/// The X509 certificate data.
/// </summary>
public string CertificateRawData { get; set; }
/// <inheritdoc />
public override AsymmetricSecurityKey ToSecurityKey()
{
if (_cert == null)
{
#pragma warning disable SYSLIB0057 // Type or member is obsolete
// TODO - Use X509CertificateLoader in a future release (when we drop NET8 support)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_cert = new X509Certificate2(Convert.FromBase64String(CertificateRawData));
}
// handling this as it typically means the user profile is not loaded, and this is about the best way to detect this.
// when the user profile is not loaded, using X509KeyStorageFlags.MachineKeySet is the only way for this to work on windows.
// https://stackoverflow.com/questions/52750160/what-is-the-rationale-for-all-the-different-x509keystorageflags/52840537#52840537
catch (CryptographicException ex) when (ex.HResult == unchecked((int)0x80070002)) // File not found
{
_cert = new X509Certificate2(Convert.FromBase64String(CertificateRawData), (string)null, X509KeyStorageFlags.MachineKeySet);
}
}
else
{
_cert = new X509Certificate2(Convert.FromBase64String(CertificateRawData));
}
#pragma warning restore SYSLIB0057 // Type or member is obsolete
}
var key = new X509SecurityKey(_cert, Id);
return key;
}
}
| X509KeyContainer |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Server/ApiKeysFeature.cs | {
"start": 13350,
"end": 13528
} | public class ____(ApiKeysFeature feature) : IApiKeyResolver
{
public string? GetApiKeyToken(IRequest req)
{
return feature.GetApiKeyToken(req);
}
}
| ApiKeyResolver |
csharp | reactiveui__ReactiveUI | src/ReactiveUI/Platforms/uikit-common/ReactiveNavigationController.cs | {
"start": 972,
"end": 6042
} | public abstract class ____ : UINavigationController, IReactiveNotifyPropertyChanged<ReactiveNavigationController>, IHandleObservableErrors, IReactiveObject, ICanActivate, IActivatableView
{
private readonly Subject<Unit> _activated = new();
private readonly Subject<Unit> _deactivated = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="rootViewController">The ui view controller.</param>
protected ReactiveNavigationController(UIViewController rootViewController)
: base(rootViewController)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="navigationBarType">The navigation bar type.</param>
/// <param name="toolbarType">The toolbar type.</param>
protected ReactiveNavigationController(Type navigationBarType, Type toolbarType)
: base(navigationBarType, toolbarType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="nibName">The name.</param>
/// <param name="bundle">The bundle.</param>
protected ReactiveNavigationController(string nibName, NSBundle bundle)
: base(nibName, bundle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="handle">The pointer.</param>
protected ReactiveNavigationController(in IntPtr handle)
: base(handle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="t">The object flag.</param>
protected ReactiveNavigationController(NSObjectFlag t)
: base(t)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
/// <param name="coder">The coder.</param>
protected ReactiveNavigationController(NSCoder coder)
: base(coder)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveNavigationController"/> class.
/// </summary>
protected ReactiveNavigationController()
{
}
/// <inheritdoc/>
public event PropertyChangingEventHandler? PropertyChanging;
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveNavigationController>> Changing => this.GetChangingObservable();
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveNavigationController>> Changed => this.GetChangedObservable();
/// <inheritdoc/>
public IObservable<Exception> ThrownExceptions => this.GetThrownExceptionsObservable();
/// <inheritdoc/>
public IObservable<Unit> Activated => _activated.AsObservable();
/// <inheritdoc/>
public IObservable<Unit> Deactivated => _deactivated.AsObservable();
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) => PropertyChanging?.Invoke(this, args);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
/// <summary>
/// When this method is called, an object will not fire change
/// notifications (neither traditional nor Observable notifications)
/// until the return value is disposed.
/// </summary>
/// <returns>An object that, when disposed, reenables change
/// notifications.</returns>
public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this);
/// <inheritdoc/>
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
_activated.OnNext(Unit.Default);
this.ActivateSubviews(true);
}
/// <inheritdoc/>
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
_deactivated.OnNext(Unit.Default);
this.ActivateSubviews(false);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_activated?.Dispose();
_deactivated?.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>
/// This is a UINavigationController that is both an UINavigationController and has ReactiveObject powers
/// (i.e. you can call RaiseAndSetIfChanged).
/// </summary>
/// <typeparam name="TViewModel">The view model type.</typeparam>
[SuppressMessage("Design", "CA1010: Implement generic IEnumerable", Justification = "UI Kit exposes IEnumerable")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same | ReactiveNavigationController |
csharp | dotnet-architecture__eShopOnWeb | tests/FunctionalTests/Web/Pages/Basket/BasketPageCheckout.cs | {
"start": 146,
"end": 1823
} | public class ____ : IClassFixture<TestApplication>
{
public BasketPageCheckout(TestApplication factory)
{
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = true
});
}
public HttpClient Client { get; }
[Fact]
public async Task RedirectsToLoginIfNotAuthenticated()
{
// Load Home Page
var response = await Client.GetAsync("/");
response.EnsureSuccessStatusCode();
var stringResponse1 = await response.Content.ReadAsStringAsync();
string token = WebPageHelpers.GetRequestVerificationToken(stringResponse1);
// Add Item to Cart
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("id", "2"),
new KeyValuePair<string, string>("name", "shirt"),
new KeyValuePair<string, string>("price", "19.49"),
new KeyValuePair<string, string>("__RequestVerificationToken", token)
};
var formContent = new FormUrlEncodedContent(keyValues);
var postResponse = await Client.PostAsync("/basket/index", formContent);
postResponse.EnsureSuccessStatusCode();
var stringResponse = await postResponse.Content.ReadAsStringAsync();
Assert.Contains(".NET Black & White Mug", stringResponse);
keyValues.Clear();
formContent = new FormUrlEncodedContent(keyValues);
var postResponse2 = await Client.PostAsync("/Basket/Checkout", formContent);
Assert.Contains("/Identity/Account/Login", postResponse2!.RequestMessage!.RequestUri!.ToString()!);
}
}
| BasketPageCheckout |
csharp | protobuf-net__protobuf-net | src/Examples/DictionaryTests.cs | {
"start": 8390,
"end": 15760
} | public class ____
{
const string ExpectedHex = "0A-11-0A-03-61-62-63-12-0A-0A-03-64-65-66-12-03-67-68-69";
/*
0A = field 1, type String
11 = length 17
0A = field 1, type String
03 = length 3
61-62-63 = "abc"
12 = field 2, type String
0A = length 10
0A = field 1, type String
03 = length 3
64-65-66 = "def"
12 = field 2, type String
03 = length 3
67-68-69 = "ghi"
etc
*/
private ITestOutputHelper Log { get; }
public NestedDictionaryTests(ITestOutputHelper _log) => Log = _log;
[Fact]
public void TestNestedConcreteConcreteDictionary()
{
Dictionary<string, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>
{
{ "abc", new Dictionary<string,string> {{"def","ghi"}}},
{ "jkl", new Dictionary<string,string> {{"mno","pqr"},{"stu","vwx"}}}
};
CheckNested(data, "original");
// CheckHex(data, ExpectedHex);
var clone = Serializer.DeepClone(data);
CheckNested(clone, "clone");
}
private static void CheckHex<T>(T data, string expected)
{
using var ms = new MemoryStream();
Serializer.Serialize(ms, data);
var hex = BitConverter.ToString(ms.GetBuffer(), 0, (int)ms.Length);
Assert.Equal(expected, hex);
}
[Fact]
public void TestNestedInterfaceInterfaceDictionary()
{
IDictionary<string, IDictionary<string, string>> data = new Dictionary<string, IDictionary<string, string>>
{
{ "abc", new Dictionary<string,string> {{"def","ghi"}}},
{ "jkl", new Dictionary<string,string> {{"mno","pqr"},{"stu","vwx"}}}
};
CheckNested(data, "original");
var clone = Serializer.DeepClone(data);
CheckNested(clone, "clone");
}
[Fact]
public void TestNestedInterfaceConcreteDictionary()
{
IDictionary<string, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>
{
{ "abc", new Dictionary<string,string> {{"def","ghi"}}},
{ "jkl", new Dictionary<string,string> {{"mno","pqr"},{"stu","vwx"}}}
};
CheckNested(data, "original");
var clone = Serializer.DeepClone(data);
CheckNested(clone, "clone");
}
[Fact]
public void TestNestedConcreteInterfaceDictionary()
{
Dictionary<string, IDictionary<string, string>> data = new Dictionary<string, IDictionary<string, string>>
{
{ "abc", new Dictionary<string,string> {{"def","ghi"}}},
{ "jkl", new Dictionary<string,string> {{"mno","pqr"},{"stu","vwx"}}}
};
CheckNested(data, "original");
var clone = Serializer.DeepClone(data);
CheckNested(clone, "clone");
}
#pragma warning disable IDE0060
static void CheckNested<TInner>(IDictionary<string, TInner> data, string message)
#pragma warning restore IDE0060
where TInner : IDictionary<string, string>
{
Assert.NotNull(data); //, message);
Assert.Equal(2, data.Keys.Count); //, message);
var allKeys = string.Join(", ", data.Keys.OrderBy(x => x));
Assert.Equal("abc, jkl", allKeys);
var inner = data["abc"];
Assert.Single(inner.Keys); //, message);
Assert.Equal("ghi", inner["def"]); //, message);
inner = data["jkl"];
Assert.Equal(2, inner.Keys.Count); //, message);
Assert.Equal("pqr", inner["mno"]); //, message);
Assert.Equal("vwx", inner["stu"]); //, message);
}
#if LONG_RUNNING
[Fact]
public void CheckPerformanceNotInsanelyBad()
{
var model = RuntimeTypeModel.Create();
model.Add(typeof (PropsViaDictionaryDefault), true);
model.Add(typeof (PropsViaDictionaryGrouped), true);
model.Add(typeof (PropsViaProperties), true);
model.CompileInPlace();
var o1 = new PropsViaProperties { Field1 = 123, Field2 = 456, Field3 = 789 };
var o2 = new PropsViaDictionaryDefault()
{
Values = new List<KeyValuePair> {
new KeyValuePair {Key = "Field1", Value =123 },
new KeyValuePair {Key = "Field2", Value =456 },
new KeyValuePair {Key = "Field2", Value =789 },
}
};
var o3 = new PropsViaDictionaryGrouped()
{
Values = new List<KeyValuePair> {
new KeyValuePair {Key = "Field1", Value =123 },
new KeyValuePair {Key = "Field2", Value =456 },
new KeyValuePair {Key = "Field2", Value =789 },
}
};
int l1 = BulkTest(model, o1, out int s1, out int d1);
int l2 = BulkTest(model, o2, out int s2, out int d2);
int l3 = BulkTest(model, o3, out int s3, out int d3);
Log.WriteLine("Bytes (props)\t" + l1);
Log.WriteLine("Ser (props)\t" + s1);
Log.WriteLine("Deser (props)\t" + d1);
Log.WriteLine("Bytes (kv-default)\t" + l2);
Log.WriteLine("Ser (kv-default)\t" + s2);
Log.WriteLine("Deser (kv-default)\t" + d2);
Log.WriteLine("Bytes (kv-grouped)\t" + l3);
Log.WriteLine("Ser (kv-grouped)\t" + s3);
Log.WriteLine("Deser (kv-grouped)\t" + d3);
using var state = ProtoWriter.State.Create(Stream.Null, null, null);
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < LOOP; i++ ) {
state.WriteFieldHeader(1, WireType.String);
state.WriteString("Field1");
state.WriteFieldHeader(1, WireType.String);
state.WriteString("Field2");
state.WriteFieldHeader(1, WireType.String);
state.WriteString("Field3");
}
watch.Stop();
state.Close();
Log.WriteLine("Encoding: " + watch.ElapsedMilliseconds);
}
#endif
const int LOOP = 500000;
static int BulkTest<T>(TypeModel model, T obj, out int serialize, out int deserialize) where T: class
{
using MemoryStream ms = new MemoryStream();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < LOOP; i++)
{
ms.Position = 0;
ms.SetLength(0);
model.Serialize(ms, obj);
}
watch.Stop();
serialize = (int)watch.ElapsedMilliseconds;
watch.Reset();
Type type = typeof(T);
watch.Start();
for (int i = 0; i < LOOP; i++)
{
ms.Position = 0;
#pragma warning disable CS0618
model.Deserialize(ms, null, type);
#pragma warning restore CS0618
}
watch.Stop();
deserialize = (int)watch.ElapsedMilliseconds;
return (int)ms.Length;
}
[ProtoContract]
| NestedDictionaryTests |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Events/InvalidIdentityProviderConfiguration.cs | {
"start": 288,
"end": 1314
} | public class ____ : Event
{
/// <summary>
/// Initializes a new instance of the <see cref="InvalidIdentityProviderConfiguration" /> class.
/// </summary>
public InvalidIdentityProviderConfiguration(IdentityProvider idp, string errorMessage)
: base(EventCategories.Error,
"Invalid IdentityProvider Configuration",
EventTypes.Error,
EventIds.InvalidIdentityProviderConfiguration,
errorMessage)
{
Scheme = idp.Scheme;
DisplayName = idp.DisplayName ?? "unknown name";
Type = idp.Type ?? "unknown type";
}
/// <summary>
/// Gets or sets the scheme.
/// </summary>
public string Scheme { get; set; }
/// <summary>
/// Gets or sets the display name of the identity provider.
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the type of the identity provider.
/// </summary>
public string Type { get; set; }
}
| InvalidIdentityProviderConfiguration |
csharp | npgsql__npgsql | src/Npgsql.Json.NET/Internal/JsonNetTypeInfoResolverFactory.cs | {
"start": 158,
"end": 457
} | sealed class ____(JsonSerializerSettings? settings = null) : PgTypeInfoResolverFactory
{
public override IPgTypeInfoResolver CreateResolver() => new Resolver(settings);
public override IPgTypeInfoResolver? CreateArrayResolver() => new ArrayResolver(settings);
| JsonNetTypeInfoResolverFactory |
csharp | microsoft__PowerToys | src/modules/launcher/Plugins/Microsoft.PowerToys.Run.Plugin.Calculator.UnitTest/QueryTests.cs | {
"start": 446,
"end": 11501
} | public class ____
{
private static Mock<Main> _main;
private static Mock<IPublicAPI> _api;
[TestInitialize]
public void Initialize()
{
_api = new Mock<IPublicAPI>();
_api.Setup(api => api.ChangeQuery(It.IsAny<string>(), It.IsAny<bool>())).Verifiable();
_main = new Mock<Main>();
_main.Object.Init(new PluginInitContext() { API = _api.Object });
}
[DataTestMethod]
[DataRow("=pi(9+)", "Expression wrong or incomplete (Did you forget some parentheses?)")]
[DataRow("=pi,", "Expression wrong or incomplete (Did you forget some parentheses?)")]
[DataRow("=log()", "Expression wrong or incomplete (Did you forget some parentheses?)")]
[DataRow("=0xf0x6", "Expression wrong or incomplete (Did you forget some parentheses?)")]
[DataRow("=0xf,0x6", "Expression wrong or incomplete (Did you forget some parentheses?)")]
[DataRow("=2^96", "Result value was either too large or too small for a decimal number")]
[DataRow("=+()", "Calculation result is not a valid number (NaN)")]
[DataRow("=[10,10]", "Unsupported use of square brackets")]
[DataRow("=5/0", "Expression contains division by zero")]
[DataRow("=5 / 0", "Expression contains division by zero")]
[DataRow("10+(8*9)/0+7", "Expression contains division by zero")]
[DataRow("10+(8*9)/0*7", "Expression contains division by zero")]
[DataRow("10+(8*9)/0x00", "Expression contains division by zero")]
[DataRow("10+(8*9)/0b0", "Expression contains division by zero")]
public void ErrorResultOnInvalidKeywordQuery(string typedString, string expectedResult)
{
Query expectedQuery = new(typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).FirstOrDefault().SubTitle;
// Assert
Assert.AreEqual(expectedResult, result);
}
[DataTestMethod]
[DataRow("pi(9+)")]
[DataRow("pi,")]
[DataRow("log()")]
[DataRow("0xf0x6")]
[DataRow("0xf,0x6")]
[DataRow("2^96")]
[DataRow("+()")]
[DataRow("[10,10]")]
[DataRow("5/0")]
[DataRow("5 / 0")]
[DataRow("10+(8*9)/0+7")]
[DataRow("10+(8*9)/0*7")]
public void NoResultOnInvalidGlobalQuery(string typedString)
{
// Setup
Query expectedQuery = new(typedString);
// Act
var result = _main.Object.Query(expectedQuery).Count;
// Assert
Assert.AreEqual(result, 0);
}
[DataTestMethod]
[DataRow("9+")]
[DataRow("9-")]
[DataRow("9*")]
[DataRow("9|")]
[DataRow("9\\")]
[DataRow("9^")]
[DataRow("9=")]
[DataRow("9&")]
[DataRow("9/")]
[DataRow("9%")]
public void NoResultIfQueryEndsWithBinaryOperator(string typedString)
{
// Setup
Query expectedQuery = new(typedString);
Query expectedQueryWithKeyword = new("=" + typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).Count;
var resultWithKeyword = _main.Object.Query(expectedQueryWithKeyword).Count;
// Assert
Assert.AreEqual(result, 0);
Assert.AreEqual(resultWithKeyword, 0);
}
[DataTestMethod]
[DataRow("10+(8*9)/0,5")] // German decimal digit separator
[DataRow("10+(8*9)/0.5")]
[DataRow("10+(8*9)/1,5")] // German decimal digit separator
[DataRow("10+(8*9)/1.5")]
public void NoErrorForDivisionByNumberWithDecimalDigits(string typedString)
{
// Setup
Query expectedQuery = new(typedString);
Query expectedQueryWithKeyword = new("=" + typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).FirstOrDefault().SubTitle;
var resultWithKeyword = _main.Object.Query(expectedQueryWithKeyword).FirstOrDefault().SubTitle;
// Assert
Assert.AreEqual(result, "Copy this number to the clipboard");
Assert.AreEqual(resultWithKeyword, "Copy this number to the clipboard");
}
[DataTestMethod]
[DataRow("pie", "pi * e")]
[DataRow("eln(100)", "e * ln(100)")]
[DataRow("pi(1+1)", "pi * (1+1)")]
[DataRow("2pi", "2 * pi")]
[DataRow("2log10(100)", "2 * log10(100)")]
[DataRow("2(3+4)", "2 * (3+4)")]
[DataRow("sin(pi)cos(pi)", "sin(pi) * cos(pi)")]
[DataRow("log10(100)(2+3)", "log10(100) * (2+3)")]
[DataRow("(1+1)cos(pi)", "(1+1) * cos(pi)")]
[DataRow("(1+1)(2+2)", "(1+1) * (2+2)")]
[DataRow("2(1+1)", "2 * (1+1)")]
[DataRow("pi(1+1)", "pi * (1+1)")]
[DataRow("pilog(100)", "pi * log(100)")]
[DataRow("3log(100)", "3 * log(100)")]
[DataRow("2e", "2 * e")]
[DataRow("(1+1)(3+2)", "(1+1) * (3+2)")]
[DataRow("(1+1)cos(pi)", "(1+1) * cos(pi)")]
[DataRow("sin(pi)cos(pi)", "sin(pi) * cos(pi)")]
[DataRow("2 (1+1)", "2 * (1+1)")]
[DataRow("pi (1+1)", "pi * (1+1)")]
[DataRow("pi log(100)", "pi * log(100)")]
[DataRow("3 log(100)", "3 * log(100)")]
[DataRow("2 e", "2 * e")]
[DataRow("(1+1) (3+2)", "(1+1) * (3+2)")]
[DataRow("(1+1) cos(pi)", "(1+1) * cos(pi)")]
[DataRow("sin (pi) cos(pi)", "sin (pi) * cos(pi)")]
[DataRow("2picos(pi)(1+1)", "2 * pi * cos(pi) * (1+1)")]
[DataRow("pilog(100)log(1000)", "pi * log(100) * log(1000)")]
[DataRow("pipipie", "pi * pi * pi * e")]
[DataRow("(1+1)(3+2)(1+1)(1+1)", "(1+1) * (3+2) * (1+1) * (1+1)")]
[DataRow("(1+1) (3+2) (1+1)(1+1)", "(1+1) * (3+2) * (1+1) * (1+1)")]
[DataRow("1.0E2", "(1.0 * 10^(2))")]
[DataRow("-1.0E-2", "(-1.0 * 10^(-2))")]
[DataRow("1.2E2", "(1.2 * 10^(2))")]
[DataRow("5/1.0E2", "5/(1.0 * 10^(2))")]
[DataRow("0.1E2", "(0.1 * 10^(2))")]
[DataRow(".1E2", "(.1 * 10^(2))")]
[DataRow(".1E2", "(.1 * 10^(2))")]
[DataRow("5/5E3", "5/(5 * 10^(3))")]
[DataRow("1.E2", "(1. * 10^(2))")]
public void RightHumanMultiplicationExpressionTransformation(string typedString, string expectedQuery)
{
// Setup
// Act
var result = CalculateHelper.FixHumanMultiplicationExpressions(typedString);
// Assert
Assert.AreEqual(expectedQuery, result);
}
[DataTestMethod]
[DataRow("2(1+1)")]
[DataRow("pi(1+1)")]
[DataRow("pilog(100)")]
[DataRow("3log(100)")]
[DataRow("2e")]
[DataRow("(1+1)(3+2)")]
[DataRow("(1+1)cos(pi)")]
[DataRow("sin(pi)cos(pi)")]
[DataRow("2 (1+1)")]
[DataRow("pi (1+1)")]
[DataRow("pi log(100)")]
[DataRow("3 log(100)")]
[DataRow("2 e")]
[DataRow("(1+1) (3+2)")]
[DataRow("(1+1) cos(pi)")]
[DataRow("sin (pi) cos(pi)")]
[DataRow("2picos(pi)(1+1)")]
[DataRow("pilog(100)log(1000)")]
[DataRow("pipipie")]
[DataRow("(1+1)(3+2)(1+1)(1+1)")]
[DataRow("(1+1) (3+2) (1+1)(1+1)")]
public void NoErrorForHumanMultiplicationExpressions(string typedString)
{
// Setup
Query expectedQuery = new(typedString);
Query expectedQueryWithKeyword = new("=" + typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).FirstOrDefault()?.SubTitle;
var resultWithKeyword = _main.Object.Query(expectedQueryWithKeyword).FirstOrDefault()?.SubTitle;
// Assert
Assert.AreEqual("Copy this number to the clipboard", result);
Assert.AreEqual("Copy this number to the clipboard", resultWithKeyword);
}
[DataTestMethod]
[DataRow("2(1+1)", 4)]
[DataRow("pi(1+1)", 6.2831853072)]
[DataRow("pilog(100)", 6.2831853072)]
[DataRow("3log(100)", 6)]
[DataRow("2e", 5.4365636569)]
[DataRow("2E2", 200)]
[DataRow("2E-2", 0.02)]
[DataRow("1.2E2", 120)]
[DataRow("1.2E-1", 0.12)]
[DataRow("5/5E3", 0.001)]
[DataRow("-5/5E3", -0.001)]
[DataRow("(1+1)(3+2)", 10)]
[DataRow("(1+1)cos(pi)", -2)]
[DataRow("log(100)cos(pi)", -2)]
public void RightAnswerForHumanMultiplicationExpressions(string typedString, double answer)
{
// Setup
typedString = typedString.Replace(".", CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); // Workaround to get correct results when the tests are running on a non-english systems.
Query expectedQuery = new(typedString);
Query expectedQueryWithKeyword = new("=" + typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).FirstOrDefault()?.Title;
var resultWithKeyword = _main.Object.Query(expectedQueryWithKeyword).FirstOrDefault()?.Title;
// Assert
Assert.AreEqual(answer.ToString(CultureInfo.CurrentCulture), result);
Assert.AreEqual(answer.ToString(CultureInfo.CurrentCulture), resultWithKeyword);
}
[DataTestMethod]
[DataRow("0x1234+0x1234", 9320)]
[DataRow("0x1234-0x1234", 0)]
[DataRow("0x12345678+0x12345678", 610839792)]
[DataRow("0xf4572220-0xf4572410", -496)]
public void RightAnswerForLargeHexadecimalNumbers(string typedString, double answer)
{
// Setup
Query expectedQuery = new(typedString);
Query expectedQueryWithKeyword = new("=" + typedString, "=");
// Act
var result = _main.Object.Query(expectedQuery).FirstOrDefault()?.Title;
var resultWithKeyword = _main.Object.Query(expectedQueryWithKeyword).FirstOrDefault()?.Title;
// Assert
Assert.AreEqual(answer.ToString(CultureInfo.CurrentCulture), result);
Assert.AreEqual(answer.ToString(CultureInfo.CurrentCulture), resultWithKeyword);
}
[DataTestMethod]
[DataRow("#", "#1+1=", true)]
[DataRow("#", "#1+1", false)]
[DataRow("#", "#1/0=", false)]
[DataRow("", "1+1=", false)]
public void HandleInputReplace(string actionKeyword, string query, bool shouldChangeQuery)
{
// Setup
Query expectedQuery = new(query, actionKeyword);
_main.Object.UpdateSettings(new PowerLauncherPluginSettings()); // Default settings
// Act
_main.Object.Query(expectedQuery);
// Assert
_api.Verify(api => api.ChangeQuery(It.IsAny<string>(), It.IsAny<bool>()), shouldChangeQuery ? Times.Once : Times.Never);
}
}
}
| QueryTests |
csharp | nuke-build__nuke | source/Nuke.Build/CICD/InvokeBuildServerConfigurationGenerationAttribute.cs | {
"start": 389,
"end": 2359
} | public class ____
: BuildServerConfigurationGenerationAttributeBase, IOnBuildCreated
{
public void OnBuildCreated(IReadOnlyCollection<ExecutableTarget> executableTargets)
{
if (Build.IsServerBuild || Build.IsInterceptorExecution)
return;
var hasConfigurationChanged = GetGenerators(Build)
.Where(x => x.AutoGenerate)
.AsParallel()
.Select(HasConfigurationChanged).ToList();
if (hasConfigurationChanged.All(x => !x))
return;
if (Build.Help)
return;
if (Console.IsInputRedirected)
return;
Host.Information("Press any key to continue ...");
Console.ReadKey();
}
private bool HasConfigurationChanged(IConfigurationGenerator generator)
{
var generatedFiles = generator.GeneratedFiles.ToList();
generatedFiles.ForEach(x => x.Parent.CreateDirectory());
var previousHashes = generatedFiles
.WhereFileExists()
.ToDictionary(x => x, x => x.GetFileHash());
ProcessTasks.StartProcess(
Build.BuildAssemblyFile,
$"--{ConfigurationParameterName} {generator.Id} --host {generator.HostName}",
logInvocation: false,
logOutput: false)
.AssertZeroExitCode();
var changedFiles = generatedFiles
.Where(x => x.GetFileHash() != previousHashes.GetValueOrDefault(x))
.Select(x => Build.RootDirectory.GetRelativePathTo(x)).ToList();
if (changedFiles.Count == 0)
return false;
Telemetry.ConfigurationGenerated(generator.HostType, generator.Id, Build);
// TODO: multi-line logging
Log.Warning("Configuration files for {Configuration} have changed.", generator.DisplayName);
changedFiles.ForEach(x => Log.Verbose("Updated {File}", x));
return true;
}
}
| InvokeBuildServerConfigurationGenerationAttribute |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Api.Analyzers/test/TestFiles/AddResponseTypeAttributeCodeFixProviderIntegrationTest/CodeFixAddsFullyQualifiedProducesResponseType.Output.cs | {
"start": 273,
"end": 366
} | public class ____ : ControllerBase
{
}
}
namespace TestApp._OUTPUT_
{
| BaseController |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Services/Storage/WriteEventsToIndexScenario.cs | {
"start": 760,
"end": 6716
} | public abstract class ____<TLogFormat, TStreamId> : SpecificationWithDirectoryPerTestFixture {
protected SynchronousScheduler _publisher;
protected ITransactionFileReader _tfReader;
protected ITableIndex<TStreamId> _tableIndex;
protected IIndexBackend<TStreamId> _indexBackend;
protected IValueLookup<TStreamId> _streamIds;
protected INameLookup<TStreamId> _streamNames;
protected ISystemStreamLookup<TStreamId> _systemStreams;
protected IStreamNamesProvider<TStreamId> _provider;
protected IValidator<TStreamId> _validator;
protected ISizer<TStreamId> _sizer;
protected IIndexReader<TStreamId> _indexReader;
protected IIndexWriter<TStreamId> _indexWriter;
protected IIndexCommitter<TStreamId> _indexCommitter;
protected ObjectPool<ITransactionFileReader> _readerPool;
protected LogFormatAbstractor<TStreamId> _logFormat;
protected const int RecordOffset = 1000;
public IReadOnlyList<IPrepareLogRecord<TStreamId>> CreatePrepareLogRecord(TStreamId streamId, int expectedVersion, TStreamId eventType, Guid eventId, long transactionPosition) {
return new[]{
PrepareLogRecord.SingleWrite (
_logFormat.RecordFactory,
transactionPosition,
Guid.NewGuid(),
eventId,
streamId,
expectedVersion,
eventType,
new byte[0],
new byte[0],
DateTime.Now,
PrepareFlags.IsCommitted
)
};
}
public IReadOnlyList<IPrepareLogRecord<TStreamId>> CreatePrepareLogRecords(TStreamId streamId, int expectedVersion, IList<TStreamId> eventTypes, IList<Guid> eventIds, long transactionPosition) {
if (eventIds.Count != eventTypes.Count)
throw new Exception("eventType and eventIds length mismatch!");
if (eventIds.Count == 0)
throw new Exception("eventIds is empty");
if (eventIds.Count == 1)
return CreatePrepareLogRecord(streamId, expectedVersion, eventTypes[0], eventIds[0], transactionPosition);
var numEvents = eventTypes.Count;
var recordFactory = LogFormatHelper<TLogFormat, TStreamId>.RecordFactory;
var prepares = new List<IPrepareLogRecord<TStreamId>>();
for (var i = 0; i < numEvents; i++) {
PrepareFlags flags = PrepareFlags.Data | PrepareFlags.IsCommitted;
if (i == 0)
flags |= PrepareFlags.TransactionBegin;
if (i == numEvents - 1)
flags |= PrepareFlags.TransactionEnd;
prepares.Add(
PrepareLogRecord.Prepare(
recordFactory,
transactionPosition + RecordOffset * i,
Guid.NewGuid(),
eventIds[i],
transactionPosition,
i,
streamId,
expectedVersion + i,
flags,
eventTypes[i],
new byte[0],
new byte[0],
DateTime.Now
));
}
return prepares;
}
public CommitLogRecord CreateCommitLogRecord(long logPosition, long transactionPosition, long firstEventNumber) {
return new CommitLogRecord(logPosition, Guid.NewGuid(), transactionPosition, DateTime.Now, 0);
}
public void WriteToDB(IEnumerable<IPrepareLogRecord<TStreamId>> prepares) {
foreach (var prepare in prepares) {
((FakeInMemoryTfReader)_tfReader).AddRecord(prepare, prepare.LogPosition);
}
}
public void WriteToDB(CommitLogRecord commit) {
((FakeInMemoryTfReader)_tfReader).AddRecord(commit, commit.LogPosition);
}
public void PreCommitToIndex(IEnumerable<IPrepareLogRecord<TStreamId>> prepares) {
var preparesArray = prepares.ToArray();
_indexWriter.PreCommit(
committedPrepares: preparesArray,
eventStreamIndexes: null);
}
public ValueTask PreCommitToIndex(CommitLogRecord commitLogRecord, CancellationToken token) {
return _indexWriter.PreCommit(commitLogRecord, token);
}
public async ValueTask CommitToIndex(IReadOnlyList<IPrepareLogRecord<TStreamId>> prepares, CancellationToken token) {
await _indexCommitter.Commit(
prepares,
numStreams: 1,
eventStreamIndexes: null,
isTfEof: false,
cacheLastEventNumber: false,
token);
}
public async ValueTask CommitToIndex(CommitLogRecord commitLogRecord, CancellationToken token) {
await _indexCommitter.Commit(commitLogRecord, false, false, token);
}
public abstract ValueTask WriteEvents(CancellationToken token);
public override async Task TestFixtureSetUp() {
await base.TestFixtureSetUp();
_logFormat = LogFormatHelper<TLogFormat, TStreamId>.LogFormatFactory.Create(new() {
IndexDirectory = GetFilePathFor("index"),
});
_provider = _logFormat.StreamNamesProvider;
_publisher = new("publisher");
_tfReader = new FakeInMemoryTfReader(RecordOffset);
_tableIndex = new FakeInMemoryTableIndex<TStreamId>();
_provider.SetTableIndex(_tableIndex);
_indexBackend = new IndexBackend<TStreamId>(_tfReader,
new LRUCache<TStreamId, IndexBackend<TStreamId>.EventNumberCached>("LastEventNumber", 100_000),
new LRUCache<TStreamId, IndexBackend<TStreamId>.MetadataCached>("StreamMetadata", 100_000));
_streamIds = _logFormat.StreamIds;
_validator = _logFormat.StreamIdValidator;
var emptyStreamId = _logFormat.EmptyStreamId;
_sizer = _logFormat.StreamIdSizer;
_indexReader = new IndexReader<TStreamId>(_indexBackend, _tableIndex, _provider, _validator,
_logFormat.StreamExistenceFilterReader, new StreamMetadata(maxCount: 100000), 100, false);
_streamNames = _logFormat.StreamNames;
_systemStreams = _logFormat.SystemStreams;
_indexWriter = new IndexWriter<TStreamId>(_indexBackend, _indexReader, _streamIds, _streamNames,
_systemStreams, emptyStreamId, _sizer);
_indexCommitter = new IndexCommitter<TStreamId>(_publisher, _indexBackend, _indexReader, _tableIndex,
_logFormat.StreamNameIndexConfirmer, _streamNames, _logFormat.EventTypeIndexConfirmer, _logFormat.EventTypes,
_systemStreams, _logFormat.StreamExistenceFilter, _logFormat.StreamExistenceFilterInitializer, new InMemoryCheckpoint(-1), new IndexStatusTracker.NoOp(), new IndexTracker.NoOp(), false);
await WriteEvents(CancellationToken.None);
}
public override Task TestFixtureTearDown() {
_logFormat?.Dispose();
_readerPool.Dispose();
return base.TestFixtureTearDown();
}
}
| WriteEventsToIndexScenario |
csharp | dotnet__aspnetcore | src/Components/Endpoints/test/Binding/FormDataMetadataFactoryTests.cs | {
"start": 28926,
"end": 29032
} | public class ____
{
public string Name { get; set; }
public Address Address { get; set; }
}
| Warehouse |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/PodV1.cs | {
"start": 812,
"end": 1232
} | public sealed class ____() : BaseKubernetesResource("v1", "Pod")
{
/// <summary>
/// Represents the specification for the Kubernetes Pod resource.
/// Contains detailed configuration for the behavior and lifecycle management
/// of the Kubernetes Pod. This property is of type <see cref="PodSpecV1"/>.
/// </summary>
[YamlMember(Alias = "spec")]
public PodSpecV1 Spec { get; set; } = new();
}
| Pod |
csharp | dotnet__extensions | test/Libraries/Microsoft.Extensions.AI.OpenAI.Tests/OpenAIEmbeddingGeneratorTests.cs | {
"start": 511,
"end": 44871
} | public class ____
{
[Fact]
public void AsIEmbeddingGenerator_InvalidArgs_Throws()
{
Assert.Throws<ArgumentNullException>("embeddingClient", () => ((EmbeddingClient)null!).AsIEmbeddingGenerator());
}
[Fact]
public void AsIEmbeddingGenerator_OpenAIClient_ProducesExpectedMetadata()
{
Uri endpoint = new("http://localhost/some/endpoint");
string model = "amazingModel";
var client = new OpenAIClient(new ApiKeyCredential("key"), new OpenAIClientOptions { Endpoint = endpoint });
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = client.GetEmbeddingClient(model).AsIEmbeddingGenerator();
var metadata = embeddingGenerator.GetService<EmbeddingGeneratorMetadata>();
Assert.Equal("openai", metadata?.ProviderName);
Assert.Equal(endpoint, metadata?.ProviderUri);
Assert.Equal(model, metadata?.DefaultModelId);
embeddingGenerator = client.GetEmbeddingClient(model).AsIEmbeddingGenerator();
Assert.Equal("openai", metadata?.ProviderName);
Assert.Equal(endpoint, metadata?.ProviderUri);
Assert.Equal(model, metadata?.DefaultModelId);
}
[Fact]
public void GetService_OpenAIClient_SuccessfullyReturnsUnderlyingClient()
{
EmbeddingClient openAIClient = new OpenAIClient(new ApiKeyCredential("key")).GetEmbeddingClient("model");
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = openAIClient.AsIEmbeddingGenerator();
Assert.Same(embeddingGenerator, embeddingGenerator.GetService<IEmbeddingGenerator<string, Embedding<float>>>());
Assert.Same(openAIClient, embeddingGenerator.GetService<EmbeddingClient>());
Assert.NotNull(embeddingGenerator.GetService<EmbeddingClient>());
using IEmbeddingGenerator<string, Embedding<float>> pipeline = embeddingGenerator
.AsBuilder()
.UseOpenTelemetry()
.UseDistributedCache(new MemoryDistributedCache(Options.Options.Create(new MemoryDistributedCacheOptions())))
.Build();
Assert.NotNull(pipeline.GetService<DistributedCachingEmbeddingGenerator<string, Embedding<float>>>());
Assert.NotNull(pipeline.GetService<CachingEmbeddingGenerator<string, Embedding<float>>>());
Assert.NotNull(pipeline.GetService<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>());
Assert.Same(openAIClient, pipeline.GetService<EmbeddingClient>());
Assert.IsType<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>(pipeline.GetService<IEmbeddingGenerator<string, Embedding<float>>>());
}
[Fact]
public void GetService_EmbeddingClient_SuccessfullyReturnsUnderlyingClient()
{
EmbeddingClient openAIClient = new OpenAIClient(new ApiKeyCredential("key")).GetEmbeddingClient("model");
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = openAIClient.AsIEmbeddingGenerator();
Assert.Same(embeddingGenerator, embeddingGenerator.GetService<IEmbeddingGenerator<string, Embedding<float>>>());
Assert.Same(openAIClient, embeddingGenerator.GetService<EmbeddingClient>());
using IEmbeddingGenerator<string, Embedding<float>> pipeline = embeddingGenerator
.AsBuilder()
.UseOpenTelemetry()
.UseDistributedCache(new MemoryDistributedCache(Options.Options.Create(new MemoryDistributedCacheOptions())))
.Build();
Assert.NotNull(pipeline.GetService<DistributedCachingEmbeddingGenerator<string, Embedding<float>>>());
Assert.NotNull(pipeline.GetService<CachingEmbeddingGenerator<string, Embedding<float>>>());
Assert.NotNull(pipeline.GetService<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>());
Assert.Same(openAIClient, pipeline.GetService<EmbeddingClient>());
Assert.IsType<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>(pipeline.GetService<IEmbeddingGenerator<string, Embedding<float>>>());
}
[Fact]
public async Task GetEmbeddingsAsync_ExpectedRequestResponse()
{
const string Input = """
{"input":["hello, world!","red, white, blue"],"model":"text-embedding-3-small","encoding_format":"base64"}
""";
const string Output = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": "qjH+vMcj07wP1+U7kbwjOv4cwLyL3iy9DkgpvCkBQD0bthW98o6SvMMwmTrQRQa9r7b1uy4tuLzssJs7jZspPe0JG70KJy89ae4fPNLUwjytoHk9BX/1OlXCfTzc07M8JAMIPU7cibsUJiC8pTNGPWUbJztfwW69oNwOPQIQ+rwm60M7oAfOvDMAsTxb+fM77WIaPIverDqcu5S84f+rvFyr8rxqoB686/4cPVnj9ztLHw29mJqaPAhH8Lz/db86qga/PGhnYD1WST28YgWru1AdRTz/db899PIPPBzBE720ie47ujymPbh/Kb0scLs8V1Q7PGIFqzwVMR48xp+UOhNGYTxfwW67CaDvvOeEI7tgc228uQNoPXrLBztd2TI9HRqTvLuVJbytoPm8YVMsOvi6irzwe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DozzEKrk7KnZRvG8pbjsdYI+7yky6OfWAVzzjYGk7NX3DOzrNhDyeIaI8joTZvFcMOryYRba8G7iuu893QDw9RyW7za6FvDUJ7rva6YK9D7rBPD1o/zxCLJa65TaKvHsGAT2g6ly8+tCYu+wqy7xeAHu8vZ1nPBv+QzwfVwo8CMYAvM+91TzKTDq8Ueo4u2uvzTsBf8Q8p+uDvKofDz12tj+8wP+yOlkDtTwYyji6ZdPhPGv14rwqdtE8YPf1vLIKy7yFLs28ouFXvO1PBj15pDU83xQJPdfWUTz8x5O64kgUPBQKA72eIaK6A3a/OyzYnLoYnPg4XMNqPdxsqLsKSaY7pfSIvBoshLupKJS8G0TZOu/SqzzFcE47cvaJPA19Mb14dQC8sVllvJmwhjycBey8cvaJOmSWUbvRtFC8WtX0O2r+57twIGm8yeFpvFuG2rzCyO08PUelPK5rbzouFS29uCxMPQAUdDqtma88wqeTu5gge7zH8/O7l067PJdOO7uKxCO8/xx5vKt9+TztTwa8OhOaO+Q/Dzw33w49CZhAvSubjDydttG8IdovPIADR7stHrI7ATmvvOAs3rzL2OQ69K4XvNccZ7zlV2S8c+0EPfNDxzydKqc6LLPhO8YhtDyJhxM9H1eKOaNMKLtOcBg9HPU+PTsrbzvT0Ia8BG26PB2mpDp7TJa8wP8yPVvM77t0ea86eTBgvFurFT1C/tW7CkkmvKOSPT2aPDG9lGDFPAhSq7u5UYc8l5TQPFh3ijz9vg68lGBFO4/vKTxViZS7eQ8GPTNAs7xmsoe8o0yoPJfaZbwlvyA8IazvO0XsS717TJY8flvmOgHFWbyWnVW8mdFgvJbCkDynDF68"
}
],
"model": "text-embedding-3-small",
"usage": {
"prompt_tokens": 9,
"total_tokens": 9
}
}
""";
using VerbatimHttpHandler handler = new(Input, Output);
using HttpClient httpClient = new(handler);
using IEmbeddingGenerator<string, Embedding<float>> generator = CreateEmbeddingGenerator(httpClient, "text-embedding-3-small");
var response = await generator.GenerateAsync([
"hello, world!",
"red, white, blue",
]);
Assert.NotNull(response);
Assert.Equal(2, response.Count);
Assert.NotNull(response.Usage);
Assert.Equal(9, response.Usage.InputTokenCount);
Assert.Equal(9, response.Usage.TotalTokenCount);
foreach (Embedding<float> e in response)
{
Assert.Equal("text-embedding-3-small", e.ModelId);
Assert.NotNull(e.CreatedAt);
Assert.Equal(1536, e.Vector.Length);
Assert.Contains(e.Vector.ToArray(), f => !f.Equals(0));
}
}
[Fact]
public async Task EmbeddingGenerationOptions_DoNotOverwrite_NotNullPropertiesInRawRepresentation()
{
const string Input = """
{
"input":["hello, world!","red, white, blue"],
"dimensions":1536,
"model":"text-embedding-3-small",
"encoding_format":"base64",
"user":"MyEndUserID"
}
""";
const string Output = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": "qjH+vMcj07wP1+U7kbwjOv4cwLyL3iy9DkgpvCkBQD0bthW98o6SvMMwmTrQRQa9r7b1uy4tuLzssJs7jZspPe0JG70KJy89ae4fPNLUwjytoHk9BX/1OlXCfTzc07M8JAMIPU7cibsUJiC8pTNGPWUbJztfwW69oNwOPQIQ+rwm60M7oAfOvDMAsTxb+fM77WIaPIverDqcu5S84f+rvFyr8rxqoB686/4cPVnj9ztLHw29mJqaPAhH8Lz/db86qga/PGhnYD1WST28YgWru1AdRTz/db899PIPPBzBE720ie47ujymPbh/Kb0scLs8V1Q7PGIFqzwVMR48xp+UOhNGYTxfwW67CaDvvOeEI7tgc228uQNoPXrLBztd2TI9HRqTvLuVJbytoPm8YVMsOvi6irzweJY7/WpBvI5NKL040ym95ccmPAfj8rxJCZG9bsGYvJkpVzszp7G8wOxcu6/ZN7xXrTo7Q90YvGTtZjz/SgA8RWxVPL/hXjynl8O8ZzGjvHK0Uj0dRVI954QjvaqKfTxmUeS8Abf6O0RhV7tr+R098rnRPAju8DtoiiK95SCmvGV0pjwQMOW9wJPdPPutxDxYivi8NLKvPI3pKj3UDYE9Fg5cvQsyrTz+HEC9uuMmPMEaHbzJ4E8778YXvVDERb2cFBS9tsIsPLU7bT3+R/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Bj15pDU83xQJPdfWUTz8x5O64kgUPBQKA72eIaK6A3a/OyzYnLoYnPg4XMNqPdxsqLsKSaY7pfSIvBoshLupKJS8G0TZOu/SqzzFcE47cvaJPA19Mb14dQC8sVllvJmwhjycBey8cvaJOmSWUbvRtFC8WtX0O2r+57twIGm8yeFpvFuG2rzCyO08PUelPK5rbzouFS29uCxMPQAUdDqtma88wqeTu5gge7zH8/O7l067PJdOO7uKxCO8/xx5vKt9+TztTwa8OhOaO+Q/Dzw33w49CZhAvSubjDydttG8IdovPIADR7stHrI7ATmvvOAs3rzL2OQ69K4XvNccZ7zlV2S8c+0EPfNDxzydKqc6LLPhO8YhtDyJhxM9H1eKOaNMKLtOcBg9HPU+PTsrbzvT0Ia8BG26PB2mpDp7TJa8wP8yPVvM77t0ea86eTBgvFurFT1C/tW7CkkmvKOSPT2aPDG9lGDFPAhSq7u5UYc8l5TQPFh3ijz9vg68lGBFO4/vKTxViZS7eQ8GPTNAs7xmsoe8o0yoPJfaZbwlvyA8IazvO0XsS717TJY8flvmOgHFWbyWnVW8mdFgvJbCkDynDF68"
}
],
"model": "text-embedding-3-small",
"usage": {
"prompt_tokens": 9,
"total_tokens": 9
}
}
""";
using VerbatimHttpHandler handler = new(Input, Output);
using HttpClient httpClient = new(handler);
using IEmbeddingGenerator<string, Embedding<float>> generator = CreateEmbeddingGenerator(httpClient, "text-embedding-3-small");
var response = await generator.GenerateAsync([
"hello, world!",
"red, white, blue",
], new EmbeddingGenerationOptions
{
Dimensions = 3072,
RawRepresentationFactory = (e) => new OpenAI.Embeddings.EmbeddingGenerationOptions
{
Dimensions = 1536,
EndUserId = "MyEndUserID"
}
});
Assert.NotNull(response);
Assert.Equal(2, response.Count);
Assert.NotNull(response.Usage);
Assert.Equal(9, response.Usage.InputTokenCount);
Assert.Equal(9, response.Usage.TotalTokenCount);
foreach (Embedding<float> e in response)
{
Assert.Equal("text-embedding-3-small", e.ModelId);
Assert.NotNull(e.CreatedAt);
Assert.Equal(1536, e.Vector.Length);
Assert.Contains(e.Vector.ToArray(), f => !f.Equals(0));
}
}
[Fact]
public async Task EmbeddingGenerationOptions_MissingUsage_Ignored()
{
const string Input = """
{
"input":["hello, world!"],
"model":"text-embedding-3-small",
"encoding_format":"base64"
}
""";
const string Output = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": "AAAAAA=="
}
],
"model": "text-embedding-3-small"
}
""";
using VerbatimHttpHandler handler = new(Input, Output);
using HttpClient httpClient = new(handler);
using IEmbeddingGenerator<string, Embedding<float>> generator = CreateEmbeddingGenerator(httpClient, "text-embedding-3-small");
var response = await generator.GenerateAsync(["hello, world!"]);
Assert.NotNull(response);
Assert.Single(response);
Assert.Null(response.Usage);
foreach (Embedding<float> e in response)
{
Assert.Equal("text-embedding-3-small", e.ModelId);
Assert.NotNull(e.CreatedAt);
Assert.Equal(1, e.Vector.Length);
}
}
[Fact]
public async Task EmbeddingGenerationOptions_NullUsage_Ignored()
{
const string Input = """
{
"input":["hello, world!"],
"model":"text-embedding-3-small",
"encoding_format":"base64"
}
""";
const string Output = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": "AAAAAA=="
}
],
"model": "text-embedding-3-small",
"usage": null
}
""";
using VerbatimHttpHandler handler = new(Input, Output);
using HttpClient httpClient = new(handler);
using IEmbeddingGenerator<string, Embedding<float>> generator = CreateEmbeddingGenerator(httpClient, "text-embedding-3-small");
var response = await generator.GenerateAsync(["hello, world!"]);
Assert.NotNull(response);
Assert.Single(response);
Assert.Null(response.Usage);
foreach (Embedding<float> e in response)
{
Assert.Equal("text-embedding-3-small", e.ModelId);
Assert.NotNull(e.CreatedAt);
Assert.Equal(1, e.Vector.Length);
}
}
[Fact]
public async Task RequestHeaders_UserAgent_ContainsMEAI()
{
using var handler = new ThrowUserAgentExceptionHandler();
using HttpClient httpClient = new(handler);
using IEmbeddingGenerator<string, Embedding<float>> generator = CreateEmbeddingGenerator(httpClient, "text-embedding-3-small");
InvalidOperationException e = await Assert.ThrowsAsync<InvalidOperationException>(() => generator.GenerateAsync("hello"));
Assert.StartsWith("User-Agent header: OpenAI", e.Message);
Assert.Contains("MEAI", e.Message);
}
private static IEmbeddingGenerator<string, Embedding<float>> CreateEmbeddingGenerator(HttpClient httpClient, string modelId) =>
new OpenAIClient(
new ApiKeyCredential("apikey"),
new OpenAIClientOptions { Transport = new HttpClientPipelineTransport(httpClient) })
.GetEmbeddingClient(modelId)
.AsIEmbeddingGenerator();
}
| OpenAIEmbeddingGeneratorTests |
csharp | cake-build__cake | src/Cake.Core.Tests/Unit/IO/PathCollapserTests.cs | {
"start": 5806,
"end": 7074
} | public sealed class ____
{
[Fact]
public void Should_Collapse_Path_With_Windows_Root()
{
// Given, When
var path = PathCollapser.Collapse(new DirectoryPath("c:/hello/temp/test/../../world"));
// Then
Assert.Equal("c:/hello/world", path);
}
[WindowsFact]
public void Should_Stop_Collapsing_When_Windows_Root_Is_Reached()
{
// Given, When
var path = PathCollapser.Collapse(new DirectoryPath("c:/../../../../../../temp"));
// Then
Assert.Equal("c:/temp", path);
}
[Theory]
[InlineData("C:/foo/..", "C:")]
public void Should_Collapse_To_Root_When_Only_One_Folder_Is_Followed_By_Ellipsis(string input,
string expected)
{
// Given, When
var path = PathCollapser.Collapse(new DirectoryPath(input));
// Then
Assert.Equal(expected, path);
}
}
}
}
} | WithPathsInWindowsFormat |
csharp | grandnode__grandnode2 | src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs | {
"start": 341,
"end": 1406
} | public class ____ : IStartupApplication
{
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IGrandAuthenticationService, CookieAuthenticationService>();
services.AddScoped<ICookieOptionsFactory, CookieOptionsFactory>();
services.AddScoped<IApiAuthenticationService, ApiAuthenticationService>();
services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();
services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();
services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();
services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();
services.AddScoped<IRefreshTokenService, RefreshTokenService>();
}
public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
{
}
public int Priority => 100;
public bool BeforeConfigure => false;
} | StartupApplication |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/ItemContainer/ItemContainer.cs | {
"start": 529,
"end": 20399
} | partial class ____ : Control
{
// Change to 'true' to turn on debugging outputs in Output window
//bool ItemContainerTrace::s_IsDebugOutputEnabled{ false };
//bool ItemContainerTrace::s_IsVerboseDebugOutputEnabled{ false };
// Keeps track of the one ItemContainer with the mouse pointer over, if any.
// The OnPointerExited method does not get invoked when the ItemContainer is scrolled away from the mouse pointer.
// This static instance allows to clear the mouse over state when any other ItemContainer gets the mouse over state.
[ThreadStatic]
static WeakReference<ItemContainer> s_mousePointerOverInstance;
public ItemContainer()
{
//ITEMCONTAINER_TRACE_INFO(null, TRACE_MSG_METH, METH_NAME, this);
//__RP_Marker_ClassById(RuntimeProfiler::ProfId_ItemContainer);
//EnsureProperties();
this.SetDefaultStyleKey();
}
~ItemContainer()
{
//ITEMCONTAINER_TRACE_INFO(null, TRACE_MSG_METH, METH_NAME, this);
if (s_mousePointerOverInstance?.TryGetTarget(out var mousePointerOverInstance) == true)
{
if (mousePointerOverInstance == this)
{
s_mousePointerOverInstance = null;
}
}
}
protected override void OnApplyTemplate()
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH, METH_NAME, this);
// Unload events from previous template when ItemContainer gets a new template.
if (m_selectionCheckbox is { } selectionCheckbox)
{
m_checked_revoker.Disposable = null;
m_unchecked_revoker.Disposable = null;
}
m_rootPanel = GetTemplateChild<Panel>(s_containerRootName);
// If the Child property is already set, add it to the tree. After this point, the
// property changed event for Child property will add it to the tree.
if (Child is { } child)
{
if (m_rootPanel is { } rootPanel)
{
rootPanel.Children.Insert(0, child);
}
}
m_pointerInfo = new PointerInfo<ItemContainer>();
// Uno docs: We override OnIsEnabledChanged instead of subscribing to IsEnabledChanged event.
//m_isEnabledChangedRevoker.revoke();
//m_isEnabledChangedRevoker = IsEnabledChanged(auto_revoke, { this, &OnIsEnabledChanged });
base.OnApplyTemplate();
UpdateVisualState(true);
UpdateMultiSelectState(true);
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ItemContainerAutomationPeer(this);
}
// Uno docs: We use OnIsEnabledChanged override instead of subscribing to IsEnabledChanged event.
private protected override void OnIsEnabledChanged(IsEnabledChangedEventArgs e)
{
//ITEMCONTAINER_TRACE_INFO(*this, TRACE_MSG_METH_INT, METH_NAME, this, IsEnabled());
if (!IsEnabled)
{
ProcessPointerCanceled(null);
}
else
{
UpdateVisualState(true);
}
}
void OnPropertyChanged(DependencyPropertyChangedEventArgs args)
{
var dependencyProperty = args.Property;
#if DEBUG
if (dependencyProperty == IsSelectedProperty)
{
//bool oldValue = (bool)args.OldValue;
//bool newValue = (bool)args.NewValue;
//ITEMCONTAINER_TRACE_VERBOSE(null, TRACE_MSG_METH_STR_INT_INT, METH_NAME, this, L"IsSelected", oldValue, newValue);
}
else if (dependencyProperty == MultiSelectModeProperty)
{
//ItemContainerMultiSelectMode oldValue = (ItemContainerMultiSelectMode)args.OldValue;
//ItemContainerMultiSelectMode newValue = (ItemContainerMultiSelectMode)args.NewValue;
//ITEMCONTAINER_TRACE_VERBOSE(null, TRACE_MSG_METH_STR_STR, METH_NAME, this, L"MultiSelectMode", TypeLogging::ItemContainerMultiSelectModeToString(newValue).c_str());
}
else
{
//ITEMCONTAINER_TRACE_VERBOSE(null, L"%s[%p](property: %s)\n", METH_NAME, this, DependencyPropertyToString(dependencyProperty).c_str());
}
#endif
if (dependencyProperty == IsSelectedProperty)
{
#if MUX_PRERELEASE
bool isMultipleOrExtended = (MultiSelectMode() & (ItemContainerMultiSelectMode.Multiple | ItemContainerMultiSelectMode.Extended)) != 0;
#else
bool isMultipleOrExtended = (MultiSelectModeInternal() & (ItemContainerMultiSelectMode.Multiple | ItemContainerMultiSelectMode.Extended)) != 0;
#endif
AutomationEvents eventToRaise =
IsSelected ?
(isMultipleOrExtended ? AutomationEvents.SelectionItemPatternOnElementAddedToSelection : AutomationEvents.SelectionItemPatternOnElementSelected) :
(isMultipleOrExtended ? AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection : AutomationEvents.PropertyChanged);
if (eventToRaise != AutomationEvents.PropertyChanged && AutomationPeer.ListenerExists(eventToRaise))
{
if (FrameworkElementAutomationPeer.CreatePeerForElement(this) is { } peer)
{
peer.RaiseAutomationEvent(eventToRaise);
}
}
}
else if (dependencyProperty == ChildProperty)
{
if (m_rootPanel is { } rootPanel)
{
if (args.OldValue != null && rootPanel.Children.IndexOf(args.OldValue as UIElement) is int oldChildIndex)
{
rootPanel.Children.RemoveAt(oldChildIndex);
}
rootPanel.Children.Insert(0, args.NewValue as UIElement);
}
}
if (m_pointerInfo != null)
{
if (dependencyProperty == IsSelectedProperty ||
dependencyProperty == MultiSelectModeProperty)
{
UpdateVisualState(true);
UpdateMultiSelectState(true);
}
}
}
void GoToState(string stateName, bool useTransitions)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_INT, METH_NAME, this, stateName.data(), useTransitions);
VisualStateManager.GoToState(this, stateName, useTransitions);
}
internal override void UpdateVisualState(bool useTransitions)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, useTransitions);
// DisabledStates
if (!IsEnabled)
{
GoToState(s_disabledStateName, useTransitions);
GoToState(IsSelected ? s_selectedNormalStateName : s_unselectedNormalStateName, useTransitions);
}
else
{
GoToState(s_enabledStateName, useTransitions);
// CombinedStates
if (m_pointerInfo == null)
{
return;
}
if (m_pointerInfo.IsPressed() && IsSelected)
{
GoToState(s_selectedPressedStateName, useTransitions);
}
else if (m_pointerInfo.IsPressed())
{
GoToState(s_unselectedPressedStateName, useTransitions);
}
else if (m_pointerInfo.IsPointerOver() && IsSelected)
{
GoToState(s_selectedPointerOverStateName, useTransitions);
}
else if (m_pointerInfo.IsPointerOver())
{
GoToState(s_unselectedPointerOverStateName, useTransitions);
}
else if (IsSelected)
{
GoToState(s_selectedNormalStateName, useTransitions);
}
else
{
GoToState(s_unselectedNormalStateName, useTransitions);
}
}
}
void UpdateMultiSelectState(bool useTransitions)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, useTransitions);
#if MUX_PRERELEASE
ItemContainerMultiSelectMode multiSelectMode = MultiSelectMode();
#else
ItemContainerMultiSelectMode multiSelectMode = MultiSelectModeInternal();
#endif
// MultiSelectStates
if ((multiSelectMode & ItemContainerMultiSelectMode.Multiple) != 0)
{
GoToState(s_multipleStateName, useTransitions);
if (m_selectionCheckbox is null)
{
LoadSelectionCheckbox();
}
UpdateCheckboxState();
}
else
{
GoToState(s_singleStateName, useTransitions);
}
}
void ProcessPointerOver(PointerRoutedEventArgs args, bool isPointerOver)
{
if (m_pointerInfo is not null)
{
bool oldIsPointerOver = m_pointerInfo.IsPointerOver();
var pointerDeviceType = args.Pointer.PointerDeviceType;
if (pointerDeviceType == PointerDeviceType.Touch)
{
if (isPointerOver)
{
m_pointerInfo.SetIsTouchPointerOver();
}
else
{
// Once a touch pointer leaves the ItemContainer it is no longer tracked because this
// ItemContainer may never receive a PointerReleased, PointerCanceled or PointerCaptureLost
// for that PointerId.
m_pointerInfo.ResetAll();
}
}
else if (pointerDeviceType == PointerDeviceType.Pen)
{
if (isPointerOver)
{
m_pointerInfo.SetIsPenPointerOver();
}
else
{
// Once a pen pointer leaves the ItemContainer it is no longer tracked because this
// ItemContainer may never receive a PointerReleased, PointerCanceled or PointerCaptureLost
// for that PointerId.
m_pointerInfo.ResetAll();
}
}
else
{
if (isPointerOver)
{
m_pointerInfo.SetIsMousePointerOver();
}
else
{
m_pointerInfo.ResetIsMousePointerOver();
}
UpdateMousePointerOverInstance(isPointerOver);
}
if (m_pointerInfo.IsPointerOver() != oldIsPointerOver)
{
UpdateVisualState(true);
}
}
}
void ProcessPointerCanceled(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_INFO(*this, TRACE_MSG_METH_INT, METH_NAME, this, args == null ? -1 : args.Pointer().PointerId());
if (m_pointerInfo is not null)
{
if (args == null)
{
m_pointerInfo.ResetAll();
}
else
{
var pointer = args.Pointer;
if (m_pointerInfo.IsPointerIdTracked(pointer.PointerId))
{
m_pointerInfo.ResetTrackedPointerId();
}
var pointerDeviceType = pointer.PointerDeviceType;
switch (pointerDeviceType)
{
case PointerDeviceType.Touch:
m_pointerInfo.ResetPointerPressed();
m_pointerInfo.ResetIsTouchPointerOver();
break;
case PointerDeviceType.Pen:
m_pointerInfo.ResetPointerPressed();
m_pointerInfo.ResetIsPenPointerOver();
break;
case PointerDeviceType.Mouse:
m_pointerInfo.ResetIsMouseButtonPressed(true /*isForLeftMouseButton*/);
m_pointerInfo.ResetIsMouseButtonPressed(false /*isForLeftMouseButton*/);
m_pointerInfo.ResetIsMousePointerOver();
UpdateMousePointerOverInstance(false /*isPointerOver*/);
break;
}
}
}
UpdateVisualState(true);
}
protected override void OnPointerEntered(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerEntered(args);
ProcessPointerOver(args, true /*isPointerOver*/);
}
protected override void OnPointerMoved(PointerRoutedEventArgs args)
{
base.OnPointerMoved(args);
ProcessPointerOver(args, true /*isPointerOver*/);
}
protected override void OnPointerExited(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerExited(args);
ProcessPointerOver(args, false /*isPointerOver*/);
}
protected override void OnPointerPressed(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerPressed(args);
if (m_pointerInfo == null || args.Handled)
{
return;
}
var pointer = args.Pointer;
var pointerDeviceType = pointer.PointerDeviceType;
PointerUpdateKind pointerUpdateKind = PointerUpdateKind.Other;
if (pointerDeviceType == PointerDeviceType.Mouse)
{
var pointerProperties = args.GetCurrentPoint(this).Properties;
pointerUpdateKind = pointerProperties.PointerUpdateKind;
if (pointerUpdateKind != PointerUpdateKind.LeftButtonPressed &&
pointerUpdateKind != PointerUpdateKind.RightButtonPressed)
{
return;
}
}
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_STR, METH_NAME, this, TypeLogging::PointerDeviceTypeToString(pointerDeviceType).c_str(), TypeLogging::PointerUpdateKindToString(pointerUpdateKind).c_str());
var pointerId = pointer.PointerId;
if (!m_pointerInfo.IsTrackingPointer())
{
m_pointerInfo.TrackPointerId(pointerId);
}
else if (!m_pointerInfo.IsPointerIdTracked(pointerId))
{
return;
}
bool canRaiseItemInvoked = CanRaiseItemInvoked();
switch (pointerDeviceType)
{
case PointerDeviceType.Touch:
m_pointerInfo.SetPointerPressed();
m_pointerInfo.SetIsTouchPointerOver();
break;
case PointerDeviceType.Pen:
m_pointerInfo.SetPointerPressed();
m_pointerInfo.SetIsPenPointerOver();
break;
case PointerDeviceType.Mouse:
m_pointerInfo.SetIsMouseButtonPressed(pointerUpdateKind == PointerUpdateKind.LeftButtonPressed /*isForLeftMouseButton*/);
canRaiseItemInvoked &= pointerUpdateKind == PointerUpdateKind.LeftButtonPressed;
m_pointerInfo.SetIsMousePointerOver();
UpdateMousePointerOverInstance(true /*isPointerOver*/);
break;
}
if (canRaiseItemInvoked)
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.PointerPressed, args.OriginalSource);
}
UpdateVisualState(true);
}
protected override void OnPointerReleased(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerReleased(args);
if (m_pointerInfo == null ||
!m_pointerInfo.IsPointerIdTracked(args.Pointer.PointerId) ||
!m_pointerInfo.IsPressed())
{
return;
}
m_pointerInfo.ResetTrackedPointerId();
bool canRaiseItemInvoked = CanRaiseItemInvoked();
var pointerDeviceType = args.Pointer.PointerDeviceType;
if (pointerDeviceType == PointerDeviceType.Mouse)
{
var pointerProperties = args.GetCurrentPoint(this).Properties;
var pointerUpdateKind = pointerProperties.PointerUpdateKind;
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_STR, METH_NAME, this, TypeLogging::PointerDeviceTypeToString(pointerDeviceType).c_str(), TypeLogging::PointerUpdateKindToString(pointerUpdateKind).c_str());
if (pointerUpdateKind == PointerUpdateKind.LeftButtonReleased ||
pointerUpdateKind == PointerUpdateKind.RightButtonReleased)
{
m_pointerInfo.ResetIsMouseButtonPressed(pointerUpdateKind == PointerUpdateKind.LeftButtonReleased /*isForLeftMouseButton*/);
}
canRaiseItemInvoked &= pointerUpdateKind == PointerUpdateKind.LeftButtonReleased;
}
else
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR, METH_NAME, this, TypeLogging::PointerDeviceTypeToString(pointerDeviceType).c_str());
m_pointerInfo.ResetPointerPressed();
}
if (canRaiseItemInvoked &&
!args.Handled &&
!m_pointerInfo.IsPressed())
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.PointerReleased, args.OriginalSource);
}
UpdateVisualState(true);
}
protected override void OnPointerCanceled(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerCanceled(args);
ProcessPointerCanceled(args);
}
protected override void OnPointerCaptureLost(PointerRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_INT, METH_NAME, this, args.Pointer().PointerId());
base.OnPointerCaptureLost(args);
ProcessPointerCanceled(args);
}
protected override void OnTapped(TappedRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH, METH_NAME, this);
base.OnTapped(args);
if (CanRaiseItemInvoked() && !args.Handled)
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.Tap, args.OriginalSource);
}
}
protected override void OnDoubleTapped(DoubleTappedRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH, METH_NAME, this);
base.OnDoubleTapped(args);
if (CanRaiseItemInvoked() && !args.Handled)
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.DoubleTap, args.OriginalSource);
}
}
protected override void OnKeyDown(KeyRoutedEventArgs args)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR, METH_NAME, this, TypeLogging::KeyRoutedEventArgsToString(args).c_str());
base.OnKeyDown(args);
if (!args.Handled && CanRaiseItemInvoked())
{
if (args.Key == VirtualKey.Enter)
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.EnterKey, args.OriginalSource);
}
else if (args.Key == VirtualKey.Space)
{
args.Handled = RaiseItemInvoked(ItemContainerInteractionTrigger.SpaceKey, args.OriginalSource);
}
}
}
bool CanRaiseItemInvoked()
{
#if MUX_PRERELEASE
return static_cast<int>(CanUserInvoke() & ItemContainerUserInvokeMode::UserCanInvoke) ||
static_cast<int>(CanUserSelect() & (ItemContainerUserSelectMode::Auto | ItemContainerUserSelectMode::UserCanSelect));
#else
return (CanUserInvokeInternal() & ItemContainerUserInvokeMode.UserCanInvoke) != 0 ||
(CanUserSelectInternal() & (ItemContainerUserSelectMode.Auto | ItemContainerUserSelectMode.UserCanSelect)) != 0;
#endif
}
internal bool RaiseItemInvoked(ItemContainerInteractionTrigger interactionTrigger, object originalSource)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR, METH_NAME, this, TypeLogging::ItemContainerInteractionTriggerToString(interactionTrigger).c_str());
if (ItemInvoked is not null)
{
var itemInvokedEventArgs = new ItemContainerInvokedEventArgs(interactionTrigger, originalSource);
ItemInvoked.Invoke(this, itemInvokedEventArgs);
return itemInvokedEventArgs.Handled;
}
return false;
}
void LoadSelectionCheckbox()
{
m_selectionCheckbox = GetTemplateChild<CheckBox>(s_selectionCheckboxName);
if (m_selectionCheckbox is { } selectionCheckbox)
{
selectionCheckbox.Checked += OnCheckToggle;
m_checked_revoker.Disposable = new DisposableAction(() => selectionCheckbox.Checked -= OnCheckToggle);
selectionCheckbox.Unchecked += OnCheckToggle;
m_unchecked_revoker.Disposable = new DisposableAction(() => selectionCheckbox.Unchecked -= OnCheckToggle);
}
}
void OnCheckToggle(object sender, RoutedEventArgs args)
{
UpdateCheckboxState();
}
void UpdateCheckboxState()
{
if (m_selectionCheckbox is { } selectionCheckbox)
{
bool isChecked = SharedHelpers.IsTrue(selectionCheckbox.IsChecked);
bool isSelected = IsSelected;
if (isChecked != isSelected)
{
selectionCheckbox.IsChecked = isSelected;
}
}
}
void UpdateMousePointerOverInstance(bool isPointerOver)
{
ItemContainer mousePointerOverInstance = null;
s_mousePointerOverInstance?.TryGetTarget(out mousePointerOverInstance);
if (isPointerOver)
{
if (mousePointerOverInstance == null || mousePointerOverInstance != this)
{
if (mousePointerOverInstance != null && mousePointerOverInstance.m_pointerInfo != null)
{
mousePointerOverInstance.m_pointerInfo.ResetIsMousePointerOver();
}
s_mousePointerOverInstance = new WeakReference<ItemContainer>(this);
}
}
else
{
if (mousePointerOverInstance != null && mousePointerOverInstance == this)
{
s_mousePointerOverInstance = null;
}
}
}
#if false
string DependencyPropertyToString(
DependencyProperty dependencyProperty)
{
if (dependencyProperty == IsSelectedProperty)
{
return "IsSelected";
}
else if (dependencyProperty == CanUserSelectProperty)
{
return "CanUserSelect";
}
else if (dependencyProperty == CanUserInvokeProperty)
{
return "CanUserInvoke";
}
else if (dependencyProperty == MultiSelectModeProperty)
{
return "MultiSelectMode";
}
else
{
return "UNKNOWN";
}
}
protected override Size MeasureOverride(Size availableSize)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_FLT_FLT, METH_NAME, this, L"availableSize", availableSize.Width, availableSize.Height);
Size returnedSize = base.MeasureOverride(availableSize);
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_FLT_FLT, METH_NAME, this, L"returnedSize", returnedSize.Width, returnedSize.Height);
return returnedSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_FLT_FLT, METH_NAME, this, L"finalSize", finalSize.Width, finalSize.Height);
Size returnedSize = base.ArrangeOverride(finalSize);
//ITEMCONTAINER_TRACE_VERBOSE(*this, TRACE_MSG_METH_STR_FLT_FLT, METH_NAME, this, L"returnedSize", returnedSize.Width, returnedSize.Height);
return returnedSize;
}
#endif
}
| ItemContainer |
csharp | dotnet__orleans | test/TesterInternal/GrainDirectory/DistributedGrainDirectoryTests.cs | {
"start": 334,
"end": 856
} | public sealed class ____(DefaultClusterFixture fixture, ITestOutputHelper output)
: GrainDirectoryTests<IGrainDirectory>(output), IClassFixture<DefaultClusterFixture>
{
private readonly TestCluster _testCluster = fixture.HostedCluster;
private InProcessSiloHandle Primary => (InProcessSiloHandle)_testCluster.Primary;
protected override IGrainDirectory CreateGrainDirectory() =>
Primary.SiloHost.Services.GetRequiredService<GrainDirectoryResolver>().DefaultGrainDirectory;
}
| DefaultGrainDirectoryTests |
csharp | microsoft__semantic-kernel | dotnet/test/VectorData/Qdrant.ConformanceTests/TypeTests/QdrantDataTypeTests.cs | {
"start": 279,
"end": 1097
} | public class ____(QdrantDataTypeTests.Fixture fixture)
: DataTypeTests<Guid, DataTypeTests<Guid>.DefaultRecord>(fixture), IClassFixture<QdrantDataTypeTests.Fixture>
{
// Qdrant doesn't seem to support filtering on float/double or string ararys,
// https://qdrant.tech/documentation/concepts/filtering/#match
[ConditionalFact]
public override Task Float()
=> this.Test<float>("Float", 8.5f, 9.5f, isFilterable: false);
[ConditionalFact]
public override Task Double()
=> this.Test<double>("Double", 8.5d, 9.5d, isFilterable: false);
[ConditionalFact]
public override Task String_array()
=> this.Test<string[]>(
"StringArray",
["foo", "bar"],
["foo", "baz"],
isFilterable: false);
public new | QdrantDataTypeTests |
csharp | AutoMapper__AutoMapper | src/UnitTests/Mappers/StringDictionaryMapperTests.cs | {
"start": 9269,
"end": 9515
} | public class ____ : SomeBase
{
public override int X { get { return _x + 10; } }
public override int Y { get { return _y + 20; } }
private int _z = 300;
public int Z { get { return _z + 30; } }
}
| SomeBody |
csharp | Xabaril__AspNetCore.Diagnostics.HealthChecks | src/CallerArgumentExpressionAttribute.cs | {
"start": 1036,
"end": 2088
} | internal static class ____
{
/// <summary>Throws an <see cref="ArgumentNullException"/> if <paramref name="argument"/> is null.</summary>
/// <param name="argument">The reference type argument to validate as non-null.</param>
/// <param name="throwOnEmptyString">Only applicable to strings.</param>
/// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
public static T ThrowIfNull<T>([NotNull] T? argument, bool throwOnEmptyString = false, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
where T : class
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(argument, paramName);
if (throwOnEmptyString && argument is string s && string.IsNullOrEmpty(s))
throw new ArgumentNullException(paramName);
#else
if (argument is null || throwOnEmptyString && argument is string s && string.IsNullOrEmpty(s))
throw new ArgumentNullException(paramName);
#endif
return argument;
}
}
| Guard |
csharp | LibreHardwareMonitor__LibreHardwareMonitor | LibreHardwareMonitor/UI/NotifyIconAdv.cs | {
"start": 25335,
"end": 25631
} | public enum ____ : int
{
Message = 0x1,
Icon = 0x2,
Tip = 0x4,
State = 0x8,
Info = 0x10
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
| NotifyIconDataFlags |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsIntrospectionTest.Client.cs | {
"start": 144815,
"end": 145728
} | public partial interface ____ : IIntrospectionQuery___schema_Types_Interfaces_OfType_OfType
{
}
// StrawberryShake.CodeGeneration.CSharp.Generators.ResultInterfaceGenerator
/// <summary>
/// The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.
///
/// Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
| IIntrospectionQuery___schema_Types_Interfaces_OfType_OfType___Type |
csharp | MiniProfiler__dotnet | src/MiniProfiler.Providers.PostgreSql/PostgreSqlStorage.cs | {
"start": 532,
"end": 884
} | class ____ the specified connection string.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
public PostgreSqlStorage(string connectionString) : base(connectionString) { /* base call */ }
/// <summary>
/// Initializes a new instance of the <see cref="PostgreSqlStorage"/> | with |
csharp | dotnet__aspire | src/Tools/ConfigurationSchemaGenerator/ConfigurationBindingGenerator.ForSchemaGeneration.cs | {
"start": 688,
"end": 998
} | internal sealed class ____
{
public bool LanguageVersionIsSupported { get; } = true;
public KnownTypeSymbols? TypeSymbols { get; }
public CompilationData(KnownTypeSymbols? typeSymbols)
{
TypeSymbols = typeSymbols;
}
}
internal sealed | CompilationData |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Serialization/CamelCaseNamingStrategyTests.cs | {
"start": 9009,
"end": 9986
} | public class ____
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
[JsonProperty(NamingStrategyType = typeof(DefaultNamingStrategy))]
public string HasAttributeNamingStrategy { get; set; }
}
[Test]
public void JsonObjectAttribute_NamingStrategyType()
{
ContainerAttributeNamingStrategyTestClass c = new ContainerAttributeNamingStrategyTestClass
{
Prop1 = "Value1!",
Prop2 = "Value2!"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""prop1"": ""Value1!"",
""prop2"": ""Value2!"",
""HasAttributeNamingStrategy"": null
}", json);
}
[JsonDictionary(NamingStrategyType = typeof(CamelCaseNamingStrategy), NamingStrategyParameters = new object[] { true, true })]
| ContainerAttributeNamingStrategyTestClass |
csharp | RicoSuter__NJsonSchema | src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs | {
"start": 554,
"end": 1877
} | public abstract class ____
{
/// <summary>Initializes a new instance of the <see cref="CodeGeneratorSettingsBase"/> class.</summary>
#pragma warning disable CS8618
public CodeGeneratorSettingsBase()
#pragma warning restore CS8618
{
GenerateDefaultValues = true;
ExcludedTypeNames = [];
}
/// <summary>Gets or sets the schema type (default: JsonSchema).</summary>
public SchemaType SchemaType { get; set; } = SchemaType.JsonSchema;
/// <summary>Gets or sets a value indicating whether to generate default values for properties (when JSON Schema default is set, default: true).</summary>
public bool GenerateDefaultValues { get; set; }
/// <summary>Gets or sets the excluded type names (must be defined in an import or other namespace).</summary>
public string[] ExcludedTypeNames { get; set; }
/// <summary>Gets or sets the property name generator.</summary>
[JsonIgnore]
public IPropertyNameGenerator PropertyNameGenerator { get; set; }
/// <summary>Gets or sets the type name generator.</summary>
[JsonIgnore]
public ITypeNameGenerator TypeNameGenerator { get; set; } = new DefaultTypeNameGenerator();
/// <summary>Gets or sets the | CodeGeneratorSettingsBase |
csharp | bitwarden__server | src/Api/SecretsManager/Models/Request/ServiceAccountGrantedPoliciesRequestModel.cs | {
"start": 192,
"end": 1077
} | public class ____
{
public required IEnumerable<GrantedAccessPolicyRequest> ProjectGrantedPolicyRequests { get; set; }
public ServiceAccountGrantedPolicies ToGrantedPolicies(ServiceAccount serviceAccount)
{
var projectGrantedPolicies = ProjectGrantedPolicyRequests
.Select(x => x.ToServiceAccountProjectAccessPolicy(serviceAccount.Id, serviceAccount.OrganizationId))
.ToList();
AccessPolicyHelpers.CheckForDistinctAccessPolicies(projectGrantedPolicies);
AccessPolicyHelpers.CheckAccessPoliciesHaveReadPermission(projectGrantedPolicies);
return new ServiceAccountGrantedPolicies
{
ServiceAccountId = serviceAccount.Id,
OrganizationId = serviceAccount.OrganizationId,
ProjectGrantedPolicies = projectGrantedPolicies
};
}
}
| ServiceAccountGrantedPoliciesRequestModel |
csharp | unoplatform__uno | src/SourceGenerators/System.Xaml.Tests/Test/System.Xaml/TestedTypes.cs | {
"start": 9568,
"end": 9777
} | public class ____
{
public ListWrapper ()
{
Items = new List<int> ();
}
public ListWrapper (List<int> items)
{
Items = items;
}
public List<int> Items { get; private set; }
}
| ListWrapper |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/CancellationTests.cs | {
"start": 5826,
"end": 5868
} | public record ____(int Id);
}
| Product |
csharp | dotnet__maui | src/Controls/tests/ManualTests/Tests/Commands/G6.xaml.cs | {
"start": 305,
"end": 437
} | public partial class ____ : ContentPage
{
public G6()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
}
| G6 |
csharp | abpframework__abp | framework/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/Repositories/Repository_Specifications_Tests.cs | {
"start": 77,
"end": 183
} | public class ____ : Repository_Specifications_Tests<AbpMemoryDbTestModule>
{
}
| Repository_Specifications_Tests |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/Pulumi/Pulumi.Generated.cs | {
"start": 535650,
"end": 548991
} | partial class ____
{
#region Name
/// <inheritdoc cref="PulumiStackTagSetSettings.Name"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Name))]
public static T SetName<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Name, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Name"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Name))]
public static T ResetName<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Name));
#endregion
#region Value
/// <inheritdoc cref="PulumiStackTagSetSettings.Value"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Value))]
public static T SetValue<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Value, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Value"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Value))]
public static T ResetValue<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Value));
#endregion
#region Color
/// <inheritdoc cref="PulumiStackTagSetSettings.Color"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Color))]
public static T SetColor<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Color, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Color"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Color))]
public static T ResetColor<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Color));
#endregion
#region Cwd
/// <inheritdoc cref="PulumiStackTagSetSettings.Cwd"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Cwd))]
public static T SetCwd<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Cwd, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Cwd"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Cwd))]
public static T ResetCwd<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Cwd));
#endregion
#region DisableIntegrityChecking
/// <inheritdoc cref="PulumiStackTagSetSettings.DisableIntegrityChecking"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.DisableIntegrityChecking))]
public static T SetDisableIntegrityChecking<T>(this T o, bool? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.DisableIntegrityChecking, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.DisableIntegrityChecking"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.DisableIntegrityChecking))]
public static T ResetDisableIntegrityChecking<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.DisableIntegrityChecking));
/// <inheritdoc cref="PulumiStackTagSetSettings.DisableIntegrityChecking"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.DisableIntegrityChecking))]
public static T EnableDisableIntegrityChecking<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.DisableIntegrityChecking, true));
/// <inheritdoc cref="PulumiStackTagSetSettings.DisableIntegrityChecking"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.DisableIntegrityChecking))]
public static T DisableDisableIntegrityChecking<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.DisableIntegrityChecking, false));
/// <inheritdoc cref="PulumiStackTagSetSettings.DisableIntegrityChecking"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.DisableIntegrityChecking))]
public static T ToggleDisableIntegrityChecking<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.DisableIntegrityChecking, !o.DisableIntegrityChecking));
#endregion
#region Emoji
/// <inheritdoc cref="PulumiStackTagSetSettings.Emoji"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Emoji))]
public static T SetEmoji<T>(this T o, bool? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Emoji, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Emoji"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Emoji))]
public static T ResetEmoji<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Emoji));
/// <inheritdoc cref="PulumiStackTagSetSettings.Emoji"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Emoji))]
public static T EnableEmoji<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Emoji, true));
/// <inheritdoc cref="PulumiStackTagSetSettings.Emoji"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Emoji))]
public static T DisableEmoji<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Emoji, false));
/// <inheritdoc cref="PulumiStackTagSetSettings.Emoji"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Emoji))]
public static T ToggleEmoji<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Emoji, !o.Emoji));
#endregion
#region LogFlow
/// <inheritdoc cref="PulumiStackTagSetSettings.LogFlow"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogFlow))]
public static T SetLogFlow<T>(this T o, bool? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogFlow, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogFlow"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogFlow))]
public static T ResetLogFlow<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.LogFlow));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogFlow"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogFlow))]
public static T EnableLogFlow<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogFlow, true));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogFlow"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogFlow))]
public static T DisableLogFlow<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogFlow, false));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogFlow"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogFlow))]
public static T ToggleLogFlow<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogFlow, !o.LogFlow));
#endregion
#region LogToStderr
/// <inheritdoc cref="PulumiStackTagSetSettings.LogToStderr"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogToStderr))]
public static T SetLogToStderr<T>(this T o, bool? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogToStderr, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogToStderr"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogToStderr))]
public static T ResetLogToStderr<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.LogToStderr));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogToStderr"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogToStderr))]
public static T EnableLogToStderr<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogToStderr, true));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogToStderr"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogToStderr))]
public static T DisableLogToStderr<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogToStderr, false));
/// <inheritdoc cref="PulumiStackTagSetSettings.LogToStderr"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.LogToStderr))]
public static T ToggleLogToStderr<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.LogToStderr, !o.LogToStderr));
#endregion
#region NonInteractive
/// <inheritdoc cref="PulumiStackTagSetSettings.NonInteractive"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.NonInteractive))]
public static T SetNonInteractive<T>(this T o, bool? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.NonInteractive, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.NonInteractive"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.NonInteractive))]
public static T ResetNonInteractive<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.NonInteractive));
/// <inheritdoc cref="PulumiStackTagSetSettings.NonInteractive"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.NonInteractive))]
public static T EnableNonInteractive<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.NonInteractive, true));
/// <inheritdoc cref="PulumiStackTagSetSettings.NonInteractive"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.NonInteractive))]
public static T DisableNonInteractive<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.NonInteractive, false));
/// <inheritdoc cref="PulumiStackTagSetSettings.NonInteractive"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.NonInteractive))]
public static T ToggleNonInteractive<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.NonInteractive, !o.NonInteractive));
#endregion
#region Profiling
/// <inheritdoc cref="PulumiStackTagSetSettings.Profiling"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Profiling))]
public static T SetProfiling<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Profiling, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Profiling"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Profiling))]
public static T ResetProfiling<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Profiling));
#endregion
#region Tracing
/// <inheritdoc cref="PulumiStackTagSetSettings.Tracing"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Tracing))]
public static T SetTracing<T>(this T o, string v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Tracing, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Tracing"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Tracing))]
public static T ResetTracing<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Tracing));
#endregion
#region Verbose
/// <inheritdoc cref="PulumiStackTagSetSettings.Verbose"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Verbose))]
public static T SetVerbose<T>(this T o, int? v) where T : PulumiStackTagSetSettings => o.Modify(b => b.Set(() => o.Verbose, v));
/// <inheritdoc cref="PulumiStackTagSetSettings.Verbose"/>
[Pure] [Builder(Type = typeof(PulumiStackTagSetSettings), Property = nameof(PulumiStackTagSetSettings.Verbose))]
public static T ResetVerbose<T>(this T o) where T : PulumiStackTagSetSettings => o.Modify(b => b.Remove(() => o.Verbose));
#endregion
}
#endregion
#region PulumiStackTagGetSettingsExtensions
/// <inheritdoc cref="PulumiTasks.PulumiStackTagGet(Nuke.Common.Tools.Pulumi.PulumiStackTagGetSettings)"/>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static | PulumiStackTagSetSettingsExtensions |
csharp | dotnet__maui | src/Essentials/src/Share/Share.macos.cs | {
"start": 195,
"end": 1581
} | partial class ____ : IShare
{
Task PlatformRequestAsync(ShareTextRequest request)
{
var items = new List<NSObject>();
if (!string.IsNullOrWhiteSpace(request.Title))
items.Add(new NSString(request.Title));
if (!string.IsNullOrWhiteSpace(request.Text))
items.Add(new NSString(request.Text));
if (!string.IsNullOrWhiteSpace(request.Uri))
items.Add(NSUrl.FromString(request.Uri));
return PlatformShowRequestAsync(request, items);
}
Task PlatformRequestAsync(ShareFileRequest request) =>
PlatformRequestAsync((ShareMultipleFilesRequest)request);
Task PlatformRequestAsync(ShareMultipleFilesRequest request)
{
var items = new List<NSObject>();
if (!string.IsNullOrWhiteSpace(request.Title))
items.Add(new NSString(request.Title));
foreach (var file in request.Files)
items.Add(NSUrl.FromFilename(file.FullPath));
return PlatformShowRequestAsync(request, items);
}
static Task PlatformShowRequestAsync(ShareRequestBase request, List<NSObject> items)
{
var window = Platform.GetCurrentWindow();
var view = window.ContentView;
var rect = request.PresentationSourceBounds.AsCGRect();
rect.Y = view.Bounds.Height - rect.Bottom;
var picker = new NSSharingServicePicker(items.ToArray());
picker.ShowRelativeToRect(rect, view, NSRectEdge.MinYEdge);
return Task.CompletedTask;
}
}
}
| ShareImplementation |
csharp | moq__moq4 | src/Moq.Tests/RecursiveMocksFixture.cs | {
"start": 236,
"end": 9388
} | public class ____
{
[Fact]
public void CreatesMockForAccessedProperty()
{
var mock = new Mock<IFoo>();
mock.SetupGet(m => m.Bar.Value).Returns(5);
Assert.Equal(5, mock.Object.Bar.Value);
}
[Fact]
public void RetrievesSameMockForProperty()
{
var mock = new Mock<IFoo> { DefaultValue = DefaultValue.Mock };
var b1 = mock.Object.Bar;
var b2 = mock.Object.Bar;
Assert.Same(b1, b2);
}
[Fact]
public void NewMocksHaveSameBehaviorAndDefaultValueAsOwner()
{
var mock = new Mock<IFoo>();
mock.SetupGet(m => m.Bar.Value).Returns(5);
var barMock = Mock.Get(mock.Object.Bar);
Assert.Equal(mock.Behavior, barMock.Behavior);
Assert.Equal(mock.DefaultValue, barMock.DefaultValue);
}
[Fact]
public void CreatesMockForAccessedPropertyWithMethod()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Do("ping")).Returns("ack");
mock.Setup(m => m.Bar.Baz.Do("ping")).Returns("ack");
Assert.Equal("ack", mock.Object.Bar.Do("ping"));
Assert.Equal("ack", mock.Object.Bar.Baz.Do("ping"));
Assert.Equal(default(string), mock.Object.Bar.Do("foo"));
}
[Fact]
public void CreatesMockForAccessedPropertyWithVoidMethod()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Baz.Do());
//Assert.Throws<MockVerificationException>(() => mock.VerifyAll());
Assert.NotNull(mock.Object.Bar);
Assert.NotNull(mock.Object.Bar.Baz);
mock.Object.Bar.Baz.Do();
mock.Verify(m => m.Bar.Baz.Do());
}
[Fact]
public void CreatesMockForAccessedPropertyWithSetterWithValue()
{
var mock = new Mock<IFoo>();
mock.SetupSet(m => m.Bar.Value = 5);
Assert.NotNull(mock.Object.Bar);
var ex = Assert.Throws<MockException>(() => mock.VerifyAll());
Assert.True(ex.IsVerificationError);
mock.Object.Bar.Value = 5;
mock.VerifyAll();
}
[Fact]
public void CreatesMockForAccessedPropertyWithSetter()
{
var mock = new Mock<IFoo>();
mock.SetupSet(m => m.Bar.Value = It.IsAny<int>());
Assert.NotNull(mock.Object.Bar);
var ex = Assert.Throws<MockException>(() => mock.VerifyAll());
Assert.True(ex.IsVerificationError);
mock.Object.Bar.Value = 5;
mock.VerifyAll();
}
[Fact]
public void VerifiesAllHierarchy()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Do("ping")).Returns("ack");
mock.Setup(m => m.Do("ping")).Returns("ack");
mock.Object.Do("ping");
var bar = mock.Object.Bar;
var ex = Assert.Throws<MockException>(() => mock.VerifyAll());
Assert.True(ex.IsVerificationError);
}
[Fact]
public void VerifiesHierarchy()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Do("ping")).Returns("ack").Verifiable();
mock.Setup(m => m.Do("ping")).Returns("ack");
mock.Object.Do("ping");
var bar = mock.Object.Bar;
var ex = Assert.Throws<MockException>(() => mock.Verify());
Assert.True(ex.IsVerificationError);
}
[Fact]
public void VerifiesHierarchyMethodWithExpression()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
Assert.Throws<MockException>(() => mock.Verify(m => m.Bar.Do("ping")));
mock.Object.Bar.Do("ping");
mock.Verify(m => m.Bar.Do("ping"));
}
[Fact]
public void VerifiesHierarchyPropertyGetWithExpression()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
Assert.Throws<MockException>(() => mock.VerifyGet(m => m.Bar.Value));
var value = mock.Object.Bar.Value;
mock.VerifyGet(m => m.Bar.Value);
}
[Fact]
public void VerifiesHierarchyPropertySetWithExpression()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
Assert.Throws<MockException>(() => mock.VerifySet(m => m.Bar.Value = It.IsAny<int>()));
mock.Object.Bar.Value = 5;
mock.VerifySet(m => m.Bar.Value = It.IsAny<int>());
}
[Fact]
public void VerifiesReturnWithExpression()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Do("ping")).Returns("ack").Verifiable();
Assert.Throws<MockException>(() => mock.Verify(m => m.Bar.Do("ping")));
var result = mock.Object.Bar.Do("ping");
Assert.Equal("ack", result);
mock.Verify(m => m.Bar.Do("ping"));
}
[Fact]
public void VerifiesVoidWithExpression()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Baz.Do());
Assert.Throws<MockException>(() => mock.Verify(m => m.Bar.Baz.Do()));
mock.Object.Bar.Baz.Do();
mock.Verify(m => m.Bar.Baz.Do());
}
[Fact]
public void VerifiesGetWithExpression()
{
var mock = new Mock<IFoo>();
mock.SetupGet(m => m.Bar.Value).Returns(5);
Assert.Throws<MockException>(() => mock.VerifyGet(m => m.Bar.Value));
var result = mock.Object.Bar.Value;
Assert.Equal(5, result);
mock.VerifyGet(m => m.Bar.Value);
}
[Fact]
public void VerifiesGetWithExpression2()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Bar.Value).Returns(5);
Assert.Throws<MockException>(() => mock.Verify(m => m.Bar.Value));
var result = mock.Object.Bar.Value;
Assert.Equal(5, result);
mock.Verify(m => m.Bar.Value);
}
[Fact]
public void VerifiesSetWithExpression()
{
var mock = new Mock<IFoo>();
mock.SetupSet(m => m.Bar.Value = It.IsAny<int>());
Assert.Throws<MockException>(() => mock.VerifySet(m => m.Bar.Value = It.IsAny<int>()));
mock.Object.Bar.Value = 5;
mock.VerifySet(m => m.Bar.Value = It.IsAny<int>());
}
[Fact]
public void VerifiesSetWithExpressionAndValue()
{
var mock = new Mock<IFoo>();
mock.SetupSet(m => m.Bar.Value = 5);
Assert.Throws<MockException>(() => mock.VerifySet(m => m.Bar.Value = 5));
mock.Object.Bar.Value = 5;
mock.VerifySet(m => m.Bar.Value = 5);
}
[Fact]
public void FieldAccessNotSupported()
{
var mock = new Mock<Foo>();
Assert.Throws<ArgumentException>(() => mock.Setup(m => m.BarField.Do("ping")));
}
[Fact]
public void NonMockeableTypeThrows()
{
var mock = new Mock<IFoo>();
Assert.Throws<ArgumentException>(() => mock.Setup(m => m.Bar.Value.ToString()));
}
[Fact]
public void IntermediateIndexerAccessIsSupported()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m[0].Do("ping")).Returns("ack");
var result = mock.Object[0].Do("ping");
Assert.Equal("ack", result);
}
[Fact]
public void IntermediateMethodInvocationAreSupported()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.GetBar().Do("ping")).Returns("ack");
var result = mock.Object.GetBar().Do("ping");
Assert.Equal("ack", result);
}
[Fact]
public void FullMethodInvocationsSupportedInsideFluent()
{
var fooMock = new Mock<IFoo>(MockBehavior.Strict);
fooMock.Setup(f => f.Bar.GetBaz("hey").Value).Returns(5);
Assert.Equal(5, fooMock.Object.Bar.GetBaz("hey").Value);
}
[Fact]
public void FullMethodInvocationInsideFluentCanUseMatchers()
{
var fooMock = new Mock<IFoo>(MockBehavior.Strict);
fooMock.Setup(f => f.Bar.GetBaz(It.IsAny<string>()).Value).Returns(5);
Assert.Equal(5, fooMock.Object.Bar.GetBaz("foo").Value);
}
[Fact]
public void Param_array_args_in_setup_expression_parts_are_compared_by_structural_equality_not_reference_equality()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.GetBar(1).Value).Returns(1);
mock.Setup(m => m.GetBar(1).OtherValue).Returns(2);
Assert.Equal(1, mock.Object.GetBar(1).Value);
Assert.Equal(2, mock.Object.GetBar(1).OtherValue);
}
| RecursiveMocksFixture |
csharp | ShareX__ShareX | ShareX.HelpersLib/Controls/ExportImportControl.Designer.cs | {
"start": 35,
"end": 6420
} | partial class ____
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportImportControl));
this.cmsExport = new System.Windows.Forms.ContextMenuStrip(this.components);
this.tsmiExportClipboard = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiExportFile = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiExportUpload = new System.Windows.Forms.ToolStripMenuItem();
this.cmsImport = new System.Windows.Forms.ContextMenuStrip(this.components);
this.tsmiImportClipboard = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiImportFile = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiImportURL = new System.Windows.Forms.ToolStripMenuItem();
this.btnImport = new HelpersLib.MenuButton();
this.btnExport = new HelpersLib.MenuButton();
this.cmsExport.SuspendLayout();
this.cmsImport.SuspendLayout();
this.SuspendLayout();
//
// cmsExport
//
this.cmsExport.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiExportClipboard,
this.tsmiExportFile,
this.tsmiExportUpload});
this.cmsExport.Name = "cmsExport";
this.cmsExport.ShowImageMargin = false;
resources.ApplyResources(this.cmsExport, "cmsExport");
//
// tsmiExportClipboard
//
this.tsmiExportClipboard.Name = "tsmiExportClipboard";
resources.ApplyResources(this.tsmiExportClipboard, "tsmiExportClipboard");
this.tsmiExportClipboard.Click += new System.EventHandler(this.tsmiExportClipboard_Click);
//
// tsmiExportFile
//
this.tsmiExportFile.Name = "tsmiExportFile";
resources.ApplyResources(this.tsmiExportFile, "tsmiExportFile");
this.tsmiExportFile.Click += new System.EventHandler(this.tsmiExportFile_Click);
//
// tsmiExportUpload
//
this.tsmiExportUpload.Name = "tsmiExportUpload";
resources.ApplyResources(this.tsmiExportUpload, "tsmiExportUpload");
this.tsmiExportUpload.Click += new System.EventHandler(this.tsmiExportUpload_Click);
//
// cmsImport
//
this.cmsImport.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiImportClipboard,
this.tsmiImportFile,
this.tsmiImportURL});
this.cmsImport.Name = "cmsImport";
this.cmsImport.ShowImageMargin = false;
resources.ApplyResources(this.cmsImport, "cmsImport");
//
// tsmiImportClipboard
//
this.tsmiImportClipboard.Name = "tsmiImportClipboard";
resources.ApplyResources(this.tsmiImportClipboard, "tsmiImportClipboard");
this.tsmiImportClipboard.Click += new System.EventHandler(this.tsmiImportClipboard_Click);
//
// tsmiImportFile
//
this.tsmiImportFile.Name = "tsmiImportFile";
resources.ApplyResources(this.tsmiImportFile, "tsmiImportFile");
this.tsmiImportFile.Click += new System.EventHandler(this.tsmiImportFile_Click);
//
// tsmiImportURL
//
this.tsmiImportURL.Name = "tsmiImportURL";
resources.ApplyResources(this.tsmiImportURL, "tsmiImportURL");
this.tsmiImportURL.Click += new System.EventHandler(this.tsmiImportURL_Click);
//
// btnImport
//
resources.ApplyResources(this.btnImport, "btnImport");
this.btnImport.Menu = this.cmsImport;
this.btnImport.Name = "btnImport";
this.btnImport.UseVisualStyleBackColor = true;
//
// btnExport
//
resources.ApplyResources(this.btnExport, "btnExport");
this.btnExport.Menu = this.cmsExport;
this.btnExport.Name = "btnExport";
this.btnExport.UseVisualStyleBackColor = true;
//
// ExportImportControl
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnImport);
this.Controls.Add(this.btnExport);
this.Name = "ExportImportControl";
this.cmsExport.ResumeLayout(false);
this.cmsImport.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContextMenuStrip cmsExport;
private System.Windows.Forms.ToolStripMenuItem tsmiExportClipboard;
private System.Windows.Forms.ToolStripMenuItem tsmiExportFile;
private System.Windows.Forms.ContextMenuStrip cmsImport;
private System.Windows.Forms.ToolStripMenuItem tsmiImportClipboard;
private System.Windows.Forms.ToolStripMenuItem tsmiImportFile;
private MenuButton btnExport;
private MenuButton btnImport;
private System.Windows.Forms.ToolStripMenuItem tsmiExportUpload;
private System.Windows.Forms.ToolStripMenuItem tsmiImportURL;
}
}
| ExportImportControl |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp/IHasErrorCode.cs | {
"start": 21,
"end": 96
} | public interface ____
{
int Code { get; set; }
}
} | IHasErrorCode |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Misc.Zettle/Controllers/ZettleAdminController.cs | {
"start": 868,
"end": 16567
} | public class ____ : BasePluginController
{
#region Fields
protected readonly CurrencySettings _currencySettings;
protected readonly IBaseAdminModelFactory _baseAdminModelFactory;
protected readonly ICurrencyService _currencyService;
protected readonly IDateTimeHelper _dateTimeHelper;
protected readonly ILocalizationService _localizationService;
protected readonly INotificationService _notificationService;
protected readonly IPermissionService _permissionService;
protected readonly IProductService _productService;
protected readonly IScheduleTaskService _scheduleTaskService;
protected readonly ISettingService _settingService;
protected readonly IStoreContext _storeContext;
protected readonly TaxSettings _taxSettings;
protected readonly ZettleRecordService _zettleRecordService;
protected readonly ZettleService _zettleService;
protected readonly ZettleSettings _zettleSettings;
#endregion
#region Ctor
public ZettleAdminController(CurrencySettings currencySettings,
IBaseAdminModelFactory baseAdminModelFactory,
ICurrencyService currencyService,
IDateTimeHelper dateTimeHelper,
ILocalizationService localizationService,
INotificationService notificationService,
IPermissionService permissionService,
IProductService productService,
IScheduleTaskService scheduleTaskService,
ISettingService settingService,
IStoreContext storeContext,
TaxSettings taxSettings,
ZettleRecordService zettleRecordService,
ZettleService zettleService,
ZettleSettings zettleSettings)
{
_currencySettings = currencySettings;
_baseAdminModelFactory = baseAdminModelFactory;
_currencyService = currencyService;
_dateTimeHelper = dateTimeHelper;
_localizationService = localizationService;
_notificationService = notificationService;
_permissionService = permissionService;
_productService = productService;
_scheduleTaskService = scheduleTaskService;
_settingService = settingService;
_storeContext = storeContext;
_taxSettings = taxSettings;
_zettleRecordService = zettleRecordService;
_zettleService = zettleService;
_zettleSettings = zettleSettings;
}
#endregion
#region Methods
#region Configuration
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> Configure()
{
var model = new ConfigurationModel
{
ClientId = _zettleSettings.ClientId,
ApiKey = _zettleSettings.ApiKey,
DisconnectOnUninstall = _zettleSettings.DisconnectOnUninstall,
AutoSyncEnabled = _zettleSettings.AutoSyncEnabled,
AutoSyncPeriod = _zettleSettings.AutoSyncPeriod,
DeleteBeforeImport = _zettleSettings.DeleteBeforeImport,
SyncEnabled = _zettleSettings.SyncEnabled,
PriceSyncEnabled = _zettleSettings.PriceSyncEnabled,
ImageSyncEnabled = _zettleSettings.ImageSyncEnabled,
InventoryTrackingEnabled = _zettleSettings.InventoryTrackingEnabled,
DefaultTaxEnabled = _zettleSettings.DefaultTaxEnabled,
DiscountSyncEnabled = _zettleSettings.DiscountSyncEnabled,
};
if (ZettleService.IsConfigured(_zettleSettings))
{
//account info
var (accountInfo, error) = await _zettleService.GetAccountInfoAsync();
if (!string.IsNullOrEmpty(error) || accountInfo is null)
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Configuration.Error");
var errorMessage = string.Format(locale, error, Url.Action("List", "Log"));
_notificationService.ErrorNotification(errorMessage, false);
return View("~/Plugins/Misc.Zettle/Views/Configure.cshtml", model);
}
model.Connected = true;
model.Account.Name = accountInfo.Name;
model.Account.CustomerStatus = accountInfo.CustomerStatus?.ToLower() ?? "undefined";
model.Account.Accepted = string.Equals(accountInfo.CustomerStatus, "ACCEPTED", StringComparison.InvariantCultureIgnoreCase);
//ensure the same currencies are used
var storeCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId);
if (string.IsNullOrEmpty(accountInfo.Currency) ||
!accountInfo.Currency.Equals(storeCurrency.CurrencyCode, StringComparison.InvariantCultureIgnoreCase))
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Account.Fields.Currency.Warning");
var warning = string.Format(locale, storeCurrency.CurrencyCode, accountInfo.Currency, Url.Action("List", "Currency"));
_notificationService.WarningNotification(warning, false);
}
model.Account.Currency = accountInfo.Currency;
//ensure the same tax types are used
var taxNone = string.Equals(accountInfo.TaxationType, "NONE", StringComparison.InvariantCultureIgnoreCase);
var taxVat = string.Equals(accountInfo.TaxationType, "VAT", StringComparison.InvariantCultureIgnoreCase);
var taxRates = string.Equals(accountInfo.TaxationType, "SALES_TAX", StringComparison.InvariantCultureIgnoreCase);
if (_taxSettings.EuVatEnabled != taxVat)
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Account.Fields.TaxationType.Vat.Warning");
var warning = string.Format(locale, Url.Action("Tax", "Setting"));
_notificationService.WarningNotification(warning, false);
}
model.Account.TaxationType = accountInfo.TaxationType?.Replace('_', ' ');
if (taxVat)
{
_zettleSettings.DefaultTaxEnabled = true;
if (accountInfo.VatPercentage.HasValue)
model.Account.TaxationType = $"{model.Account.TaxationType} ({accountInfo.VatPercentage}%)";
}
if (taxRates)
{
var (percentage, _) = await _zettleService.GetDefaultTaxRateAsync();
if (percentage.HasValue)
model.Account.TaxationType = $"{model.Account.TaxationType} ({percentage}% by default)";
else
{
var warning = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Account.Fields.TaxationType.SalesTax.Warning");
_notificationService.WarningNotification(warning);
}
}
//ensure the same price types are used
var pricesIncludeTax = string.Equals(accountInfo.TaxationMode, "INCLUSIVE", StringComparison.InvariantCultureIgnoreCase);
if (_taxSettings.PricesIncludeTax != pricesIncludeTax || (_taxSettings.PricesIncludeTax && taxNone))
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Account.Fields.TaxationMode.Warning");
var warning = string.Format(locale, Url.Action("Tax", "Setting"));
_notificationService.WarningNotification(warning, false);
}
model.Account.TaxationMode = accountInfo.TaxationMode;
//ensure the webhook is created
var store = await _storeContext.GetCurrentStoreAsync();
var webhookUrl = $"{store.Url.TrimEnd('/')}{Url.RouteUrl(ZettleDefaults.WebhookRouteName)}".ToLowerInvariant();
var (webhook, _) = await _zettleService.CreateWebhookAsync(webhookUrl);
_zettleSettings.WebhookUrl = webhook?.Destination;
_zettleSettings.WebhookKey = webhook?.SigningKey;
await _settingService.SaveSettingAsync(_zettleSettings);
if (string.IsNullOrEmpty(_zettleSettings.WebhookUrl))
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Configuration.Webhook.Warning");
var warning = string.Format(locale, Url.Action("List", "Log"));
_notificationService.WarningNotification(warning, false);
}
//last import details
if (!string.IsNullOrEmpty(_zettleSettings.ImportId))
{
var (import, _) = await _zettleService.GetImportAsync();
if (import is not null)
{
model.Import.StartDate = import.Created;
model.Import.EndDate = import.Finished;
model.Import.State = import.State?.Replace('_', ' ');
model.Import.Items = import.Items?.ToString();
model.Import.Active = string.Equals(import.State, "IMPORTING", StringComparison.InvariantCultureIgnoreCase);
}
}
}
var scheduleTask = await _scheduleTaskService.GetTaskByTypeAsync(ZettleDefaults.SynchronizationTask.Type);
if (scheduleTask is not null)
{
model.AutoSyncEnabled = scheduleTask.Enabled;
model.AutoSyncPeriod = scheduleTask.Seconds / 60;
}
return View("~/Plugins/Misc.Zettle/Views/Configure.cshtml", model);
}
[HttpPost, ActionName("Configure")]
[FormValueRequired("credentials")]
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> SaveCredentials(ConfigurationModel model)
{
if (!ModelState.IsValid)
return await Configure();
if (!model.ClientId?.Equals(_zettleSettings.ClientId) ?? true)
{
//credentials are changed
await _zettleRecordService.ClearRecordsAsync();
_zettleSettings.WebhookUrl = string.Empty;
_zettleSettings.WebhookKey = string.Empty;
_zettleSettings.ImportId = string.Empty;
if (ZettleService.IsConfigured(_zettleSettings))
{
if (_zettleSettings.DisconnectOnUninstall)
await _zettleService.DisconnectAsync();
else if (!string.IsNullOrEmpty(_zettleSettings.WebhookUrl))
await _zettleService.DeleteWebhookAsync();
}
}
_zettleSettings.ClientId = model.ClientId;
_zettleSettings.ApiKey = model.ApiKey;
_zettleSettings.DisconnectOnUninstall = model.DisconnectOnUninstall;
await _settingService.SaveSettingAsync(_zettleSettings);
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Plugins.Saved"));
return await Configure();
}
[HttpPost, ActionName("Configure")]
[FormValueRequired("sync")]
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> SaveSync(ConfigurationModel model)
{
if (!ModelState.IsValid)
return await Configure();
_zettleSettings.AutoSyncEnabled = model.AutoSyncEnabled;
_zettleSettings.AutoSyncPeriod = model.AutoSyncPeriod;
_zettleSettings.DeleteBeforeImport = model.DeleteBeforeImport;
_zettleSettings.SyncEnabled = model.SyncEnabled;
_zettleSettings.PriceSyncEnabled = model.PriceSyncEnabled;
_zettleSettings.ImageSyncEnabled = model.ImageSyncEnabled;
_zettleSettings.InventoryTrackingEnabled = model.InventoryTrackingEnabled;
_zettleSettings.DefaultTaxEnabled = model.DefaultTaxEnabled;
_zettleSettings.DiscountSyncEnabled = model.DiscountSyncEnabled;
await _settingService.SaveSettingAsync(_zettleSettings);
var scheduleTask = await _scheduleTaskService.GetTaskByTypeAsync(ZettleDefaults.SynchronizationTask.Type);
if (scheduleTask is not null)
{
if (!scheduleTask.Enabled && _zettleSettings.AutoSyncEnabled)
scheduleTask.LastEnabledUtc = DateTime.UtcNow;
scheduleTask.Enabled = _zettleSettings.AutoSyncEnabled;
scheduleTask.Seconds = _zettleSettings.AutoSyncPeriod * 60;
await _scheduleTaskService.UpdateTaskAsync(scheduleTask);
}
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Plugins.Saved"));
return await Configure();
}
[HttpPost, ActionName("Configure")]
[FormValueRequired("revoke")]
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> RevokeAccess()
{
if (!ZettleService.IsConfigured(_zettleSettings))
return await Configure();
if (!string.IsNullOrEmpty(_zettleSettings.WebhookUrl))
await _zettleService.DeleteWebhookAsync();
var (_, error) = await _zettleService.DisconnectAsync();
if (!string.IsNullOrEmpty(error))
{
var locale = await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Configuration.Error");
var errorMessage = string.Format(locale, error, Url.Action("List", "Log"));
_notificationService.ErrorNotification(errorMessage, false);
return await Configure();
}
await _zettleRecordService.ClearRecordsAsync();
_zettleSettings.ClientId = string.Empty;
_zettleSettings.ApiKey = string.Empty;
_zettleSettings.WebhookUrl = string.Empty;
_zettleSettings.WebhookKey = string.Empty;
_zettleSettings.ImportId = string.Empty;
await _settingService.SaveSettingAsync(_zettleSettings);
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Plugins.Misc.Zettle.Credentials.AccessRevoked"));
return await Configure();
}
#endregion
#region Synchronization
[HttpPost]
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> SyncRecordList(SyncRecordSearchModel searchModel)
{
var records = await _zettleRecordService.GetAllRecordsAsync(productOnly: true,
pageIndex: searchModel.Page - 1, pageSize: searchModel.PageSize);
var products = await _productService.GetProductsByIdsAsync(records.Select(record => record.ProductId).Distinct().ToArray());
var model = await new SyncRecordListModel().PrepareToGridAsync(searchModel, records, () =>
{
return records.SelectAwait(async record => new SyncRecordModel
{
Id = record.Id,
Active = record.Active,
ProductId = record.ProductId,
ProductName = products.FirstOrDefault(product => product.Id == record.ProductId)?.Name ?? "Not found",
PriceSyncEnabled = record.PriceSyncEnabled,
ImageSyncEnabled = record.ImageSyncEnabled,
InventoryTrackingEnabled = record.InventoryTrackingEnabled,
UpdatedDate = record.UpdatedOnUtc.HasValue
? await _dateTimeHelper.ConvertToUserTimeAsync(record.UpdatedOnUtc.Value, DateTimeKind.Utc)
: null
});
});
return Json(model);
}
[HttpPost]
[CheckPermission(StandardPermission.Configuration.MANAGE_PLUGINS)]
public async Task<IActionResult> SyncRecordUpdate(SyncRecordModel model)
{
var productRecord = await _zettleRecordService.GetRecordByIdAsync(model.Id)
?? throw new ArgumentException("No | ZettleAdminController |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Client/AuthDtos.cs | {
"start": 35729,
"end": 35912
} | public class ____ : IGet, IReturn<AdminGetJobProgressResponse>
{
[ValidateGreaterThan(0)]
public long Id { get; set; }
public int? LogStart { get; set; }
}
| AdminGetJobProgress |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 122539,
"end": 122756
} | public class ____
{
public int Id { get; set; }
public RelatedEntity565 ParentEntity { get; set; }
public IEnumerable<RelatedEntity567> ChildEntities { get; set; }
}
| RelatedEntity566 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.