language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
GtkSharp__GtkSharp
Source/Samples/Sections/Widgets/SwitchSection.cs
{ "start": 221, "end": 644 }
class ____ : ListSection { public SwitchSection() { AddItem(CreateSwitchButton()); } public (string, Widget) CreateSwitchButton() { var btn = new Switch(); btn.ButtonReleaseEvent += (o, args) => ApplicationOutput.WriteLine(o, $"Switch is now: {!btn.Active}"); return ("Switch:", btn); } } }
SwitchSection
csharp
DuendeSoftware__IdentityServer
bff/performance/Bff.Performance/TestClient.cs
{ "start": 248, "end": 3930 }
public class ____(Uri baseAddress, CookieHandler cookies, HttpMessageHandler handler) { public HttpClient Client = new(handler) { BaseAddress = baseAddress }; public void ClearCookies() => cookies.ClearCookies(); public static TestClient Create(Uri baseAddress, CookieContainer? cookies = null) { var inner = new SocketsHttpHandler { // We need to disable cookies and follow redirects // because we do this manually (see below). UseCookies = false, AllowAutoRedirect = false }; var cookieHandler = new CookieHandler(inner, cookies); var handler = new AutoFollowRedirectHandler((_) => { }) { InnerHandler = cookieHandler }; return new TestClient(baseAddress, cookieHandler, handler); } public Task<HttpResponseMessage> GetAsync(string path, Dictionary<string, string>? headers = null, CancellationToken ct = default) { var request = BuildRequest(HttpMethod.Get, path, headers); return Client.SendAsync(request); } public Task<HttpResponseMessage> PostAsync(string path, object? body, Dictionary<string, string>? headers = null, CancellationToken ct = default) { var request = BuildRequest(HttpMethod.Post, path, headers); request.Content = JsonContent.Create(body); return Client.SendAsync(request); } public Task<HttpResponseMessage> PostAsync<T>(Uri path, T body, Dictionary<string, string>? headers = null, CancellationToken ct = default) where T : HttpContent { var request = BuildRequest(HttpMethod.Post, path.ToString(), headers); request.Content = body; return Client.SendAsync(request); } private static HttpRequestMessage BuildRequest(HttpMethod httpMethod, string path, Dictionary<string, string>? headers = null) { var request = new HttpRequestMessage(httpMethod, path); if (headers == null) { request.Headers.Add("x-csrf", "1"); } else { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } return request; } public async Task<HttpResponseMessage> TriggerLogin(string userName = "alice", string password = "alice", CancellationToken ct = default) => await GetAsync("/bff/login"); public async Task<HttpResponseMessage> TriggerLogout() { // To trigger a logout, we need the logout claim var userClaims = await GetUserClaims(); var logoutLink = userClaims.FirstOrDefault(x => x.Type == "bff:logout_url") ?? throw new InvalidOperationException("Failed to find logout link claim"); return await GetAsync(logoutLink.Value.ToString()!); } public async Task<UserClaim[]> GetUserClaims() { var userClaimsString = await GetStringAsync("/bff/user"); var userClaims = JsonSerializer.Deserialize<UserClaim[]>(userClaimsString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; return userClaims; } private async Task<string> GetStringAsync(string path) { var response = await GetAsync(path); if (!response.IsSuccessStatusCode) { throw new InvalidOperationException($"Failed to get string from {path}. Status code: {response.StatusCode}"); } return await response.Content.ReadAsStringAsync(); } public async Task<HttpResponseMessage> InvokeApi(string url) => await GetAsync(url);
TestClient
csharp
AvaloniaUI__Avalonia
src/Avalonia.X11/X11Structs.cs
{ "start": 38962, "end": 39329 }
internal enum ____ { InputHint = (1 << 0), StateHint = (1 << 1), IconPixmapHint = (1 << 2), IconWindowHint = (1 << 3), IconPositionHint = (1 << 4), IconMaskHint = (1 << 5), WindowGroupHint = (1 << 6), AllHints = (InputHint | StateHint | IconPixmapHint | IconWindowHint | IconPositionHint | IconMaskHint | WindowGroupHint) }
XWMHintsFlags
csharp
microsoft__semantic-kernel
dotnet/src/InternalUtilities/planning/PlannerInstrumentation.cs
{ "start": 875, "end": 1205 }
record ____ creation duration.</summary> private static readonly Histogram<double> s_createPlanDuration = s_meter.CreateHistogram<double>( name: "semantic_kernel.planning.create_plan.duration", unit: "s", description: "Duration time of plan creation."); /// <summary><see cref="Histogram{T}"/> to
plan
csharp
dotnet__aspire
tests/Aspire.Hosting.Tests/Eventing/DistributedApplicationBuilderEventingTests.cs
{ "start": 12771, "end": 12843 }
public class ____ : IDistributedApplicationEvent { }
DummyEvent
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Chat/RcsTransportConfiguration.cs
{ "start": 304, "end": 4657 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal RcsTransportConfiguration() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int MaxAttachmentCount { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.MaxAttachmentCount is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.MaxAttachmentCount"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int MaxFileSizeInKilobytes { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.MaxFileSizeInKilobytes is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.MaxFileSizeInKilobytes"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int MaxGroupMessageSizeInKilobytes { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.MaxGroupMessageSizeInKilobytes is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.MaxGroupMessageSizeInKilobytes"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int MaxMessageSizeInKilobytes { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.MaxMessageSizeInKilobytes is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.MaxMessageSizeInKilobytes"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int MaxRecipientCount { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.MaxRecipientCount is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.MaxRecipientCount"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public int WarningFileSizeInKilobytes { get { throw new global::System.NotImplementedException("The member int RcsTransportConfiguration.WarningFileSizeInKilobytes is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20RcsTransportConfiguration.WarningFileSizeInKilobytes"); } } #endif // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.MaxAttachmentCount.get // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.MaxMessageSizeInKilobytes.get // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.MaxGroupMessageSizeInKilobytes.get // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.MaxRecipientCount.get // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.MaxFileSizeInKilobytes.get // Forced skipping of method Windows.ApplicationModel.Chat.RcsTransportConfiguration.WarningFileSizeInKilobytes.get } }
RcsTransportConfiguration
csharp
grpc__grpc-dotnet
examples/Container/Frontend/Balancer/BalancerConfiguration.cs
{ "start": 694, "end": 1101 }
public class ____ { public event EventHandler? Updated; public LoadBalancerName LoadBalancerPolicyName { get; private set; } = LoadBalancerName.PickFirst; public void Update(LoadBalancerName loadBalancerPolicyName) { LoadBalancerPolicyName = loadBalancerPolicyName; Updated?.Invoke(this, EventArgs.Empty); } }
BalancerConfiguration
csharp
dotnet__aspire
tests/Aspire.Hosting.Tests/Dashboard/DashboardResourceTests.cs
{ "start": 28269, "end": 28546 }
private sealed class ____ : IDashboardEndpointProvider { public Task<string> GetResourceServiceUriAsync(CancellationToken cancellationToken = default) { return Task.FromResult("http://localhost:5000"); } } }
MockDashboardEndpointProvider
csharp
microsoft__semantic-kernel
dotnet/src/InternalUtilities/src/Diagnostics/UnreachableException.cs
{ "start": 277, "end": 452 }
class ____ is (sometimes) never instantiated. /// <summary> /// Exception thrown when the program executes an instruction that was thought to be unreachable. /// </summary>
that
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 244877, "end": 245097 }
public class ____ { public int Id { get; set; } public RelatedEntity1127 ParentEntity { get; set; } public IEnumerable<RelatedEntity1129> ChildEntities { get; set; } }
RelatedEntity1128
csharp
ShareX__ShareX
ShareX.HelpersLib/UpdateChecker/UpdateMessageBox.cs
{ "start": 1150, "end": 4874 }
public partial class ____ : Form { public static bool IsOpen { get; private set; } public bool ActivateWindow { get; private set; } protected override bool ShowWithoutActivation => !ActivateWindow; public UpdateMessageBox(UpdateChecker updateChecker, bool activateWindow = true) { ActivateWindow = activateWindow; InitializeComponent(); ShareXResources.ApplyTheme(this); if (!ActivateWindow) { WindowState = FormWindowState.Minimized; NativeMethods.FlashWindowEx(this, 10); } Text = Resources.UpdateMessageBox_UpdateMessageBox_update_is_available; StringBuilder sbText = new StringBuilder(); if (updateChecker.IsPortable) { sbText.AppendLine(Helpers.SafeStringFormat(Resources.UpdateMessageBox_UpdateMessageBox_Portable, Application.ProductName)); } else { sbText.AppendLine(Helpers.SafeStringFormat(Resources.UpdateMessageBox_UpdateMessageBox_, Application.ProductName)); } sbText.AppendLine(); sbText.Append(Resources.UpdateMessageBox_UpdateMessageBox_CurrentVersion); sbText.Append(": "); sbText.Append(updateChecker.CurrentVersion); sbText.AppendLine(); sbText.Append(Resources.UpdateMessageBox_UpdateMessageBox_LatestVersion); sbText.Append(": "); sbText.Append(updateChecker.LatestVersion); if (updateChecker.IsDev) sbText.Append(" Dev"); if (updateChecker is GitHubUpdateChecker githubUpdateChecker && githubUpdateChecker.IsPreRelease) sbText.Append(" (Pre-release)"); lblText.Text = sbText.ToString(); lblViewChangelog.Visible = !updateChecker.IsDev; } public static DialogResult Start(UpdateChecker updateChecker, bool activateWindow = true) { DialogResult result = DialogResult.None; if (updateChecker != null && updateChecker.Status == UpdateStatus.UpdateAvailable) { IsOpen = true; try { using (UpdateMessageBox messageBox = new UpdateMessageBox(updateChecker, activateWindow)) { result = messageBox.ShowDialog(); } if (result == DialogResult.Yes) { updateChecker.DownloadUpdate(); } } finally { IsOpen = false; } } return result; } private void UpdateMessageBox_Shown(object sender, EventArgs e) { if (ActivateWindow) { this.ForceActivate(); } } private void UpdateMessageBox_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.Cancel && e.CloseReason == CloseReason.UserClosing) { DialogResult = DialogResult.No; } } private void lblViewChangelog_Click(object sender, EventArgs e) { URLHelpers.OpenURL(Links.Changelog); } private void btnYes_MouseClick(object sender, MouseEventArgs e) { DialogResult = DialogResult.Yes; Close(); } private void btnNo_MouseClick(object sender, MouseEventArgs e) { DialogResult = DialogResult.No; Close(); } } }
UpdateMessageBox
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Acceptance.Specs/FormattingCallsWhenThrowingReceivedCallsExceptions.cs
{ "start": 5665, "end": 6068 }
public class ____ : Context { protected int _ignored; protected override void ExpectedCall() { _ignored = Sample.Received().AProperty; } [Test] public void Should_list_expected_property_get() { ExceptionMessageContains(ExpectedCallMessagePrefix + "AProperty"); } }
When_checking_call_to_a_property_getter
csharp
grpc__grpc-dotnet
test/Grpc.Net.Client.Tests/Balancer/SubchannelsLoadBalancerTests.cs
{ "start": 5477, "end": 6099 }
class ____ : ISubchannelTransport { public void Dispose() { } public DnsEndPoint? CurrentEndPoint { get; } public TimeSpan? ConnectTimeout { get; } public TransportStatus TransportStatus { get; } public ValueTask<Stream> GetStreamAsync(DnsEndPoint endPoint, CancellationToken cancellationToken) { return ValueTask.FromResult<Stream>(new MemoryStream()); } public ValueTask<ConnectResult> TryConnectAsync(ConnectContext context, int attempt) { return ValueTask.FromResult(ConnectResult.Success); } public void Disconnect() { } } #endif
CustomSubchannelTransport
csharp
dotnet__machinelearning
tools-local/Microsoft.ML.InternalCodeAnalyzer/NameAnalyzer.cs
{ "start": 478, "end": 869 }
internal enum ____ { UnderScoreCamelCased, // For example, _myPrivateField CamelCased, // For example, myAwesomeParameter PascalCased, // For example, AwesomeClass IPascalCased, // For example, IEnumerableStuff TPascalCased, // For example, TDictArg } [DiagnosticAnalyzer(LanguageNames.CSharp)]
NameType
csharp
AutoMapper__AutoMapper
src/UnitTests/MappingInheritance/IgnoreShouldBeInherited.cs
{ "start": 5573, "end": 6210 }
class ____ : Bar { } protected override MapperConfiguration CreateConfiguration() => new(c => { c.CreateMap<object, Foo>().ForMember(d => d.FooText, o => o.Ignore()).ForMember(d => d.Text, o => o.MapFrom(s=>"")); c.CreateMap<Bar, Foo>().ForMember(d => d.FooText, o => o.MapFrom(s => s.FooText)).IncludeBase<object, Foo>(); c.CreateMap<Boo, Foo>().ForMember(d => d.FooText, o => o.Ignore()).IncludeBase<Bar, Foo>(); }); [Fact] public void Should_not_map() { var dest = Map<Foo>(new Boo { FooText = "hi" }); dest.FooText.ShouldBeNull(); dest.Text.ShouldBe(""); } }
Boo
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Spatial/Indexing/GeoPointFieldIndexHandler.cs
{ "start": 104, "end": 1005 }
public class ____ : ContentFieldIndexHandler<GeoPointField> { public override Task BuildIndexAsync(GeoPointField field, BuildFieldIndexContext context) { var options = context.Settings.ToOptions(); ContentItemDocumentIndex.GeoPoint value = null; if (field.Longitude != null && field.Latitude != null) { value = new ContentItemDocumentIndex.GeoPoint { Longitude = (decimal)field.Longitude, Latitude = (decimal)field.Latitude, }; } foreach (var key in context.Keys) { context.DocumentIndex.Set(key, value, options); } // Also index as "Location" to be able to search on multiple Content Types context.DocumentIndex.Set("Location", value, DocumentIndexOptions.Store); return Task.CompletedTask; } }
GeoPointFieldIndexHandler
csharp
unoplatform__uno
src/Uno.UI/Controls/BindableImageView.Android.cs
{ "start": 17212, "end": 17670 }
private class ____ : ScaleGestureDetector.SimpleOnScaleGestureListener { private BindableImageView _parent; public ScaleListener(BindableImageView parent) { _parent = parent; } public override bool OnScaleBegin(ScaleGestureDetector detector) { _parent.OnScaleBegin(); return true; } public override bool OnScale(ScaleGestureDetector detector) { _parent.OnScale(detector); return true; } }
ScaleListener
csharp
dotnet__efcore
src/EFCore/Metadata/IConventionElementType.cs
{ "start": 373, "end": 766 }
interface ____ used during model creation and allows the metadata to be modified. /// Once the model is built, <see cref="IElementType" /> represents a read-only view of the same metadata. /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information and examples. /// </para> /// </remarks>
is
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32/Interop/UnmanagedMethods.cs
{ "start": 83557, "end": 83745 }
public enum ____ { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 }
PROCESS_DPI_AWARENESS
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Models/Catalog/SpecificationAttributeModel.cs
{ "start": 1084, "end": 1625 }
public class ____ : BaseEntityModel { [GrandResourceDisplayName("Admin.Catalog.Attributes.SpecificationAttributes.UsedByProducts.Product")] public string ProductName { get; set; } [GrandResourceDisplayName("Admin.Catalog.Attributes.SpecificationAttributes.UsedByProducts.OptionName")] public string OptionName { get; set; } [GrandResourceDisplayName("Admin.Catalog.Attributes.SpecificationAttributes.UsedByProducts.Published")] public bool Published { get; set; } } }
UsedByProductModel
csharp
dotnet__machinelearning
src/Microsoft.ML.TimeSeries/STL/Loess.cs
{ "start": 6111, "end": 6297 }
class ____ used to store the parameters which are needed for lowess algorithm. /// The name of these constansts are compliant with the original terms in paper. /// </summary>
is
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.Including.cs
{ "start": 4540, "end": 5810 }
public class ____ { [UsedImplicitly] public string Name { get; set; } } [Fact] public void When_including_a_property_using_an_expression_it_should_evaluate_it_from_the_root() { // Arrange var list1 = new List<CustomType> { new() { Name = "A" }, new() { Name = "B" } }; var list2 = new List<CustomType> { new() { Name = "C" }, new() { Name = "D" } }; var objectA = new ClassA { ListOfCustomTypes = list1 }; var objectB = new ClassA { ListOfCustomTypes = list2 }; // Act Action act = () => objectA.Should().BeEquivalentTo(objectB, options => options.Including(x => x.ListOfCustomTypes)); // Assert act.Should().Throw<XunitException>().WithMessage("*C*but*A*D*but*B*"); }
CustomType
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Types/Descriptors/Configurations/TypeSystemConfiguration.cs
{ "start": 260, "end": 5040 }
public abstract class ____ : ITypeSystemConfiguration { private List<TypeDependency>? _dependencies; private List<ITypeSystemConfigurationTask>? _tasks; private IFeatureCollection? _features; /// <summary> /// Gets or sets the name of the type system member. /// </summary> public virtual string Name { get; set => field = string.Intern(value.EnsureGraphQLName()); } = string.Empty; /// <summary> /// Gets or sets the description of the type system member. /// </summary> public string? Description { get; set; } /// <summary> /// Gets or sets a name to which this definition is bound to. /// </summary> public string? BindTo { get; set; } /// <summary> /// Defines whether the <see cref="Configurations"/>> have been applied or not. /// </summary> public bool ConfigurationsAreApplied { get; set; } /// <summary> /// Get access to context data that are copied to the type /// and can be used for customizations. /// </summary> public virtual IFeatureCollection Features => _features ??= new FeatureCollection(); /// <summary> /// Gets access to additional type dependencies. /// </summary> public IList<TypeDependency> Dependencies => _dependencies ??= []; /// <summary> /// Defines if this type has dependencies. /// </summary> public bool HasDependencies => _dependencies is { Count: > 0 }; /// <summary> /// Gets configurations that shall be applied at a later point. /// </summary> public IList<ITypeSystemConfigurationTask> Tasks => _tasks ??= []; /// <summary> /// Defines if this type has configurations. /// </summary> public bool HasTasks => _tasks is { Count: > 0 }; /// <summary> /// Gets lazy configuration of this definition and all dependent definitions. /// </summary> public virtual IEnumerable<ITypeSystemConfigurationTask> GetTasks() { if (_tasks is null) { return []; } return _tasks; } /// <summary> /// Gets access to additional type dependencies. /// </summary> public IReadOnlyList<TypeDependency> GetDependencies() { if (_dependencies is null) { return []; } return _dependencies; } /// <summary> /// Get access to features that are copied to the type /// and can be used for customizations. /// </summary> public IFeatureCollection GetFeatures() => _features ?? FeatureCollection.Empty; /// <summary> /// Ensures that a feature collection is created. /// </summary> public void TouchFeatures() => _features ??= new FeatureCollection(); protected void CopyTo(TypeSystemConfiguration target) { if (_dependencies?.Count > 0) { target._dependencies = [.. _dependencies]; } if (_tasks?.Count > 0) { target._tasks = []; foreach (var configuration in _tasks) { target._tasks.Add(configuration.Copy(target)); } } if (_features?.IsEmpty is false) { target._features = new FeatureCollection(); foreach (var item in _features) { target._features[item.Key] = item.Value; } } target.Name = Name; target.Description = Description; target.ConfigurationsAreApplied = ConfigurationsAreApplied; target.BindTo = BindTo; } protected void MergeInto(TypeSystemConfiguration target) { if (_dependencies?.Count > 0) { target._dependencies ??= []; target._dependencies.AddRange(_dependencies); } if (_tasks?.Count > 0) { target._tasks ??= []; foreach (var configuration in _tasks) { target._tasks.Add(configuration.Copy(target)); } } if (_features?.IsEmpty is false) { target._features ??= new FeatureCollection(); foreach (var item in _features) { target._features[item.Key] = item.Value; } } if (target.Description is null && Description is not null) { target.Description = Description; } if (BindTo is not null) { target.BindTo = BindTo; } if (!target.ConfigurationsAreApplied) { target.ConfigurationsAreApplied = ConfigurationsAreApplied; } } public override string ToString() => GetType().Name + ": " + Name; }
TypeSystemConfiguration
csharp
Humanizr__Humanizer
src/Humanizer/FluentDate/OnDate.Days.cs
{ "start": 59830, "end": 65805 }
public class ____ { /// <summary> /// The nth day of November of the current year /// </summary> public static DateOnly The(int dayNumber) => new(DateTime.Now.Year, 11, dayNumber); /// <summary> /// The 1st day of November of the current year /// </summary> public static DateOnly The1st => new(DateTime.Now.Year, 11, 1); /// <summary> /// The 2nd day of November of the current year /// </summary> public static DateOnly The2nd => new(DateTime.Now.Year, 11, 2); /// <summary> /// The 3rd day of November of the current year /// </summary> public static DateOnly The3rd => new(DateTime.Now.Year, 11, 3); /// <summary> /// The 4th day of November of the current year /// </summary> public static DateOnly The4th => new(DateTime.Now.Year, 11, 4); /// <summary> /// The 5th day of November of the current year /// </summary> public static DateOnly The5th => new(DateTime.Now.Year, 11, 5); /// <summary> /// The 6th day of November of the current year /// </summary> public static DateOnly The6th => new(DateTime.Now.Year, 11, 6); /// <summary> /// The 7th day of November of the current year /// </summary> public static DateOnly The7th => new(DateTime.Now.Year, 11, 7); /// <summary> /// The 8th day of November of the current year /// </summary> public static DateOnly The8th => new(DateTime.Now.Year, 11, 8); /// <summary> /// The 9th day of November of the current year /// </summary> public static DateOnly The9th => new(DateTime.Now.Year, 11, 9); /// <summary> /// The 10th day of November of the current year /// </summary> public static DateOnly The10th => new(DateTime.Now.Year, 11, 10); /// <summary> /// The 11th day of November of the current year /// </summary> public static DateOnly The11th => new(DateTime.Now.Year, 11, 11); /// <summary> /// The 12th day of November of the current year /// </summary> public static DateOnly The12th => new(DateTime.Now.Year, 11, 12); /// <summary> /// The 13th day of November of the current year /// </summary> public static DateOnly The13th => new(DateTime.Now.Year, 11, 13); /// <summary> /// The 14th day of November of the current year /// </summary> public static DateOnly The14th => new(DateTime.Now.Year, 11, 14); /// <summary> /// The 15th day of November of the current year /// </summary> public static DateOnly The15th => new(DateTime.Now.Year, 11, 15); /// <summary> /// The 16th day of November of the current year /// </summary> public static DateOnly The16th => new(DateTime.Now.Year, 11, 16); /// <summary> /// The 17th day of November of the current year /// </summary> public static DateOnly The17th => new(DateTime.Now.Year, 11, 17); /// <summary> /// The 18th day of November of the current year /// </summary> public static DateOnly The18th => new(DateTime.Now.Year, 11, 18); /// <summary> /// The 19th day of November of the current year /// </summary> public static DateOnly The19th => new(DateTime.Now.Year, 11, 19); /// <summary> /// The 20th day of November of the current year /// </summary> public static DateOnly The20th => new(DateTime.Now.Year, 11, 20); /// <summary> /// The 21st day of November of the current year /// </summary> public static DateOnly The21st => new(DateTime.Now.Year, 11, 21); /// <summary> /// The 22nd day of November of the current year /// </summary> public static DateOnly The22nd => new(DateTime.Now.Year, 11, 22); /// <summary> /// The 23rd day of November of the current year /// </summary> public static DateOnly The23rd => new(DateTime.Now.Year, 11, 23); /// <summary> /// The 24th day of November of the current year /// </summary> public static DateOnly The24th => new(DateTime.Now.Year, 11, 24); /// <summary> /// The 25th day of November of the current year /// </summary> public static DateOnly The25th => new(DateTime.Now.Year, 11, 25); /// <summary> /// The 26th day of November of the current year /// </summary> public static DateOnly The26th => new(DateTime.Now.Year, 11, 26); /// <summary> /// The 27th day of November of the current year /// </summary> public static DateOnly The27th => new(DateTime.Now.Year, 11, 27); /// <summary> /// The 28th day of November of the current year /// </summary> public static DateOnly The28th => new(DateTime.Now.Year, 11, 28); /// <summary> /// The 29th day of November of the current year /// </summary> public static DateOnly The29th => new(DateTime.Now.Year, 11, 29); /// <summary> /// The 30th day of November of the current year /// </summary> public static DateOnly The30th => new(DateTime.Now.Year, 11, 30); } /// <summary> /// Provides fluent date accessors for December /// </summary>
November
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs
{ "start": 64737, "end": 64848 }
public static class ____ { public static Book GetBook() => new Book(); }
BookQuery
csharp
dotnet__orleans
src/api/Orleans.Core/Orleans.Core.cs
{ "start": 56130, "end": 56629 }
partial class ____ { public const long RING_SIZE = 4294967296L; public static IRingRange CreateFullRange() { throw null; } public static IRingRange CreateRange(System.Collections.Generic.List<IRingRange> inRanges) { throw null; } public static IRingRange CreateRange(uint begin, uint end) { throw null; } public static System.Collections.Generic.IEnumerable<ISingleRange> GetSubRanges(IRingRange range) { throw null; } } public static
RangeFactory
csharp
dotnet__orleans
src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs
{ "start": 37334, "end": 39305 }
public partial class ____ : Grain, ITransactionCoordinatorGrain, IGrainWithGuidKey, IGrain, Runtime.IAddressable { public System.Threading.Tasks.Task AddAndThrow(ITransactionTestGrain grain, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainAdd(ITransactionCommitterTestGrain committer, Abstractions.ITransactionCommitOperation<IRemoteCommitService> operation, System.Collections.Generic.List<ITransactionTestGrain> grains, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainAdd(System.Collections.Generic.List<ITransactionTestGrain> grains, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainAddAndThrow(System.Collections.Generic.List<ITransactionTestGrain> throwGrains, System.Collections.Generic.List<ITransactionTestGrain> grains, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainDouble(System.Collections.Generic.List<ITransactionTestGrain> grains) { throw null; } public System.Threading.Tasks.Task MultiGrainDoubleByRWRW(System.Collections.Generic.List<ITransactionTestGrain> grains, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainDoubleByWRWR(System.Collections.Generic.List<ITransactionTestGrain> grains, int numberToAdd) { throw null; } public System.Threading.Tasks.Task MultiGrainSet(System.Collections.Generic.List<ITransactionTestGrain> grains, int newValue) { throw null; } public System.Threading.Tasks.Task MultiGrainSetBit(System.Collections.Generic.List<Correctnesss.ITransactionalBitArrayGrain> grains, int bitIndex) { throw null; } public System.Threading.Tasks.Task OrphanCallTransaction(ITransactionTestGrain grain) { throw null; } public System.Threading.Tasks.Task UpdateViolated(ITransactionTestGrain grain, int numberToAdd) { throw null; } } [GenerateSerializer]
TransactionCoordinatorGrain
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore/Shell/Removing/ShellRemovalManager.cs
{ "start": 250, "end": 7135 }
public class ____ : IShellRemovalManager { private readonly IShellHost _shellHost; private readonly IShellContextFactory _shellContextFactory; private readonly IEnumerable<IShellRemovingHandler> _shellRemovingHandlers; protected readonly IStringLocalizer S; private readonly ILogger _logger; public ShellRemovalManager( IShellHost shellHost, IShellContextFactory shellContextFactory, IEnumerable<IShellRemovingHandler> shellRemovingHandlers, IStringLocalizer<ShellRemovalManager> localizer, ILogger<ShellRemovalManager> logger) { _shellHost = shellHost; _shellContextFactory = shellContextFactory; _shellRemovingHandlers = shellRemovingHandlers; S = localizer; _logger = logger; } public async Task<ShellRemovingContext> RemoveAsync(ShellSettings shellSettings, bool localResourcesOnly = false) { var context = new ShellRemovingContext { ShellSettings = shellSettings, LocalResourcesOnly = localResourcesOnly, }; if (shellSettings.IsDefaultShell()) { context.ErrorMessage = S["The tenant should not be the '{0}' tenant.", ShellSettings.DefaultShellName]; return context; } // A disabled tenant may be still in use in at least one active scope. if (!shellSettings.IsRemovable() || _shellHost.IsShellActive(shellSettings)) { context.ErrorMessage = S["The tenant '{0}' should be 'Disabled' or 'Uninitialized'.", shellSettings.Name]; return context; } // Check if the tenant is not 'Uninitialized' and that all resources should be removed. if (shellSettings.IsDisabled() && !context.LocalResourcesOnly) { // Create an isolated shell context composed of all features that have been installed. ShellContext maximumContext = null; try { maximumContext = await _shellContextFactory.CreateMaximumContextAsync(shellSettings); } catch (Exception ex) { _logger.LogError( ex, "Failed to create a 'ShellContext' before removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to create a 'ShellContext' before removing the tenant."]; context.Error = ex; return context; } await using var shellContext = maximumContext; (var locker, var locked) = await shellContext.TryAcquireShellRemovingLockAsync(); if (!locked) { _logger.LogError( "Failed to acquire a lock before executing the tenant handlers while removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to acquire a lock before executing the tenant handlers."]; return context; } await using var acquiredLock = locker; await (await shellContext.CreateScopeAsync()).UsingServiceScopeAsync(async scope => { // Execute tenant level removing handlers (singletons or scoped) in a reverse order. // If feature A depends on feature B, the activating handler of feature B should run // before the handler of the dependent feature A, but on removing the resources of // feature B should be removed after the resources of the dependent feature A. var tenantHandlers = scope.ServiceProvider.GetServices<IModularTenantEvents>().Reverse(); foreach (var handler in tenantHandlers) { try { await handler.RemovingAsync(context); if (!context.Success) { break; } } catch (Exception ex) { var type = handler.GetType().FullName; _logger.LogError( ex, "Failed to execute the tenant handler '{TenantHandler}' while removing the tenant '{TenantName}'.", type, shellSettings.Name); context.ErrorMessage = S["Failed to execute the tenant handler '{0}'.", type]; context.Error = ex; break; } } }); } if (_shellHost.TryGetSettings(ShellSettings.DefaultShellName, out var defaultSettings)) { // Use the default shell context to execute the host level removing handlers. var shellContext = await _shellHost.GetOrCreateShellContextAsync(defaultSettings); (var locker, var locked) = await shellContext.TryAcquireShellRemovingLockAsync(); if (!locked) { _logger.LogError( "Failed to acquire a lock before executing the host handlers while removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to acquire a lock before executing the host handlers."]; // If only local resources should be removed while syncing tenants. if (context.LocalResourcesOnly) { // Indicates that we can retry in a next loop. context.FailedOnLockTimeout = true; } return context; } await using var acquiredLock = locker; // Execute host level removing handlers in a reverse order. foreach (var handler in _shellRemovingHandlers.Reverse()) { try { await handler.RemovingAsync(context); if (!context.Success) { break; } } catch (Exception ex) { var type = handler.GetType().FullName; _logger.LogError( ex, "Failed to execute the host handler '{HostHandler}' while removing the tenant '{TenantName}'.", type, shellSettings.Name); context.ErrorMessage = S["Failed to execute the host handler '{0}'.", type]; context.Error = ex; break; } } } return context; } }
ShellRemovalManager
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Auth/FacebookAuthProvider.cs
{ "start": 379, "end": 8962 }
public class ____ : OAuthProvider { public const string Name = "facebook"; public static string Realm = "https://graph.facebook.com/v3.2/"; public static string PreAuthUrl = "https://www.facebook.com/dialog/oauth"; public static string[] DefaultFields = { "id", "name", "first_name", "last_name", "email" }; public string AppId { get => ConsumerKey; set => ConsumerKey = value; } public string AppSecret { get => ConsumerSecret; set => ConsumerSecret = value; } public string[] Permissions { get; set; } public string[] Fields { get; set; } public bool RetrieveUserPicture { get; set; } = true; public override Dictionary<string, string> Meta { get; } = new Dictionary<string, string> { [Keywords.Allows] = Keywords.Embed + "," + Keywords.AccessTokenAuth, }; public FacebookAuthProvider(IAppSettings appSettings) : base(appSettings, Realm, Name, "AppId", "AppSecret") { this.AppId = appSettings.GetString("oauth.facebook.AppId"); this.AppSecret = appSettings.GetString("oauth.facebook.AppSecret"); this.Permissions = appSettings.Get("oauth.facebook.Permissions", TypeConstants.EmptyStringArray); this.Fields = appSettings.Get("oauth.facebook.Fields", DefaultFields); Icon = Svg.ImageSvg("<svg xmlns='http://www.w3.org/2000/svg' fill='currentColor' viewBox='0 0 20 20'><path fill-rule='evenodd' d='M20 10c0-5.523-4.477-10-10-10S0 4.477 0 10c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V10h2.54V7.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V10h2.773l-.443 2.89h-2.33v6.988C16.343 19.128 20 14.991 20 10z' clip-rule='evenodd' /></svg>"); NavItem = new NavItem { Href = "/auth/" + Name, Label = "Sign In with Facebook", Id = "btn-" + Name, ClassName = "btn-social btn-facebook", IconClass = "fab svg-facebook", }; } public override async Task<object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default) { var tokens = Init(authService, ref session, request); var ctx = CreateAuthContext(authService, session, tokens); //Transferring AccessToken/Secret from Mobile/Desktop App to Server if (request?.AccessToken != null) { if (!await AuthHttpGateway.VerifyFacebookAccessTokenAsync(AppId, request.AccessToken, token).ConfigAwait()) return HttpError.Unauthorized("AccessToken is not for App: " + AppId); var isHtml = authService.Request.IsHtml(); var failedResult = await AuthenticateWithAccessTokenAsync(authService, session, tokens, request.AccessToken, token).ConfigAwait(); if (failedResult != null) return ConvertToClientError(failedResult, isHtml); return isHtml ? await authService.Redirect(SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"))).SuccessAuthResultAsync(authService,session).ConfigAwait() : null; //return default AuthenticateResponse } var httpRequest = authService.Request; var error = httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_code"] ?? httpRequest.QueryString["error_description"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"Facebook error callback. {httpRequest.QueryString}"); return authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", error))); } var code = httpRequest.QueryString[Keywords.Code]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = $"{PreAuthUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&scope={string.Join(",", Permissions)}&{Keywords.State}={session.Id}"; await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait(); return authService.Redirect(PreAuthUrlFilter(ctx, preAuthUrl)); } try { var accessTokenUrl = $"{AccessTokenUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&client_secret={AppSecret}&code={code}"; var contents = await AccessTokenUrlFilter(ctx, accessTokenUrl).GetJsonFromUrlAsync(token: token).ConfigAwait(); var authInfo = JsonObject.Parse(contents); var accessToken = authInfo["access_token"]; //Haz Access! return await AuthenticateWithAccessTokenAsync(authService, session, tokens, accessToken, token).ConfigAwait() ?? await authService.Redirect(SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"))).SuccessAuthResultAsync(authService,session).ConfigAwait(); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))); } } //Shouldn't get here return authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "Unknown"))); } protected virtual async Task<object> AuthenticateWithAccessTokenAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken, CancellationToken token=default) { tokens.AccessTokenSecret = accessToken; var json = AuthHttpGateway.DownloadFacebookUserInfo(accessToken, Fields); var authInfo = JsonObject.Parse(json); session.IsAuthenticated = true; return await OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait(); } protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo, CancellationToken token=default) { try { tokens.UserId = authInfo.Get("id"); tokens.UserName = authInfo.Get("id") ?? authInfo.Get("username"); tokens.DisplayName = authInfo.Get("name"); tokens.FirstName = authInfo.Get("first_name"); tokens.LastName = authInfo.Get("last_name"); tokens.Email = authInfo.Get("email"); if (RetrieveUserPicture) { var json = await AuthHttpGateway.DownloadFacebookUserInfoAsync(tokens.AccessTokenSecret, new[]{ "picture" }, token).ConfigAwait(); var obj = JsonObject.Parse(json); var picture = obj.Object("picture"); var data = picture?.Object("data"); if (data != null) { if (data.TryGetValue("url", out var profileUrl)) { tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl.SanitizeOAuthUrl(); if (string.IsNullOrEmpty(userSession.ProfileUrl)) userSession.ProfileUrl = profileUrl.SanitizeOAuthUrl(); } } } userSession.UserAuthName = tokens.Email; } catch (Exception ex) { Log.Error($"Could not retrieve facebook user info for '{tokens.DisplayName}'", ex); } await LoadUserOAuthProviderAsync(userSession, tokens).ConfigAwait(); } public override Task LoadUserOAuthProviderAsync(IAuthSession authSession, IAuthTokens tokens) { if (authSession is AuthUserSession userSession) { userSession.FacebookUserId = tokens.UserId ?? userSession.FacebookUserId; userSession.FacebookUserName = tokens.UserName ?? userSession.FacebookUserName; userSession.DisplayName = tokens.DisplayName ?? userSession.DisplayName; userSession.FirstName = tokens.FirstName ?? userSession.FirstName; userSession.LastName = tokens.LastName ?? userSession.LastName; userSession.PrimaryEmail = tokens.Email ?? userSession.PrimaryEmail ?? userSession.Email; } return Task.CompletedTask; } }
FacebookAuthProvider
csharp
Cysharp__ZLogger
src/ZLogger.Unity/Assets/Tests/FormatTest.cs
{ "start": 207, "end": 10874 }
public class ____ { [Fact] public void FormatLogEntry_CustomMetadata() { using var ms = new MemoryStream(); var sourceCodeHash = Guid.NewGuid().ToString(); var loggerFactory = LoggerFactory.Create(x => x .SetMinimumLevel(LogLevel.Debug) .AddZLoggerStream(ms, options => { var hashProp = JsonEncodedText.Encode("Hash"); options.UseJsonFormatter(formatter => { formatter.AdditionalFormatter = (Utf8JsonWriter writer, in LogInfo _) => { writer.WriteString(hashProp, sourceCodeHash); }; }); })); var logger = loggerFactory.CreateLogger("test"); var tako = 100; var yaki = "あいうえお"; logger.ZLogDebug($"FooBar{tako} NanoNano{yaki}"); logger.LogInformation(""); loggerFactory.Dispose(); using var sr = new StreamReader(new MemoryStream(ms.ToArray()), Encoding.UTF8); var json = sr.ReadLine(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Message").GetString().Should().Be("FooBar100 NanoNanoあいうえお"); doc.GetProperty("tako").GetInt32().Should().Be(100); doc.GetProperty("yaki").GetString().Should().Be("あいうえお"); doc.GetProperty("Hash").GetString().Should().Be(sourceCodeHash); doc.GetProperty("LogLevel").GetString().Should().Be("Debug"); } [Fact] public void FormatLogEntry_ExcludeLogInfoProperties() { var options = new ZLoggerOptions().UseJsonFormatter(formatter => { formatter.IncludeProperties = IncludeProperties.LogLevel | IncludeProperties.Timestamp | IncludeProperties.EventIdValue; }); var processor = new TestProcessor(options); var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var now = DateTime.UtcNow; logger.ZLogInformation(new EventId(1, "TEST"), $"HELLO!"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.TryGetProperty("Message", out _).Should().BeFalse(); doc.GetProperty("LogLevel").GetString().Should().Be("Information"); doc.GetProperty("EventId").GetInt32().Should().Be(1); doc.TryGetProperty("EventIdName", out _).Should().BeFalse(); doc.TryGetProperty("CategoryName", out _).Should().BeFalse(); } [Fact] public void FormatLogEntry_ExcludeAllLogInfo() { var options = new ZLoggerOptions().UseJsonFormatter(formatter => { formatter.IncludeProperties = IncludeProperties.None; }); var processor = new TestProcessor(options); var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); logger.ZLogInformation(new EventId(1, "TEST"), $"HELLO!"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.TryGetProperty("Message", out _).Should().BeFalse(); doc.TryGetProperty("LogLevel", out _).Should().BeFalse(); doc.TryGetProperty("Timestamp", out _).Should().BeFalse(); doc.TryGetProperty("EventId", out _).Should().BeFalse(); doc.TryGetProperty("EventIdName", out _).Should().BeFalse(); doc.TryGetProperty("EventIdName", out _).Should().BeFalse(); doc.TryGetProperty("CategoryName", out _).Should().BeFalse(); } [Fact] public void KeyNameMutator_Lower() { var options = new ZLoggerOptions { IncludeScopes = true }; options.UseJsonFormatter(formatter => { formatter.KeyNameMutator = KeyNameMutator.LowerFirstCharacter; }); var processor = new TestProcessor(options); using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var Tako = 100; var Yaki = "あいうえお"; logger.ZLogDebug($"tako: {Tako} yaki: {Yaki}"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Message").GetString().Should().Be("tako: 100 yaki: あいうえお"); doc.GetProperty("tako").GetInt32().Should().Be(100); doc.GetProperty("yaki").GetString().Should().Be("あいうえお"); } [Fact] public void KeyNameMutatorProp1() { var options = new ZLoggerOptions { IncludeScopes = true }; options.UseJsonFormatter(formatter => { formatter.KeyNameMutator = KeyNameMutator.LastMemberName; }); var processor = new TestProcessor(options); using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var zzz = new { Tako = 100, Yaki = "あいうえお" }; logger.ZLogDebug($"tako: {zzz.Tako} yaki: {zzz.Yaki}"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Message").GetString().Should().Be("tako: 100 yaki: あいうえお"); doc.GetProperty("Tako").GetInt32().Should().Be(100); doc.GetProperty("Yaki").GetString().Should().Be("あいうえお"); } [Fact] public void KeyNameMutatorProp2() { var options = new ZLoggerOptions { IncludeScopes = true }; options.UseJsonFormatter(formatter => { formatter.KeyNameMutator = KeyNameMutator.LastMemberNameUpperFirstCharacter; }); var processor = new TestProcessor(options); using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var zzz = new { tako = 100, yaki = "あいうえお" }; logger.ZLogDebug($"tako: {zzz.tako} yaki: {zzz.yaki}"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Message").GetString().Should().Be("tako: 100 yaki: あいうえお"); doc.GetProperty("Tako").GetInt32().Should().Be(100); doc.GetProperty("Yaki").GetString().Should().Be("あいうえお"); } [Fact] public void NestPayload() { var options = new ZLoggerOptions { IncludeScopes = true }; options.UseJsonFormatter(formatter => { formatter.KeyNameMutator = KeyNameMutator.LastMemberName; formatter.PropertyKeyValuesObjectName = JsonEncodedText.Encode("Payload"); }); var processor = new TestProcessor(options); using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var zzz = new { Tako = 100, Yaki = "あいうえお" }; logger.ZLogDebug($"tako: {zzz.Tako} yaki: {zzz.Yaki}"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Message").GetString().Should().Be("tako: 100 yaki: あいうえお"); doc.GetProperty("Payload").GetProperty("Tako").GetInt32().Should().Be(100); doc.GetProperty("Payload").GetProperty("Yaki").GetString().Should().Be("あいうえお"); } [Fact] public void ConfigureName() { var options = new ZLoggerOptions().UseJsonFormatter(formatter => { formatter.JsonPropertyNames = JsonPropertyNames.Default with { Message = JsonEncodedText.Encode("MMMMMMMMMMMOsage"), LogLevel = JsonEncodedText.Encode("LeVeL5"), Category = JsonEncodedText.Encode("CAT"), Timestamp = JsonEncodedText.Encode("TST"), EventId = JsonEncodedText.Encode("EventIddd"), EventIdName = JsonEncodedText.Encode("EventNAME"), }; formatter.IncludeProperties = IncludeProperties.All; }); var processor = new TestProcessor(options); var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); logger.ZLogInformation(new EventId(1, "TEST"), $"HELLO!"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.TryGetProperty("MMMMMMMMMMMOsage", out _).Should().BeTrue(); doc.TryGetProperty("LeVeL5", out _).Should().BeTrue(); doc.TryGetProperty("TST", out _).Should().BeTrue(); doc.TryGetProperty("EventIddd", out _).Should().BeTrue(); doc.TryGetProperty("EventNAME", out _).Should().BeTrue(); doc.TryGetProperty("CAT", out _).Should().BeTrue(); } [Fact] public void KeyNameMutator_CallMethod() { var options = new ZLoggerOptions { IncludeScopes = true }; options.UseJsonFormatter(formatter => { formatter.KeyNameMutator = KeyNameMutator.LastMemberName; }); var processor = new TestProcessor(options); using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); var Tako = 100; var Yaki = "あいうえお"; var anon = new { Tako, Yaki }; var mc = new MyClass(); logger.ZLogDebug($"tako: {mc.Call(10, anon.Tako)} yaki: {(((mc.Call2(1, 2))))}"); var json = processor.Dequeue(); var doc = JsonDocument.Parse(json).RootElement; doc.GetProperty("Call").GetInt32().Should().Be(110); doc.GetProperty("Call2").GetInt32().Should().Be(3); }
JsonFormatTest
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Serializers/BsonValueSerializerTests.cs
{ "start": 47183, "end": 49939 }
public class ____ { public TestClass() { } public TestClass(BsonJavaScript value) { this.B = value; this.V = value; } public BsonValue B { get; set; } public BsonJavaScript V { get; set; } } [Fact] public void TestNull() { var obj = new TestClass(null); var json = obj.ToJson(writerSettings: new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }); var expected = "{ 'B' : #, 'V' : # }".Replace("#", "{ '_csharpnull' : true }").Replace("'", "\""); Assert.Equal(expected, json); var bson = obj.ToBson(); var rehydrated = BsonSerializer.Deserialize<TestClass>(bson); Assert.Equal(null, rehydrated.B); Assert.Equal(null, rehydrated.V); Assert.True(bson.SequenceEqual(rehydrated.ToBson())); } [Fact] public void TestNotNull() { var obj = new TestClass("this.age === 21"); var json = obj.ToJson(writerSettings: new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }); var expected = "{ 'B' : #, 'V' : # }".Replace("#", "{ '$code' : 'this.age === 21' }").Replace("'", "\""); Assert.Equal(expected, json); var bson = obj.ToBson(); var rehydrated = BsonSerializer.Deserialize<TestClass>(bson); Assert.True(bson.SequenceEqual(rehydrated.ToBson())); } [Fact] public void Equals_null_should_return_false() { var x = new BsonJavaScriptSerializer(); var result = x.Equals(null); result.Should().Be(false); } [Fact] public void Equals_object_should_return_false() { var x = new BsonJavaScriptSerializer(); var y = new object(); var result = x.Equals(y); result.Should().Be(false); } [Fact] public void Equals_self_should_return_true() { var x = new BsonJavaScriptSerializer(); var result = x.Equals(x); result.Should().Be(true); } [Fact] public void Equals_with_equal_fields_should_return_true() { var x = new BsonJavaScriptSerializer(); var y = new BsonJavaScriptSerializer(); var result = x.Equals(y); result.Should().Be(true); } [Fact] public void GetHashCode_should_return_zero() { var x = new BsonJavaScriptSerializer(); var result = x.GetHashCode(); result.Should().Be(0); } }
TestClass
csharp
exceptionless__Exceptionless
src/Exceptionless.Insulation/Configuration/YamlConfigurationFileParser.cs
{ "start": 133, "end": 3277 }
internal class ____ { private readonly Stack<string> _context = new(); private readonly IDictionary<string, string?> _data = new SortedDictionary<string, string?>(StringComparer.OrdinalIgnoreCase); private string? _currentPath; public IDictionary<string, string?> Parse(Stream stream) { _data.Clear(); var yamlStream = new YamlStream(); yamlStream.Load(new StreamReader(stream)); if (!yamlStream.Documents.Any()) return _data; if (!(yamlStream.Documents[0].RootNode is YamlMappingNode mappingNode)) return _data; foreach (var nodePair in mappingNode.Children) { string? context = ((YamlScalarNode)nodePair.Key).Value; if (context is not null) VisitYamlNode(context, nodePair.Value); } return _data; } private void VisitYamlNode(string context, YamlNode node) { switch (node) { case YamlScalarNode scalarNode: VisitYamlScalarNode(context, scalarNode); break; case YamlMappingNode mappingNode: VisitYamlMappingNode(context, mappingNode); break; case YamlSequenceNode sequenceNode: VisitYamlSequenceNode(context, sequenceNode); break; default: throw new ArgumentOutOfRangeException( nameof(node), $"Unsupported YAML node type '{node.GetType().Name} was found. " + $"Path '{_currentPath}', line {node.Start.Line} position {node.Start.Column}."); } } private void VisitYamlScalarNode(string context, YamlScalarNode scalarNode) { EnterContext(context); string? currentKey = _currentPath; if (currentKey is null) throw new ArgumentException("key cannot be null"); if (_data.ContainsKey(currentKey)) throw new FormatException($"A duplicate key '{currentKey}' was found."); _data[currentKey] = scalarNode.Value; ExitContext(); } private void VisitYamlMappingNode(string context, YamlMappingNode mappingNode) { EnterContext(context); foreach (var nodePair in mappingNode.Children) { string? innerContext = ((YamlScalarNode)nodePair.Key).Value; if (innerContext is not null) VisitYamlNode(innerContext, nodePair.Value); } ExitContext(); } private void VisitYamlSequenceNode(string context, YamlSequenceNode sequenceNode) { EnterContext(context); for (int i = 0; i < sequenceNode.Children.Count; ++i) VisitYamlNode(i.ToString(), sequenceNode.Children[i]); ExitContext(); } private void EnterContext(string context) { _context.Push(context); _currentPath = ConfigurationPath.Combine(_context.Reverse()); } private void ExitContext() { _context.Pop(); _currentPath = ConfigurationPath.Combine(_context.Reverse()); } }
YamlConfigurationFileParser
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Common.Tests/MockRestGatewayTests.cs
{ "start": 1498, "end": 1609 }
public class ____ : IGet, IReturn<TestResponse> { public int Id { get; set; } }
TestGetRequest
csharp
open-telemetry__opentelemetry-dotnet
test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/HttpRetryTestCase.cs
{ "start": 339, "end": 2953 }
public class ____ #pragma warning restore CA1515 // Consider making public types internal { private readonly string testRunnerName; private HttpRetryTestCase(string testRunnerName, HttpRetryAttempt[] retryAttempts, int expectedRetryAttempts = 1) { this.ExpectedRetryAttempts = expectedRetryAttempts; this.RetryAttempts = retryAttempts; this.testRunnerName = testRunnerName; } public int ExpectedRetryAttempts { get; } internal HttpRetryAttempt[] RetryAttempts { get; } public static TheoryData<HttpRetryTestCase> GetHttpTestCases() { return [ new("NetworkError", [new(statusCode: null)]), new("GatewayTimeout", [new(statusCode: HttpStatusCode.GatewayTimeout, throttleDelay: TimeSpan.FromSeconds(1))]), #if NETSTANDARD2_1_OR_GREATER || NET new("ServiceUnavailable", [new(statusCode: HttpStatusCode.TooManyRequests, throttleDelay: TimeSpan.FromSeconds(1))]), #endif new( "Exponential Backoff", [ new(statusCode: null, expectedNextRetryDelayMilliseconds: 1500), new(statusCode: null, expectedNextRetryDelayMilliseconds: 2250), new(statusCode: null, expectedNextRetryDelayMilliseconds: 3375), new(statusCode: null, expectedNextRetryDelayMilliseconds: 5000), new(statusCode: null, expectedNextRetryDelayMilliseconds: 5000) ], expectedRetryAttempts: 5), new( "Retry until non-retryable status code encountered", [ new(statusCode: HttpStatusCode.ServiceUnavailable, expectedNextRetryDelayMilliseconds: 1500), new(statusCode: HttpStatusCode.ServiceUnavailable, expectedNextRetryDelayMilliseconds: 2250), new(statusCode: HttpStatusCode.ServiceUnavailable, expectedNextRetryDelayMilliseconds: 3375), new(statusCode: HttpStatusCode.BadRequest, expectedSuccess: false), new(statusCode: HttpStatusCode.ServiceUnavailable, expectedNextRetryDelayMilliseconds: 5000) ], expectedRetryAttempts: 4), new( "Expired deadline", [ new(statusCode: HttpStatusCode.ServiceUnavailable, isDeadlineExceeded: true, expectedSuccess: false) ]), ]; // TODO: Add more cases. } public override string ToString() { return this.testRunnerName; }
HttpRetryTestCase
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedItem.cs
{ "start": 312, "end": 576 }
public class ____<TItem> : FeedItem { private TItem _item; public new TItem Item { get { return _item; } set { SetItem(value); } } protected override void SetItem(object item) { _item = (TItem)item; base.SetItem(item); } }
FeedItem
csharp
AvaloniaUI__Avalonia
src/Avalonia.Diagnostics/Diagnostics/ViewModels/VisualTreeNode.cs
{ "start": 6845, "end": 7202 }
private struct ____ { public PopupRoot(Control root, string? customName = null) { Root = root; CustomName = customName; } public Control Root { get; } public string? CustomName { get; } } }
PopupRoot
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue26498.cs
{ "start": 934, "end": 2001 }
public class ____ : ContentPage { readonly ObservableCollection<string> _listOfStrings = new ObservableCollection<string>(); ListView _stringListView = new ListView(); public ListViewPage() { var stackLayout = new StackLayout(); var ClearListButton = new Button { Text = "Clear list", AutomationId = "ClearButton", }; ClearListButton.Clicked += (s, e) => { ClearListItems(); }; var BackButton = new Button { Text = "Back to Main Page", AutomationId = "BackButton", }; BackButton.Clicked += (s, e) => { OpenMainPage(); }; stackLayout.Children.Add(ClearListButton); stackLayout.Children.Add(BackButton); _listOfStrings.Add("Item1"); _listOfStrings.Add("Item2"); _listOfStrings.Add("Item3"); _stringListView = new ListView { ItemsSource = _listOfStrings }; stackLayout.Children.Add(_stringListView); Content = stackLayout; } void ClearListItems() { _listOfStrings.Clear(); } void OpenMainPage() { Navigation.PopAsync(); } } }
ListViewPage
csharp
protobuf-net__protobuf-net
src/protobuf-net.Core/Serializers/EnumSerializer.cs
{ "start": 1315, "end": 1653 }
enum ____ for the provided type, which much be a matching enum /// </summary> [MethodImpl(ProtoReader.HotPath)] public static EnumSerializer<T> CreateInt64<T>() where T : unmanaged => SerializerCache<EnumSerializerInt64<T>>.InstanceField; /// <summary> /// Create an
serializer
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 116897, "end": 117114 }
public class ____ { public int Id { get; set; } public RelatedEntity539 ParentEntity { get; set; } public IEnumerable<RelatedEntity541> ChildEntities { get; set; } }
RelatedEntity540
csharp
AutoMapper__AutoMapper
src/IntegrationTests/BuiltInTypes/ProjectEnumerableOfIntToHashSet.cs
{ "start": 870, "end": 1830 }
public class ____ : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Customers.Add(new Customer { FirstName = "Bob", LastName = "Smith", Items = new List<Item>(new[] { new Item(), new Item(), new Item() }) }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Customer, CustomerViewModel>().ForMember(d => d.ItemsIds, o => o.MapFrom(s => s.Items.Select(i => i.Id))); }); [Fact] public void Can_map_with_projection() { using (var context = Fixture.CreateContext()) { var customer = ProjectTo<CustomerViewModel>(context.Customers).Single(); customer.ItemsIds.SequenceEqual(new int[] { 1, 2, 3 }).ShouldBeTrue(); } } }
DatabaseInitializer
csharp
aspnetboilerplate__aspnetboilerplate
test/Abp.Tests/ObjectComparators/ObjectComparatorManager_Tests.cs
{ "start": 240, "end": 1177 }
public class ____ : ObjectComparatorBase<string> { public const string EqualsCompareType = "EqualsCompareType"; public const string ReverseOfSecondIsEqualtoFirstCompareType = "ReverseOfSecondIsEqualtoFirst"; public override ImmutableList<string> CompareTypes { get; } public MyTestStringObjectComparator() { CompareTypes = ImmutableList.Create(EqualsCompareType, ReverseOfSecondIsEqualtoFirstCompareType); } protected override bool Compare(string baseObject, string compareObject, string compareType) { if (compareType != ReverseOfSecondIsEqualtoFirstCompareType) { return baseObject == compareObject; } var array = compareObject.ToCharArray(); Array.Reverse(array); return baseObject == new string(array); } }
MyTestStringObjectComparator
csharp
MiniProfiler__dotnet
src/MiniProfiler.Shared/Data/ProfiledDbCommand.cs
{ "start": 428, "end": 13974 }
public partial class ____ : DbCommand { private DbCommand _command; private DbConnection? _connection; private DbTransaction? _transaction; private IDbProfiler? _profiler; /// <summary> /// Whether to always wrap data readers, even if there isn't an active profiler on this connect. /// This allows depending on overrides for things inheriting from <see cref="ProfiledDbDataReader"/> to actually execute. /// </summary> protected virtual bool AlwaysWrapReaders => false; #if !MINIMAL private static Link<Type, Action<IDbCommand, bool>>? bindByNameCache; private bool _bindByName; /// <summary> /// Gets or sets a value indicating whether or not to bind by name. /// If the underlying command supports BindByName, this sets/clears the underlying /// implementation accordingly. This is required to support OracleCommand from Dapper. /// </summary> public bool BindByName { get => _bindByName; set { if (_bindByName != value) { if (_command != null) { GetBindByName(_command.GetType())?.Invoke(_command, value); } _bindByName = value; } } } #endif /// <summary> /// Initializes a new instance of the <see cref="ProfiledDbCommand"/> class. /// </summary> /// <param name="command">The command.</param> /// <param name="connection">The connection.</param> /// <param name="profiler">The profiler.</param> /// <exception cref="ArgumentNullException">Throws when <paramref name="command"/> is <c>null</c>.</exception> public ProfiledDbCommand(DbCommand command, DbConnection? connection, IDbProfiler? profiler) { _command = command ?? throw new ArgumentNullException(nameof(command)); if (connection != null) { _connection = connection; UnwrapAndAssignConnection(connection); } if (profiler != null) { _profiler = profiler; } } #if !MINIMAL /// <summary> /// Get the binding name. /// </summary> /// <param name="commandType">The command type.</param> /// <returns>The <see cref="Action"/>.</returns> private static Action<IDbCommand, bool>? GetBindByName(Type commandType) { if (commandType == null) return null; // GIGO if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out var action)) { return action; } var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance); action = null; ParameterInfo[] indexers; MethodInfo? setter; if (prop?.CanWrite == true && prop.PropertyType == typeof(bool) && ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0) && (setter = prop.GetSetMethod()) != null) { var method = new DynamicMethod(commandType.Name + "_BindByName", null, new[] { typeof(IDbCommand), typeof(bool) }); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Castclass, commandType); il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Callvirt, setter, null); il.Emit(OpCodes.Ret); action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>)); } // cache it Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action!); return action; } #endif /// <inheritdoc cref="DbCommand.CommandText"/> [AllowNull] public override string CommandText { get => _command.CommandText; set => _command.CommandText = value; } /// <inheritdoc cref="DbCommand.CommandTimeout"/> public override int CommandTimeout { get => _command.CommandTimeout; set => _command.CommandTimeout = value; } /// <inheritdoc cref="DbCommand.CommandType"/> public override CommandType CommandType { get => _command.CommandType; set => _command.CommandType = value; } /// <inheritdoc cref="DbCommand.DbConnection"/> protected override DbConnection? DbConnection { get => _connection; set { _connection = value; UnwrapAndAssignConnection(value); } } private void UnwrapAndAssignConnection(DbConnection? value) { if (value is ProfiledDbConnection profiledConn) { _profiler = profiledConn.Profiler; _command.Connection = profiledConn.WrappedConnection; } else { _command.Connection = value; } } /// <inheritdoc cref="DbCommand.DbParameterCollection"/> protected override DbParameterCollection DbParameterCollection => _command.Parameters; /// <inheritdoc cref="DbCommand.DbTransaction"/> protected override DbTransaction? DbTransaction { get => _transaction; set { _transaction = value; _command.Transaction = value is ProfiledDbTransaction awesomeTran ? awesomeTran.WrappedTransaction : value; } } /// <inheritdoc cref="DbCommand.DesignTimeVisible"/> public override bool DesignTimeVisible { get => _command.DesignTimeVisible; set => _command.DesignTimeVisible = value; } /// <inheritdoc cref="DbCommand.UpdatedRowSource"/> public override UpdateRowSource UpdatedRowSource { get => _command.UpdatedRowSource; set => _command.UpdatedRowSource = value; } /// <summary> /// Creates a wrapper data reader for <see cref="ExecuteDbDataReader"/> and <see cref="ExecuteDbDataReaderAsync"/> /> /// </summary> protected virtual DbDataReader CreateDbDataReader(DbDataReader original, CommandBehavior behavior, IDbProfiler? profiler) => new ProfiledDbDataReader(original, behavior, profiler); /// <inheritdoc cref="DbCommand.ExecuteDbDataReader(CommandBehavior)"/> protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { DbDataReader? result = null; if (_profiler?.IsActive != true) { result = _command.ExecuteReader(behavior); return AlwaysWrapReaders ? CreateDbDataReader(result, behavior, null) : result; } _profiler.ExecuteStart(this, SqlExecuteType.Reader); try { result = _command.ExecuteReader(behavior); result = CreateDbDataReader(result, behavior, _profiler); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.Reader, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.Reader, result); } return result; } /// <inheritdoc cref="DbCommand.ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken)"/> protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { DbDataReader? result = null; if (_profiler?.IsActive != true) { result = await _command.ExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); return AlwaysWrapReaders ? CreateDbDataReader(result, behavior, null) : result; } _profiler.ExecuteStart(this, SqlExecuteType.Reader); try { result = await _command.ExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); result = CreateDbDataReader(result, behavior, _profiler); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.Reader, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.Reader, result); } return result; } /// <inheritdoc cref="DbCommand.ExecuteNonQuery()"/> public override int ExecuteNonQuery() { if (_profiler?.IsActive != true) { return _command.ExecuteNonQuery(); } int result; _profiler.ExecuteStart(this, SqlExecuteType.NonQuery); try { result = _command.ExecuteNonQuery(); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.NonQuery, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.NonQuery, null); } return result; } /// <inheritdoc cref="DbCommand.ExecuteNonQueryAsync(CancellationToken)"/> public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { if (_profiler?.IsActive != true) { return await _command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } int result; _profiler.ExecuteStart(this, SqlExecuteType.NonQuery); try { result = await _command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.NonQuery, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.NonQuery, null); } return result; } /// <inheritdoc cref="DbCommand.ExecuteScalar()"/> public override object? ExecuteScalar() { if (_profiler?.IsActive != true) { return _command.ExecuteScalar(); } object? result; _profiler.ExecuteStart(this, SqlExecuteType.Scalar); try { result = _command.ExecuteScalar(); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.Scalar, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.Scalar, null); } return result; } /// <inheritdoc cref="DbCommand.ExecuteScalarAsync(CancellationToken)"/> public override async Task<object?> ExecuteScalarAsync(CancellationToken cancellationToken) { if (_profiler?.IsActive != true) { return await _command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); } object? result; _profiler.ExecuteStart(this, SqlExecuteType.Scalar); try { result = await _command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { _profiler.OnError(this, SqlExecuteType.Scalar, e); throw; } finally { _profiler.ExecuteFinish(this, SqlExecuteType.Scalar, null); } return result; } /// <inheritdoc cref="DbCommand.Cancel()"/> public override void Cancel() => _command.Cancel(); /// <inheritdoc cref="DbCommand.Prepare()"/> public override void Prepare() => _command.Prepare(); /// <inheritdoc cref="DbCommand.CreateDbParameter()"/> protected override DbParameter CreateDbParameter() => _command.CreateParameter(); /// <summary> /// Releases all resources used by this command. /// </summary> /// <param name="disposing">false if this is being disposed in a <c>finalizer</c>.</param> protected override void Dispose(bool disposing) { if (disposing && _command != null) { _command.Dispose(); } _command = null!; base.Dispose(disposing); } /// <summary> /// Obsolete - please use <see cref="WrappedCommand"/>. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never), Obsolete($"Please use {nameof(WrappedCommand)}", false)] public DbCommand InternalCommand => _command; /// <summary> /// Gets the internally wrapped <see cref="DbCommand"/>. /// </summary> public DbCommand WrappedCommand => _command; } }
ProfiledDbCommand
csharp
dotnet__efcore
test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.PropertyMapping.cs
{ "start": 3438, "end": 3565 }
protected class ____ { public string Name { get; set; } = ""; public int Value { get; set; } } }
ComplexTag
csharp
MonoGame__MonoGame
MonoGame.Framework/Graphics/States/DepthStencilState.cs
{ "start": 337, "end": 17325 }
public partial class ____ : GraphicsResource { private readonly bool _defaultStateObject; private bool _depthBufferEnable; private bool _depthBufferWriteEnable; private StencilOperation _counterClockwiseStencilDepthBufferFail; private StencilOperation _counterClockwiseStencilFail; private CompareFunction _counterClockwiseStencilFunction; private StencilOperation _counterClockwiseStencilPass; private CompareFunction _depthBufferFunction; private int _referenceStencil; private StencilOperation _stencilDepthBufferFail; private bool _stencilEnable; private StencilOperation _stencilFail; private CompareFunction _stencilFunction; private int _stencilMask; private StencilOperation _stencilPass; private int _stencilWriteMask; private bool _twoSidedStencilMode; /// <summary> /// Gets or Sets a value that indicates if depth buffering is enabled. /// The default value is true. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public bool DepthBufferEnable { get { return _depthBufferEnable; } set { ThrowIfBound(); _depthBufferEnable = value; } } /// <summary> /// Gets or Sets a value that indicates if writing to the depth buffer is enabled. /// The default value is true. /// </summary> /// <remarks> /// <para> /// This property enables an application to prevent the system from updating the depth buffer with new /// values. /// </para> /// <para> /// if false, depth comparisons are still made according to the render state /// <see cref="DepthBufferFunction"/>, assuming that depth buffering is taking place, but depth values /// are not written to the buffer. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public bool DepthBufferWriteEnable { get { return _depthBufferWriteEnable; } set { ThrowIfBound(); _depthBufferWriteEnable = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil test passes and the depth-buffer test fails /// for a counterclockwise triangle. /// The default value is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation CounterClockwiseStencilDepthBufferFail { get { return _counterClockwiseStencilDepthBufferFail; } set { ThrowIfBound(); _counterClockwiseStencilDepthBufferFail = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil test fails for the counterclockwise triangle. /// The default value is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation CounterClockwiseStencilFail { get { return _counterClockwiseStencilFail; } set { ThrowIfBound(); _counterClockwiseStencilFail = value; } } /// <summary> /// Gets or Sets the comparison function to use for counterclockwise stencil tests. /// The default value is <see cref="CompareFunction.Always">CompareFunction.Always</see> /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public CompareFunction CounterClockwiseStencilFunction { get { return _counterClockwiseStencilFunction; } set { ThrowIfBound(); _counterClockwiseStencilFunction = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil and depth-tests pass for a counterclockwise /// triangle. /// The default value is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation CounterClockwiseStencilPass { get { return _counterClockwiseStencilPass; } set { ThrowIfBound(); _counterClockwiseStencilPass = value; } } /// <summary> /// Gets or Sets the comparison function for the depth-buffer test. /// The default value is <see cref="CompareFunction.LessEqual">CompareFunction.LessEqual</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public CompareFunction DepthBufferFunction { get { return _depthBufferFunction; } set { ThrowIfBound(); _depthBufferFunction = value; } } /// <summary> /// Gets or Sets a reference value to use for the stencil test. /// The default is 0. /// </summary> /// <remarks> /// The reference value is compared, by the comparison function specified by the <see cref="StencilFunction"/> /// property, to the stencil buffer entry of a pixel. This can be illustrated by a simple equation: /// /// <code> /// ReferenceStencil StencilFunction (stencil buffer entry) /// </code> /// /// This comparison applies only to the bits in the reference value and stencil buffer entry that are set in /// the stencil mask by this property. If the comparison is true, the stencil test passes and the pass /// operation (specified by the <see cref="StencilPass"/> property) is performed. /// </remarks> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public int ReferenceStencil { get { return _referenceStencil; } set { ThrowIfBound(); _referenceStencil = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil test passes and the depth-test fails. /// The default is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation StencilDepthBufferFail { get { return _stencilDepthBufferFail; } set { ThrowIfBound(); _stencilDepthBufferFail = value; } } /// <summary> /// Gets or Sets a value that indicates whether stenciling is enabled. /// The default is false. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public bool StencilEnable { get { return _stencilEnable; } set { ThrowIfBound(); _stencilEnable = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil test fails. /// The default is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation StencilFail { get { return _stencilFail; } set { ThrowIfBound(); _stencilFail = value; } } /// <summary> /// Gets or Sets the comparison function for the stencil test. /// The default is <see cref="CompareFunction.Always">CompareFunction.Always</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public CompareFunction StencilFunction { get { return _stencilFunction; } set { ThrowIfBound(); _stencilFunction = value; } } /// <summary> /// Gets or Sets the mask applied to the reference value and each stencil buffer entry to determine the /// significant bits for the stencil test. /// The default mask is <see cref="Int32.MaxValue">Int32.MaxValue</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public int StencilMask { get { return _stencilMask; } set { ThrowIfBound(); _stencilMask = value; } } /// <summary> /// Gets or Sets the stencil operation to perform if the stencil test passes. /// The default value is <see cref="StencilOperation.Keep">StencilOperation.Keep</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public StencilOperation StencilPass { get { return _stencilPass; } set { ThrowIfBound(); _stencilPass = value; } } /// <summary> /// Gets or Sets the write mask applied to values written into the stencil buffer. /// The default mask is <see cref="Int32.MaxValue">Int32.MaxValue</see>. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public int StencilWriteMask { get { return _stencilWriteMask; } set { ThrowIfBound(); _stencilWriteMask = value; } } /// <summary> /// Gets or Sets a value that indicates whether two-sided stenciling is enabled. /// The default value is false. /// </summary> /// <exception cref="InvalidOperationException"> /// When setting this value for one of the default DepthStencilState instances; <see cref="Default"/>, /// <see cref="DepthRead"/>, or <see cref="None"/>. /// /// -or- /// /// When setting this value after this DepthStencilState has already been bound to the graphics device. /// </exception> public bool TwoSidedStencilMode { get { return _twoSidedStencilMode; } set { ThrowIfBound(); _twoSidedStencilMode = value; } } internal void BindToGraphicsDevice(GraphicsDevice device) { if (_defaultStateObject) throw new InvalidOperationException("You cannot bind a default state object."); if (GraphicsDevice != null && GraphicsDevice != device) throw new InvalidOperationException("This depth stencil state is already bound to a different graphics device."); GraphicsDevice = device; } internal void ThrowIfBound() { if (_defaultStateObject) throw new InvalidOperationException("You cannot modify a default depth stencil state object."); if (GraphicsDevice != null) throw new InvalidOperationException("You cannot modify the depth stencil state after it has been bound to the graphics device!"); } /// <summary> /// Creates a new instance of the DepthStencilState
DepthStencilState
csharp
dotnetcore__FreeSql
Providers/FreeSql.Provider.Custom/Oracle/Curd/CustomOracleSelect.cs
{ "start": 20038, "end": 20614 }
class ____ T8 : class { public OdbcOracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } public override string ToSql(string field = null) => CustomOracleSelect<T1>.ToSqlStatic(_commonUtils, _commonExpression, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, this.GetTableRuleUnions(), _aliasRule, _tosqlAppendContent, _whereGlobalFilter, _orm); }
where
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.SampleApp/Common/AnalyticsVersionInfoExtensions.cs
{ "start": 2053, "end": 2226 }
public enum ____ { Desktop, Holographic, IoT, Mobile, SurfaceHub, Tablet, Xbox, Other } }
DeviceFormFactor
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Indexing.Core/Recipes/CreateOrUpdateIndexProfileStep.cs
{ "start": 307, "end": 4613 }
public sealed class ____ : NamedRecipeStepHandler { public const string StepKey = "CreateOrUpdateIndexProfile"; private readonly IIndexProfileManager _indexProfileManager; private readonly IServiceProvider _serviceProvider; private readonly IndexingOptions _indexingOptions; internal readonly IStringLocalizer S; public CreateOrUpdateIndexProfileStep( IIndexProfileManager indexProfileManager, IOptions<IndexingOptions> indexingOptions, IServiceProvider serviceProvider, IStringLocalizer<CreateOrUpdateIndexProfileStep> stringLocalizer) : base(StepKey) { _indexProfileManager = indexProfileManager; _serviceProvider = serviceProvider; _indexingOptions = indexingOptions.Value; S = stringLocalizer; } protected override async Task HandleAsync(RecipeExecutionContext context) { var model = context.Step.ToObject<IndexProfileStepModel>(); var tokens = model.Indexes.Cast<JsonObject>() ?? []; foreach (var token in tokens) { IndexProfile indexProfile = null; var id = token[nameof(indexProfile.Id)]?.GetValue<string>(); if (!string.IsNullOrEmpty(id)) { indexProfile = await _indexProfileManager.FindByIdAsync(id); } if (indexProfile is null) { var name = token[nameof(indexProfile.Name)]?.GetValue<string>(); if (!string.IsNullOrEmpty(name)) { indexProfile = await _indexProfileManager.FindByNameAsync(name); } } if (indexProfile is not null) { var validationResult = await _indexProfileManager.ValidateAsync(indexProfile); if (!validationResult.Succeeded) { foreach (var error in validationResult.Errors) { context.Errors.Add(error.ErrorMessage); } continue; } await _indexProfileManager.UpdateAsync(indexProfile, token); } else { var providerName = token[nameof(indexProfile.ProviderName)]?.GetValue<string>(); if (string.IsNullOrEmpty(providerName)) { context.Errors.Add(S["Could not find provider value. The index will not be imported"]); continue; } var type = token[nameof(indexProfile.Type)]?.GetValue<string>(); if (string.IsNullOrEmpty(type)) { context.Errors.Add(S["Could not find type value. The index will not be imported"]); continue; } if (!_indexingOptions.Sources.TryGetValue(new IndexProfileKey(providerName, type), out var _)) { context.Errors.Add(S["Unable to find a provider named '{0}' with the type '{1}'.", providerName, type]); return; } indexProfile = await _indexProfileManager.NewAsync(providerName, type, token); var validationResult = await _indexProfileManager.ValidateAsync(indexProfile); if (!validationResult.Succeeded) { foreach (var error in validationResult.Errors) { context.Errors.Add(error.ErrorMessage); } continue; } var indexManager = _serviceProvider.GetRequiredKeyedService<IIndexManager>(providerName); await _indexProfileManager.CreateAsync(indexProfile); if (!await indexManager.CreateAsync(indexProfile)) { await _indexProfileManager.DeleteAsync(indexProfile); context.Errors.Add(S["Unable to create the index '{0}' for the provider '{1}'.", indexProfile.IndexName, providerName]); return; } await _indexProfileManager.SynchronizeAsync(indexProfile); } } }
CreateOrUpdateIndexProfileStep
csharp
ServiceStack__ServiceStack
ServiceStack.Stripe/src/ServiceStack.Stripe/StripeGateway.cs
{ "start": 557, "end": 941 }
public class ____ : IPost, IReturn<StripeCharge> { public int Amount { get; set; } public string Currency { get; set; } public string Customer { get; set; } public string Card { get; set; } public string Description { get; set; } public bool? Capture { get; set; } public int? ApplicationFee { get; set; } } [Route("/charges/{ChargeId}")]
ChargeStripeCustomer
csharp
getsentry__sentry-dotnet
src/Sentry/Integrations/AppDomainUnhandledExceptionIntegration.cs
{ "start": 84, "end": 1479 }
internal class ____ : ISdkIntegration { private readonly IAppDomain _appDomain; private IHub? _hub; private SentryOptions? _options; internal AppDomainUnhandledExceptionIntegration(IAppDomain? appDomain = null) => _appDomain = appDomain ?? AppDomainAdapter.Instance; public void Register(IHub hub, SentryOptions options) { _hub = hub; _options = options; _appDomain.UnhandledException += Handle; } // Internal for testability #if !NET6_0_OR_GREATER [HandleProcessCorruptedStateExceptions] #endif [SecurityCritical] internal void Handle(object sender, UnhandledExceptionEventArgs e) { _options?.LogDebug("AppDomain Unhandled Exception"); if (e.ExceptionObject is Exception ex) { ex.SetSentryMechanism( "AppDomain.UnhandledException", "This exception was caught by the .NET Application Domain global error handler. " + "The application likely crashed as a result of this exception.", handled: false); // Call the internal implementation, so that we still capture even if the hub has been disabled. _hub?.CaptureExceptionInternal(ex); } if (e.IsTerminating) { _hub?.Flush(_options!.ShutdownTimeout); } } }
AppDomainUnhandledExceptionIntegration
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/Data/DataException.cs
{ "start": 181, "end": 426 }
public class ____ : Exception { public DataException() { } public DataException(string message) : base(message) { } public DataException(string message, Exception innerException) : base(message, innerException) { } }
DataException
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs
{ "start": 76, "end": 626 }
public static class ____ { public static string ControllerName(this Type controllerType) { if (!typeof(ControllerBase).IsAssignableFrom(controllerType)) { throw new ArgumentException($"The specified type must inherit from '{nameof(ControllerBase)}'", nameof(controllerType)); } return controllerType.Name.EndsWith(nameof(Controller), StringComparison.OrdinalIgnoreCase) ? controllerType.Name[..^nameof(Controller).Length] : controllerType.Name; } }
ControllerTypeExtensions
csharp
bitwarden__server
src/Core/Settings/GlobalSettings.cs
{ "start": 32458, "end": 32574 }
public class ____ : IWebPushSettings { public string VapidPublicKey { get; set; } }
WebPushSettings
csharp
dotnet__orleans
test/Grains/TestGrains/ConsumerEventCountingGrain.cs
{ "start": 126, "end": 680 }
public class ____ : Grain, IConsumerEventCountingGrain { private int _numConsumedItems; private readonly ILogger _logger; private IAsyncObservable<int> _consumer; private StreamSubscriptionHandle<int> _subscriptionHandle; internal const string StreamNamespace = "HaloStreamingNamespace"; public ConsumerEventCountingGrain(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); }
ConsumerEventCountingGrain
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.UnitTests/Test_ObservablePropertyAttribute.cs
{ "start": 48920, "end": 49060 }
public partial class ____ : ObservableObject { [ObservableProperty] private string? value; }
ModelWithValueProperty
csharp
dotnet__maui
src/Core/tests/UnitTests/Layouts/AbsoluteLayoutManagerTests.cs
{ "start": 392, "end": 15280 }
public class ____ { IAbsoluteLayout CreateTestLayout() { var layout = Substitute.For<IAbsoluteLayout>(); layout.Height.Returns(Dimension.Unset); layout.Width.Returns(Dimension.Unset); layout.MinimumHeight.Returns(Dimension.Minimum); layout.MinimumWidth.Returns(Dimension.Minimum); layout.MaximumHeight.Returns(Dimension.Maximum); layout.MaximumWidth.Returns(Dimension.Maximum); return layout; } void SetLayoutBounds(IAbsoluteLayout layout, IView child, Rect bounds) { layout.GetLayoutBounds(child).Returns(bounds); } void SetLayoutFlags(IAbsoluteLayout layout, IView child, AbsoluteLayoutFlags flags) { layout.GetLayoutFlags(child).Returns(flags); } Size MeasureAndArrange(IAbsoluteLayout absoluteLayout, double widthConstraint = double.PositiveInfinity, double heightConstraint = double.PositiveInfinity, double left = 0, double top = 0) { var manager = new AbsoluteLayoutManager(absoluteLayout); var measuredSize = manager.Measure(widthConstraint, heightConstraint); manager.ArrangeChildren(new Rect(new Point(left, top), measuredSize)); return measuredSize; } static double AutoSize = -1; static Rect DefaultBounds = new Rect(0, 0, AutoSize, AutoSize); [Fact] public void DefaultLayoutBoundsUsesDefaultMeasure() { var abs = CreateTestLayout(); var child = CreateTestView(new Size(50, 75)); // Have GetLayoutBounds return the "default" value of 0,0,-1,-1 abs.GetLayoutBounds(child).Returns(DefaultBounds); var expectedRectangle = new Rect(0, 0, 50, 75); SubstituteChildren(abs, child); var measure = MeasureAndArrange(abs, double.PositiveInfinity, double.PositiveInfinity); // No layout bounds were specified, so plain-old measuring should be used. The view wants to be 50 by 75, and so it shall Assert.Equal(expectedRectangle.Size, measure); AssertArranged(child, expectedRectangle); } [Fact] public void AbsolutePositionAndSize() { var abs = CreateTestLayout(); var child = CreateTestView(); var expectedRectangle = new Rect(10, 15, 100, 100); SubstituteChildren(abs, child); SetLayoutBounds(abs, child, expectedRectangle); var measure = MeasureAndArrange(abs, double.PositiveInfinity, double.PositiveInfinity); // We expect that the measured size will be big enough to include the whole child rectangle at its offset var expectedSize = new Size(expectedRectangle.Left + expectedRectangle.Width, expectedRectangle.Top + expectedRectangle.Height); Assert.Equal(expectedSize, measure); AssertArranged(child, expectedRectangle); } [Fact] public void AbsoluteLayoutRespectsBounds() { var abs = CreateTestLayout(); var child = CreateTestView(); var childBounds = new Rect(10, 15, 100, 100); SubstituteChildren(abs, child); SetLayoutBounds(abs, child, childBounds); var measure = MeasureAndArrange(abs, double.PositiveInfinity, double.PositiveInfinity, left: 10, top: 10); // We expect that the measured size will be big enough to include the whole child rectangle at its offset var expectedSize = new Size(childBounds.Left + childBounds.Width, childBounds.Top + childBounds.Height); // We expect that the child will be arranged at a spot that respects the offsets var expectedRectangle = new Rect(childBounds.Left + 10, childBounds.Top + 10, childBounds.Width, childBounds.Height); Assert.Equal(expectedSize, measure); AssertArranged(child, expectedRectangle); } [Fact] public void AbsolutePositionRelativeSize() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(10, 20, 0.4, 0.5); SetLayoutBounds(abs, child, childBounds); SetLayoutFlags(abs, child, AbsoluteLayoutFlags.SizeProportional); var manager = new AbsoluteLayoutManager(abs); var measure = manager.Measure(100, 100); manager.ArrangeChildren(new Rect(0, 0, 100, 100)); var expectedMeasure = new Size(10 + 40, 20 + 50); Assert.Equal(expectedMeasure, measure); child.Received().Arrange(Arg.Is<Rect>(r => r.X == 10 && r.Y == 20 && r.Width == 40 && r.Height == 50)); } [InlineData(30, 40, 0.2, 0.3)] [InlineData(35, 45, 0.5, 0.5)] [InlineData(35, 45, 0, 0)] [InlineData(35, 45, 1, 1)] [Theory] public void RelativePositionAbsoluteSize(double width, double height, double propX, double propY) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(propX, propY, width, height); SetLayoutBounds(abs, child, childBounds); SetLayoutFlags(abs, child, AbsoluteLayoutFlags.PositionProportional); var manager = new AbsoluteLayoutManager(abs); manager.Measure(100, 100); manager.ArrangeChildren(new Rect(0, 0, 100, 100)); double expectedX = (100 - width) * propX; double expectedY = (100 - height) * propY; var expectedRectangle = new Rect(expectedX, expectedY, width, height); child.Received().Arrange(Arg.Is(expectedRectangle)); } [InlineData(0.0, 0.0, 0.0, 0.0)] [InlineData(0.2, 0.2, 0.2, 0.2)] [InlineData(0.5, 0.5, 0.5, 0.5)] [InlineData(1.0, 1.0, 1.0, 1.0)] [Theory] public void RelativePositionRelativeSize(double propX, double propY, double propHeight, double propWidth) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(propX, propY, propWidth, propHeight); SetLayoutBounds(abs, child, childBounds); SetLayoutFlags(abs, child, AbsoluteLayoutFlags.All); var manager = new AbsoluteLayoutManager(abs); manager.Measure(100, 100); manager.ArrangeChildren(new Rect(0, 0, 100, 100)); double expectedWidth = 100 * propWidth; double expectedHeight = 100 * propHeight; double expectedX = (100 - expectedWidth) * propX; double expectedY = (100 - expectedHeight) * propY; var expectedRectangle = new Rect(expectedX, expectedY, expectedWidth, expectedHeight); child.Received().Arrange(Arg.Is(expectedRectangle)); } [Theory] [InlineData(0, 0, 0, 0, 40, 40)] [InlineData(5, 5, 5, 5, 40, 40)] [InlineData(10, 10, 0, 0, 45, 45)] public void RelativePositionRespectsPadding(double left, double top, double right, double bottom, double expectedX, double expectedY) { double width = 20; double height = 20; double propX = 0.5; double propY = 0.5; var abs = CreateTestLayout(); var padding = new Thickness(left, top, right, bottom); abs.Padding.Returns(padding); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(propX, propY, width, height); SetLayoutBounds(abs, child, childBounds); SetLayoutFlags(abs, child, AbsoluteLayoutFlags.PositionProportional); var manager = new AbsoluteLayoutManager(abs); manager.Measure(100, 100); manager.ArrangeChildren(new Rect(0, 0, 100, 100)); var expectedRectangle = new Rect(expectedX, expectedY, width, height); child.Received().Arrange(Arg.Is(expectedRectangle)); } [Theory] [InlineData(50, 100, 50)] [InlineData(100, 100, 100)] [InlineData(100, 50, 50)] [InlineData(0, 50, 0)] public void MeasureRespectsMaxHeight(double maxHeight, double viewHeight, double expectedHeight) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, viewHeight); SetLayoutBounds(abs, child, childBounds); abs.MaximumHeight.Returns(maxHeight); var layoutManager = new AbsoluteLayoutManager(abs); var measure = layoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); Assert.Equal(expectedHeight, measure.Height); } [Theory] [InlineData(50, 100, 50)] [InlineData(100, 100, 100)] [InlineData(100, 50, 50)] [InlineData(0, 50, 0)] public void MeasureRespectsMaxWidth(double maxWidth, double viewWidth, double expectedWidth) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, viewWidth, 100); SetLayoutBounds(abs, child, childBounds); abs.MaximumWidth.Returns(maxWidth); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); Assert.Equal(expectedWidth, measure.Width); } [Theory] [InlineData(50, 10, 50)] [InlineData(100, 100, 100)] [InlineData(10, 50, 50)] public void MeasureRespectsMinHeight(double minHeight, double viewHeight, double expectedHeight) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, viewHeight); SetLayoutBounds(abs, child, childBounds); abs.MinimumHeight.Returns(minHeight); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); Assert.Equal(expectedHeight, measure.Height); } [Theory] [InlineData(50, 10, 50)] [InlineData(100, 100, 100)] [InlineData(10, 50, 50)] public void MeasureRespectsMinWidth(double minWidth, double viewWidth, double expectedWidth) { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, viewWidth, 100); SetLayoutBounds(abs, child, childBounds); abs.MinimumWidth.Returns(minWidth); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); Assert.Equal(expectedWidth, measure.Width); } [Fact] public void MaxWidthDominatesWidth() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); abs.Width.Returns(75); abs.MaximumWidth.Returns(50); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); // The maximum value beats out the explicit value Assert.Equal(50, measure.Width); } [Fact] public void MinWidthDominatesMaxWidth() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); abs.MinimumWidth.Returns(75); abs.MaximumWidth.Returns(50); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); // The minimum value should beat out the maximum value Assert.Equal(75, measure.Width); } [Fact] public void MaxHeightDominatesHeight() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); abs.Height.Returns(75); abs.MaximumHeight.Returns(50); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); // The maximum value beats out the explicit value Assert.Equal(50, measure.Height); } [Fact] public void MinHeightDominatesMaxHeight() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); abs.MinimumHeight.Returns(75); abs.MaximumHeight.Returns(50); var layoutManager = new AbsoluteLayoutManager(abs); var measure = layoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); // The minimum value should beat out the maximum value Assert.Equal(75, measure.Height); } [Fact] public void ArrangeAccountsForFill() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); var layoutManager = new AbsoluteLayoutManager(abs); _ = layoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); var arrangedWidth = 1000; var arrangedHeight = 1000; var target = new Rect(Point.Zero, new Size(arrangedWidth, arrangedHeight)); var actual = layoutManager.ArrangeChildren(target); // Since we're arranging in a space larger than needed and the layout is set to Fill in both directions, // we expect the returned actual arrangement size to be as large as the target space Assert.Equal(arrangedWidth, actual.Width); Assert.Equal(arrangedHeight, actual.Height); } [Fact] public void ChildMeasureRespectsAbsoluteBounds() { double expectedWidth = 115; double expectedHeight = 230; var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, expectedWidth, expectedHeight); SetLayoutBounds(abs, child, childBounds); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(double.PositiveInfinity, double.PositiveInfinity); child.Received().Measure(Arg.Is(expectedWidth), Arg.Is(expectedHeight)); } [Fact] public void ChildMeasureRespectsProportionalBounds() { double expectedWidth = 0.5; double expectedHeight = 0.6; double widthConstraint = 200; double heightConstraint = 200; var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(0, 0, expectedWidth, expectedHeight); SetLayoutBounds(abs, child, childBounds); SetLayoutFlags(abs, child, AbsoluteLayoutFlags.SizeProportional); var gridLayoutManager = new AbsoluteLayoutManager(abs); var measure = gridLayoutManager.Measure(widthConstraint, heightConstraint); child.Received().Measure(Arg.Is(expectedWidth * widthConstraint), Arg.Is(expectedHeight * heightConstraint)); } [Fact(DisplayName = "First View in LTR Absolute Layout is on the left")] public void LtrShouldHaveFirstItemOnTheLeft() { var abs = CreateTestLayout(); var child = CreateTestView(); SubstituteChildren(abs, child); var childBounds = new Rect(10, 0, 100, 100); SetLayoutBounds(abs, child, childBounds); abs.FlowDirection.Returns(FlowDirection.LeftToRight); var manager = new AbsoluteLayoutManager(abs); var measuredSize = manager.Measure(double.PositiveInfinity, 100); manager.ArrangeChildren(new Rect(Point.Zero, measuredSize)); // We expect that the view should be arranged on the left var expectedRectangle = new Rect(10, 0, 100, 100); abs[0].Received().Arrange(Arg.Is(expectedRectangle)); } } }
AbsoluteLayoutManagerTests
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp3614Tests.cs
{ "start": 3213, "end": 3562 }
public sealed class ____ : MongoCollectionFixture<Book> { protected override IEnumerable<Book> InitialData => [ new Book { Id = 1, PageCount = 1, Author = null }, new Book { Id = 2, PageCount = 2, Author = new Author { Id = 2, Name = "Two" } } ]; } } }
ClassFixture
csharp
dotnet__efcore
src/EFCore/Metadata/Builders/ComplexCollectionBuilder`.cs
{ "start": 350, "end": 777 }
class ____ returned from methods when using the <see cref="ModelBuilder" /> API /// and it is not designed to be directly constructed in your application code. /// </remarks> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <typeparam name="TComplex">The complex type being configured.</typeparam>
are
csharp
GtkSharp__GtkSharp
Source/Libs/PangoSharp/FontMap.cs
{ "start": 903, "end": 2387 }
public partial class ____ { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void d_pango_font_map_list_families2(IntPtr raw, out IntPtr families, out int n_families); static d_pango_font_map_list_families2 pango_font_map_list_families2 = FuncLoader.LoadFunction<d_pango_font_map_list_families2>(FuncLoader.GetProcAddress(GLibrary.Load(Library.Pango), "pango_font_map_list_families")); public FontFamily [] Families { get { int count; IntPtr array_ptr; pango_font_map_list_families2 (Handle, out array_ptr, out count); if (array_ptr == IntPtr.Zero) return new FontFamily [0]; FontFamily [] result = new FontFamily [count]; for (int i = 0; i < count; i++) { IntPtr fam_ptr = Marshal.ReadIntPtr (array_ptr, i * IntPtr.Size); result [i] = GLib.Object.GetObject (fam_ptr) as FontFamily; } GLib.Marshaller.Free (array_ptr); return result; } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void d_pango_font_map_list_families(IntPtr raw, IntPtr families, out int n_families); static d_pango_font_map_list_families pango_font_map_list_families = FuncLoader.LoadFunction<d_pango_font_map_list_families>(FuncLoader.GetProcAddress(GLibrary.Load(Library.Pango), "pango_font_map_list_families")); [Obsolete] public int ListFamilies(Pango.FontFamily families) { int n_families; pango_font_map_list_families(Handle, families.Handle, out n_families); return n_families; } } }
FontMap
csharp
unoplatform__uno
src/Uno.UWP/Storage/StorageFile.saf.Android.cs
{ "start": 343, "end": 603 }
public partial class ____ { public static StorageFile GetFromSafDocument(DocumentFile document) => new StorageFile(new SafFile(document)); public static StorageFile GetFromSafUri(Android.Net.Uri uri) => new StorageFile(new SafFile(uri));
StorageFile
csharp
FluentValidation__FluentValidation
src/FluentValidation.Tests/StringEnumValidatorTests.cs
{ "start": 3798, "end": 3919 }
enum ____ can't be used with IsEnumName. (Parameter 'enumType')"; exception.Message.ShouldEqual(expectedMessage); } }
and
csharp
dotnet__aspnetcore
src/Middleware/OutputCaching/test/OutputCacheMiddlewareTests.cs
{ "start": 629, "end": 800 }
public class ____ : OutputCacheMiddlewareTests { public override ITestOutputCacheStore GetStore() => new SimpleTestOutputCache(); }
OutputCacheMiddlewareTests_SimpleStore
csharp
pythonnet__pythonnet
src/testing/ReprTest.cs
{ "start": 2021, "end": 2209 }
public class ____ { public string __repr__(int i) { return "__repr__ implemention with input parameter!"; } }
Corge
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Concurrency/Scheduler.Services.cs
{ "start": 475, "end": 4628 }
partial class ____ { internal static Type[] Optimizations = [ typeof(ISchedulerLongRunning), typeof(IStopwatchProvider), typeof(ISchedulerPeriodic) /* update this list if new interface-based optimizations are added */ ]; /// <summary> /// Returns the <see cref="ISchedulerLongRunning"/> implementation of the specified scheduler, or <c>null</c> if no such implementation is available. /// </summary> /// <param name="scheduler">Scheduler to get the <see cref="ISchedulerLongRunning"/> implementation for.</param> /// <returns>The scheduler's <see cref="ISchedulerLongRunning"/> implementation if available; <c>null</c> otherwise.</returns> /// <remarks> /// This helper method is made available for query operator authors in order to discover scheduler services by using the required /// IServiceProvider pattern, which allows for interception or redefinition of scheduler services. /// </remarks> public static ISchedulerLongRunning? AsLongRunning(this IScheduler scheduler) => As<ISchedulerLongRunning>(scheduler); /// <summary> /// Returns the <see cref="IStopwatchProvider"/> implementation of the specified scheduler, or <c>null</c> if no such implementation is available. /// </summary> /// <param name="scheduler">Scheduler to get the <see cref="IStopwatchProvider"/> implementation for.</param> /// <returns>The scheduler's <see cref="IStopwatchProvider"/> implementation if available; <c>null</c> otherwise.</returns> /// <remarks> /// <para> /// This helper method is made available for query operator authors in order to discover scheduler services by using the required /// IServiceProvider pattern, which allows for interception or redefinition of scheduler services. /// </para> /// <para> /// Consider using <see cref="StartStopwatch"/> in case a stopwatch is required, but use of emulation stopwatch based /// on the scheduler's clock is acceptable. Use of this method is recommended for best-effort use of the stopwatch provider /// scheduler service, where the caller falls back to not using stopwatches if this facility wasn't found. /// </para> /// </remarks> public static IStopwatchProvider? AsStopwatchProvider(this IScheduler scheduler) => As<IStopwatchProvider>(scheduler); /// <summary> /// Returns the <see cref="ISchedulerPeriodic"/> implementation of the specified scheduler, or <c>null</c> if no such implementation is available. /// </summary> /// <param name="scheduler">Scheduler to get the <see cref="ISchedulerPeriodic"/> implementation for.</param> /// <returns>The scheduler's <see cref="ISchedulerPeriodic"/> implementation if available; <c>null</c> otherwise.</returns> /// <remarks> /// <para> /// This helper method is made available for query operator authors in order to discover scheduler services by using the required /// IServiceProvider pattern, which allows for interception or redefinition of scheduler services. /// </para> /// <para> /// Consider using the <see cref="SchedulePeriodic"/> extension methods for <see cref="IScheduler"/> in case periodic scheduling /// is required and emulation of periodic behavior using other scheduler services is desirable. Use of this method is recommended /// for best-effort use of the periodic scheduling service, where the caller falls back to not using periodic scheduling if this /// facility wasn't found. /// </para> /// </remarks> public static ISchedulerPeriodic? AsPeriodic(this IScheduler scheduler) => As<ISchedulerPeriodic>(scheduler); private static T? As<T>(IScheduler scheduler) where T : class { if (scheduler is IServiceProvider svc) { return (T?)svc.GetService(typeof(T)); } return null; } } }
Scheduler
csharp
npgsql__efcore.pg
test/EFCore.PG.FunctionalTests/Query/AdHocJsonQueryNpgsqlTest.cs
{ "start": 10858, "end": 11001 }
public class ____ { public int Id { get; set; } public TypesJsonEntity JsonEntity { get; set; } }
TypesContainerEntity
csharp
MassTransit__MassTransit
tests/MassTransit.RabbitMqTransport.Tests/Mandatory_Specs.cs
{ "start": 158, "end": 515 }
public class ____ : RabbitMqTestFixture { [Test] public async Task Should_throw_an_exception() { Assert.That(async () => await Bus.Publish(new NoBindingPlease(), context => context.Mandatory = true), Throws.TypeOf<MessageReturnedException>()); }
When_mandatory_is_specified_and_no_binding_exists
csharp
dotnet__machinelearning
src/Microsoft.ML.AutoML/EstimatorExtensions/EstimatorExtensionCatalog.cs
{ "start": 693, "end": 2287 }
internal class ____ { private static readonly IDictionary<EstimatorName, Type> _namesToExtensionTypes = new Dictionary<EstimatorName, Type>() { { EstimatorName.ColumnConcatenating, typeof(ColumnConcatenatingExtension) }, { EstimatorName.ColumnCopying, typeof(ColumnCopyingExtension) }, { EstimatorName.KeyToValueMapping, typeof(KeyToValueMappingExtension) }, { EstimatorName.Hashing, typeof(HashingExtension) }, { EstimatorName.MissingValueIndicating, typeof(MissingValueIndicatingExtension) }, { EstimatorName.MissingValueReplacing, typeof(MissingValueReplacingExtension) }, { EstimatorName.Normalizing, typeof(NormalizingExtension) }, { EstimatorName.OneHotEncoding, typeof(OneHotEncodingExtension) }, { EstimatorName.OneHotHashEncoding, typeof(OneHotHashEncodingExtension) }, { EstimatorName.TextFeaturizing, typeof(TextFeaturizingExtension) }, { EstimatorName.TypeConverting, typeof(TypeConvertingExtension) }, { EstimatorName.ValueToKeyMapping, typeof(ValueToKeyMappingExtension) }, { EstimatorName.RawByteImageLoading, typeof(RawByteImageLoading) }, { EstimatorName.ImageLoading, typeof(ImageLoading) } }; public static IEstimatorExtension GetExtension(EstimatorName estimatorName) { var extType = _namesToExtensionTypes[estimatorName]; return (IEstimatorExtension)Activator.CreateInstance(extType); } } }
EstimatorExtensionCatalog
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue2953.cs
{ "start": 1617, "end": 1810 }
internal class ____ : ViewCell { public ItemCell() { var label = new Label { BackgroundColor = Colors.Aqua }; label.SetBinding(Label.TextProperty, "."); View = label; } } }
ItemCell
csharp
nunit__nunit
src/NUnitFramework/testdata/TestFixtureData.cs
{ "start": 10157, "end": 10282 }
public abstract class ____ { [Test] public void SomeTest() { } }
AbstractFixtureBase
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.CodeGeneration.CSharp.Tests/ObsoleteTests.cs
{ "start": 372, "end": 577 }
public class ____ { [Obsolete("Reason property is \"obsolete\"")] public string Property { get; set; } } [Obsolete]
ObsoletePropertyWithMessageTestClass
csharp
dotnet__aspnetcore
src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerExtensions.cs
{ "start": 575, "end": 6454 }
public static class ____ { /// <summary> /// Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. /// The request will not be re-executed if the response has already started. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app) { ArgumentNullException.ThrowIfNull(app); return SetExceptionHandlerMiddleware(app, options: null); } /// <summary> /// Adds a middleware to the pipeline that will catch exceptions, log them, reset the request path, and re-execute the request. /// The request will not be re-executed if the response has already started. /// </summary> /// <param name="app"></param> /// <param name="errorHandlingPath"></param> /// <returns></returns> public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, string errorHandlingPath) { ArgumentNullException.ThrowIfNull(app); return app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandlingPath = new PathString(errorHandlingPath) }); } /// <summary> /// Adds a middleware to the pipeline that will catch exceptions, log them, reset the request path, and re-execute the request. /// The request will not be re-executed if the response has already started. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/>.</param> /// <param name="errorHandlingPath">The <see cref="string"/> path to the endpoint that will handle the exception.</param> /// <param name="createScopeForErrors">Whether or not to create a new <see cref="IServiceProvider"/> scope.</param> /// <returns></returns> public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, string errorHandlingPath, bool createScopeForErrors) { ArgumentNullException.ThrowIfNull(app); return app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandlingPath = new PathString(errorHandlingPath), CreateScopeForErrors = createScopeForErrors }); } /// <summary> /// Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. /// The request will not be re-executed if the response has already started. /// </summary> /// <param name="app"></param> /// <param name="configure"></param> /// <returns></returns> public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, Action<IApplicationBuilder> configure) { ArgumentNullException.ThrowIfNull(app); ArgumentNullException.ThrowIfNull(configure); var subAppBuilder = app.New(); configure(subAppBuilder); var exceptionHandlerPipeline = subAppBuilder.Build(); return app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandler = exceptionHandlerPipeline }); } /// <summary> /// Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. /// The request will not be re-executed if the response has already started. /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <returns></returns> public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, ExceptionHandlerOptions options) { ArgumentNullException.ThrowIfNull(app); ArgumentNullException.ThrowIfNull(options); var iOptions = Options.Create(options); return SetExceptionHandlerMiddleware(app, iOptions); } private static IApplicationBuilder SetExceptionHandlerMiddleware(IApplicationBuilder app, IOptions<ExceptionHandlerOptions>? options) { var problemDetailsService = app.ApplicationServices.GetService<IProblemDetailsService>(); app.Properties["analysis.NextMiddlewareName"] = "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware"; // Only use this path if there's a global router (in the 'WebApplication' case). if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null) { return app.Use(next => { var loggerFactory = app.ApplicationServices.GetRequiredService<ILoggerFactory>(); var diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>(); var exceptionHandlers = app.ApplicationServices.GetRequiredService<IEnumerable<IExceptionHandler>>(); var meterFactory = app.ApplicationServices.GetRequiredService<IMeterFactory>(); if (options is null) { options = app.ApplicationServices.GetRequiredService<IOptions<ExceptionHandlerOptions>>(); } if (!string.IsNullOrEmpty(options.Value.ExceptionHandlingPath) && options.Value.ExceptionHandler is null) { var newNext = RerouteHelper.Reroute(app, routeBuilder, next); // store the pipeline for the error case options.Value.ExceptionHandler = newNext; } return new ExceptionHandlerMiddlewareImpl(next, loggerFactory, options, diagnosticListener, exceptionHandlers, meterFactory, problemDetailsService).Invoke; }); } if (options is null) { return app.UseMiddleware<ExceptionHandlerMiddlewareImpl>(); } return app.UseMiddleware<ExceptionHandlerMiddlewareImpl>(options); } }
ExceptionHandlerExtensions
csharp
AvaloniaUI__Avalonia
src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/XamlIlAvaloniaPropertyHelper.cs
{ "start": 12137, "end": 13560 }
class ____ : AvaloniaPropertyCustomSetter { public BindingSetter( AvaloniaXamlIlWellKnownTypes types, IXamlType declaringType, IXamlField avaloniaProperty) : base(types, declaringType, avaloniaProperty, false, [types.IBinding]) { } public override void Emit(IXamlILEmitter emitter) { using (var bloc = emitter.LocalsPool.GetLocal(Types.IBinding)) emitter .Stloc(bloc.Local) .Ldsfld(AvaloniaProperty) .Ldloc(bloc.Local); EmitAnchorAndBind(emitter); } public override void EmitWithArguments( XamlEmitContextWithLocals<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter emitter, IReadOnlyList<IXamlAstValueNode> arguments) { emitter.Ldsfld(AvaloniaProperty); context.Emit(arguments[0], emitter, Parameters[0]); EmitAnchorAndBind(emitter); } private void EmitAnchorAndBind(IXamlILEmitter emitter) { emitter .Ldnull() // TODO: provide anchor? .EmitCall(Types.AvaloniaObjectBindMethod, true); } }
BindingSetter
csharp
neuecc__MessagePack-CSharp
tests/MessagePack.Tests/DynamicObjectResolverTests.cs
{ "start": 28491, "end": 28683 }
public class ____ : BaseClass { [DataMember] public string Name { get; set; } } #if !UNITY_2018_3_OR_NEWER [MessagePackObject]
DerivedClass
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.DataIngestion/Processors/ClassificationEnricher.cs
{ "start": 508, "end": 747 }
class ____ a chat-based language model to analyze the content of document chunks and assign a /// single, most relevant classification label. The classification is performed using a predefined set of classes, with /// an optional fallback
uses
csharp
OrchardCMS__OrchardCore
test/OrchardCore.Tests/Localization/CultureScopeTests.cs
{ "start": 76, "end": 1885 }
public class ____ { [Fact] public void CultureScopeSetsUICultureIfNotProvided() { // Arrange var culture = "ar-YE"; // Act using var cultureScope = CultureScope.Create(culture); // Assert Assert.Equal(culture, CultureInfo.CurrentCulture.Name); Assert.Equal(culture, CultureInfo.CurrentUICulture.Name); } [Fact] public void CultureScopeSetsBothCultureAndUICulture() { // Arrange var culture = "ar"; var uiCulture = "ar-YE"; // Act using var cultureScope = CultureScope.Create(culture, uiCulture); // Assert Assert.Equal(culture, CultureInfo.CurrentCulture.Name); Assert.Equal(uiCulture, CultureInfo.CurrentUICulture.Name); } [Fact] public void CultureScopeSetsOrginalCulturesAfterEndOfScope() { // Arrange var culture = CultureInfo.CurrentCulture; var uiCulture = CultureInfo.CurrentUICulture; // Act using (var cultureScope = CultureScope.Create("FR")) { } // Assert Assert.Equal(culture, CultureInfo.CurrentCulture); Assert.Equal(uiCulture, CultureInfo.CurrentUICulture); } [Fact] public async Task CultureScopeSetsOrginalCulturesOnException() { // Arrange var culture = CultureInfo.CurrentCulture; var uiCulture = CultureInfo.CurrentUICulture; // Act & Assert await Assert.ThrowsAsync<Exception>(Task () => { using var cultureScope = CultureScope.Create("FR"); throw new Exception("Something goes wrong!!"); }); Assert.Equal(culture, CultureInfo.CurrentCulture); Assert.Equal(uiCulture, CultureInfo.CurrentUICulture); } }
CultureScopeTests
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Forms/GraphQL/LabelPartQueryObjectType.cs
{ "start": 92, "end": 353 }
public class ____ : ObjectGraphType<LabelPart> { public LabelPartQueryObjectType() { Name = "LabelPart"; Field(x => x.For, nullable: true); Field("value", context => context.ContentItem.DisplayText); } }
LabelPartQueryObjectType
csharp
dotnet__aspnetcore
src/Identity/Extensions.Core/src/PasswordHasherOptions.cs
{ "start": 290, "end": 1368 }
public class ____ { private static readonly RandomNumberGenerator _defaultRng = RandomNumberGenerator.Create(); // secure PRNG /// <summary> /// Gets or sets the compatibility mode used when hashing passwords. Defaults to 'ASP.NET Identity version 3'. /// </summary> /// <value> /// The compatibility mode used when hashing passwords. /// </value> public PasswordHasherCompatibilityMode CompatibilityMode { get; set; } = PasswordHasherCompatibilityMode.IdentityV3; /// <summary> /// Gets or sets the number of iterations used when hashing passwords using PBKDF2. Default is 100,000. /// </summary> /// <value> /// The number of iterations used when hashing passwords using PBKDF2. /// </value> /// <remarks> /// This value is only used when the compatibility mode is set to 'V3'. /// The value must be a positive integer. /// </remarks> public int IterationCount { get; set; } = 100_000; // for unit testing internal RandomNumberGenerator Rng { get; set; } = _defaultRng; }
PasswordHasherOptions
csharp
dotnet__aspnetcore
src/Servers/Connections.Abstractions/src/BaseConnectionContext.cs
{ "start": 420, "end": 2249 }
public abstract class ____ : IAsyncDisposable { /// <summary> /// Gets or sets a unique identifier to represent this connection in trace logs. /// </summary> public abstract string ConnectionId { get; set; } /// <summary> /// Gets the collection of features provided by the server and middleware available on this connection. /// </summary> public abstract IFeatureCollection Features { get; } /// <summary> /// Gets or sets a key/value collection that can be used to share data within the scope of this connection. /// </summary> public abstract IDictionary<object, object?> Items { get; set; } /// <summary> /// Triggered when the client connection is closed. /// </summary> public virtual CancellationToken ConnectionClosed { get; set; } /// <summary> /// Gets or sets the local endpoint for this connection. /// </summary> public virtual EndPoint? LocalEndPoint { get; set; } /// <summary> /// Gets or sets the remote endpoint for this connection. /// </summary> public virtual EndPoint? RemoteEndPoint { get; set; } /// <summary> /// Aborts the underlying connection. /// </summary> public abstract void Abort(); /// <summary> /// Aborts the underlying connection. /// </summary> /// <param name="abortReason">A <see cref="ConnectionAbortedException"/> describing the reason the connection is being terminated.</param> public abstract void Abort(ConnectionAbortedException abortReason); /// <summary> /// Releases resources for the underlying connection. /// </summary> /// <returns>A <see cref="ValueTask"/> that completes when resources have been released.</returns> public virtual ValueTask DisposeAsync() { return default; } }
BaseConnectionContext
csharp
neuecc__MessagePack-CSharp
src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Formatters.cs
{ "start": 35760, "end": 36613 }
struct ____ supported"); } var length = reader.ReadArrayHeader(); var __x__ = default(int); var __y__ = default(int); for (int i = 0; i < length; i++) { var key = i; switch (key) { case 0: __x__ = reader.ReadInt32(); break; case 1: __y__ = reader.ReadInt32(); break; default: reader.Skip(); break; } } var ____result = new global::UnityEngine.Vector2Int(__x__, __y__); ____result.x = __x__; ____result.y = __y__; return ____result; } }
not
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ErrorRestTests.cs
{ "start": 4498, "end": 4602 }
public class ____ : IReturn<ActionError> { public string Id { get; set; } }
ActionError
csharp
DapperLib__Dapper
tests/Dapper.Tests/SharedTypes/SomeType.cs
{ "start": 30, "end": 140 }
public class ____ { public int A { get; set; } public string? B { get; set; } } }
SomeType
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.DependencyInjection.AutoActivation.Tests/Helpers/AnotherFakeServiceCounter.cs
{ "start": 205, "end": 314 }
public class ____ : IAnotherFakeServiceCounter { public int Counter { get; set; } }
AnotherFakeServiceCounter
csharp
DuendeSoftware__IdentityServer
identity-server/src/IdentityServer/Constants.cs
{ "start": 216, "end": 2159 }
internal static class ____ { public const string IdentityServerName = "Duende.IdentityServer"; public const string IdentityServerAuthenticationType = IdentityServerName; public const string ExternalAuthenticationMethod = "external"; public const string DefaultHashAlgorithm = "SHA256"; public static readonly TimeSpan DefaultCookieTimeSpan = TimeSpan.FromHours(10); public static readonly TimeSpan DefaultCacheDuration = TimeSpan.FromMinutes(60); public static readonly List<string> SupportedResponseTypes = new List<string> { OidcConstants.ResponseTypes.Code, OidcConstants.ResponseTypes.Token, OidcConstants.ResponseTypes.IdToken, OidcConstants.ResponseTypes.IdTokenToken, OidcConstants.ResponseTypes.CodeIdToken, OidcConstants.ResponseTypes.CodeToken, OidcConstants.ResponseTypes.CodeIdTokenToken }; public static readonly Dictionary<string, string> ResponseTypeToGrantTypeMapping = new Dictionary<string, string> { { OidcConstants.ResponseTypes.Code, GrantType.AuthorizationCode }, { OidcConstants.ResponseTypes.Token, GrantType.Implicit }, { OidcConstants.ResponseTypes.IdToken, GrantType.Implicit }, { OidcConstants.ResponseTypes.IdTokenToken, GrantType.Implicit }, { OidcConstants.ResponseTypes.CodeIdToken, GrantType.Hybrid }, { OidcConstants.ResponseTypes.CodeToken, GrantType.Hybrid }, { OidcConstants.ResponseTypes.CodeIdTokenToken, GrantType.Hybrid } }; public static readonly List<string> AllowedGrantTypesForAuthorizeEndpoint = new List<string> { GrantType.AuthorizationCode, GrantType.Implicit, GrantType.Hybrid }; public static readonly List<string> SupportedCodeChallengeMethods = new List<string> { OidcConstants.CodeChallengeMethods.Plain, OidcConstants.CodeChallengeMethods.Sha256 };
Constants
csharp
mysql-net__MySqlConnector
src/MySqlConnector/Core/ServerSession.cs
{ "start": 77303, "end": 86506 }
internal sealed class ____ { public X509RevocationMode CertificateRevocationCheckMode { get; set; } public X509CertificateCollection? ClientCertificates { get; set; } public SslProtocols EnabledSslProtocols { get; set; } public string? TargetHost { get; set; } } #endif // Some servers are exposed through a proxy, which handles the initial handshake and gives the proxy's // server version and thread ID. Detect this situation and return `true` if the real server's details should // be requested after connecting (which takes an extra roundtrip). private bool ShouldGetRealServerDetails(ConnectionSettings cs) { // currently hardcoded to the version(s) returned by the Azure Database for MySQL proxy if (ServerVersion.OriginalString is "5.6.47.0" or "5.6.42.0" or "5.6.39.0") return true; // detect Azure Database for MySQL DNS suffixes, if a "user@host" user ID is being used if (cs.ConnectionProtocol == MySqlConnectionProtocol.Sockets && cs.UserID.Contains('@')) { return HostName.EndsWith(".mysql.database.azure.com", StringComparison.OrdinalIgnoreCase) || HostName.EndsWith(".database.windows.net", StringComparison.OrdinalIgnoreCase) || HostName.EndsWith(".mysql.database.chinacloudapi.cn", StringComparison.OrdinalIgnoreCase); } // detect AWS RDS Proxy, if hostname like <name>.proxy-<random-chars>.<region>.rds.amazonaws.com if (HostName.EndsWith(".rds.amazonaws.com", StringComparison.OrdinalIgnoreCase) && HostName.AsSpan().Contains(".proxy-".AsSpan(), StringComparison.OrdinalIgnoreCase)) { return true; } return false; } private async Task GetRealServerDetailsAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { Log.DetectedProxy(m_logger, Id); try { var payload = SupportsQueryAttributes ? s_selectConnectionIdVersionWithAttributesPayload : s_selectConnectionIdVersionNoAttributesPayload; await SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false); // column count: 2 _ = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); // CONNECTION_ID() and VERSION() columns _ = await ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); _ = await ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); if (!SupportsDeprecateEof) { payload = await ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); _ = EofPayload.Create(payload.Span); } // first (and only) row payload = await ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); var reader = new ByteArrayReader(payload.Span); var length = reader.ReadLengthEncodedIntegerOrNull(); var connectionId = (length != -1 && Utf8Parser.TryParse(reader.ReadByteString(length), out int id, out _)) ? id : default(int?); length = reader.ReadLengthEncodedIntegerOrNull(); var serverVersion = length != -1 ? new ServerVersion(reader.ReadByteString(length)) : default; // OK/EOF payload payload = await ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); if (OkPayload.IsOk(payload.Span, this)) OkPayload.Verify(payload.Span, this); else EofPayload.Create(payload.Span); if (connectionId is int newConnectionId && serverVersion is not null) { Log.ChangingConnectionId(m_logger, Id, ConnectionId, newConnectionId, ServerVersion.OriginalString, serverVersion.OriginalString); ConnectionId = newConnectionId; ServerVersion = serverVersion; } } catch (MySqlException ex) { Log.FailedToGetConnectionId(m_logger, ex, Id); } } private void ShutdownSocket() { Log.ClosingStreamSocket(m_logger, Id); Utility.Dispose(ref m_payloadHandler); Utility.Dispose(ref m_stream); SafeDispose(ref m_tcpClient); SafeDispose(ref m_socket); Utility.Dispose(ref m_clientCertificate); m_activityTags.Clear(); } /// <summary> /// Disposes and sets <paramref name="disposable"/> to <c>null</c>, ignoring any /// <see cref="IOException"/> or <see cref="SocketException"/> that is thrown. /// </summary> /// <typeparam name="T">An <see cref="IDisposable"/> type.</typeparam> /// <param name="disposable">The object to dispose.</param> private static void SafeDispose<T>(ref T? disposable) where T : class, IDisposable { if (disposable is not null) { try { disposable.Dispose(); } catch (IOException) { } catch (SocketException) { } disposable = null; } } internal void SetFailed(Exception exception) { Log.SettingStateToFailed(m_logger, exception, Id); lock (m_lock) m_state = State.Failed; if (OwningConnection is not null && OwningConnection.TryGetTarget(out var connection)) connection.SetState(ConnectionState.Broken); } private void VerifyState(State state) { if (m_state != state) { ExpectedSessionState1(m_logger, Id, state, m_state); throw new InvalidOperationException($"Expected state to be {state} but was {m_state}."); } } private void VerifyState(State state1, State state2, State state3, State state4, State state5, State state6) { if (m_state != state1 && m_state != state2 && m_state != state3 && m_state != state4 && m_state != state5 && m_state != state6) { ExpectedSessionState6(m_logger, Id, state1, state2, state3, state4, state5, state6, m_state); throw new InvalidOperationException($"Expected state to be ({state1}|{state2}|{state3}|{state4}|{state5}|{state6}) but was {m_state}."); } } internal bool SslIsEncrypted => m_sslStream?.IsEncrypted is true; internal bool SslIsSigned => m_sslStream?.IsSigned is true; internal bool SslIsAuthenticated => m_sslStream?.IsAuthenticated is true; internal bool SslIsMutuallyAuthenticated => m_sslStream?.IsMutuallyAuthenticated is true; internal SslProtocols SslProtocol => m_sslStream?.SslProtocol ?? SslProtocols.None; private byte[] CreateConnectionAttributes(string? programName) { Log.CreatingConnectionAttributes(m_logger, Id); var attributesWriter = new ByteBufferWriter(); attributesWriter.WriteLengthEncodedString("_client_name"); attributesWriter.WriteLengthEncodedString("MySqlConnector"); attributesWriter.WriteLengthEncodedString("_client_version"); var version = typeof(ServerSession).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion; var plusIndex = version.IndexOf('+'); if (plusIndex != -1) version = version[..plusIndex]; attributesWriter.WriteLengthEncodedString(version); try { Utility.GetOSDetails(out var os, out var osDescription, out var architecture); if (os is not null) { attributesWriter.WriteLengthEncodedString("_os"); attributesWriter.WriteLengthEncodedString(os); } attributesWriter.WriteLengthEncodedString("_os_details"); attributesWriter.WriteLengthEncodedString(osDescription); attributesWriter.WriteLengthEncodedString("_platform"); attributesWriter.WriteLengthEncodedString(architecture); } catch (PlatformNotSupportedException) { } #if NET5_0_OR_GREATER var processId = Environment.ProcessId; #else using var process = Process.GetCurrentProcess(); var processId = process.Id; #endif attributesWriter.WriteLengthEncodedString("_pid"); attributesWriter.WriteLengthEncodedString(processId.ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(programName)) { attributesWriter.WriteLengthEncodedString("program_name"); attributesWriter.WriteLengthEncodedString(programName!); } using var connectionAttributesPayload = attributesWriter.ToPayloadData(); var connectionAttributes = connectionAttributesPayload.Span; var writer = new ByteBufferWriter(connectionAttributes.Length + 9); writer.WriteLengthEncodedInteger((ulong) connectionAttributes.Length); writer.Write(connectionAttributes); using var payload = writer.ToPayloadData(); return payload.Memory.ToArray(); } private MySqlException CreateExceptionForErrorPayload(ReadOnlySpan<byte> span) { var errorPayload = ErrorPayload.Create(span); Log.ErrorPayload(m_logger, Id, errorPayload.ErrorCode, errorPayload.State, errorPayload.Message); var exception = errorPayload.ToException(); if (exception.ErrorCode is MySqlErrorCode.ClientInteractionTimeout) SetFailed(exception); return exception; } private void ClearPreparedStatements() { if (m_preparedStatements is not null) { foreach (var pair in m_preparedStatements) pair.Value.Dispose(); m_preparedStatements.Clear(); } } private string GetPassword(ConnectionSettings cs, MySqlConnection connection) { if (cs.Password.Length != 0) return cs.Password; if (connection.ProvidePasswordCallback is { } passwordProvider) { try { Log.ObtainingPasswordViaProvidePasswordCallback(m_logger, Id); return passwordProvider(new(HostName, cs.Port, cs.UserID, cs.Database)); } catch (Exception ex) { Log.FailedToObtainPassword(m_logger, ex, Id, ex.Message); throw new MySqlException(MySqlErrorCode.ProvidePasswordCallbackFailed, "Failed to obtain password via ProvidePasswordCallback", ex); } } return ""; }
SslClientAuthenticationOptions
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Equivalency.Specs/NestedPropertiesSpecs.cs
{ "start": 4843, "end": 5204 }
public class ____ { public StringContainer(string mainValue, string subValue = null) { MainValue = mainValue; SubValues = [new StringSubContainer { SubValue = subValue }]; } public string MainValue { get; set; } public IList<StringSubContainer> SubValues { get; set; } }
StringContainer
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Indexing.Abstractions/DocumentIndex.cs
{ "start": 185, "end": 2416 }
public class ____ { public string Id { get; private set; } public DocumentIndex(string id) { ArgumentException.ThrowIfNullOrEmpty(id); Id = id; } public List<DocumentIndexEntry> Entries { get; } = []; public void Set(string name, string value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Text, options)); } public void Set(string name, IHtmlContent value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Text, options)); } public void Set(string name, DateTimeOffset? value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.DateTime, options)); } public void Set(string name, int? value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Integer, options)); } public void Set(string name, bool? value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Boolean, options)); } public void Set(string name, object value, DocumentIndexOptions options, Dictionary<string, object> metadata = null) { Entries.Add(new DocumentIndexEntry(name, value, Types.Complex, options) { Metadata = metadata, }); } public void Set(string name, float[] value, int dimensions, DocumentIndexOptions options, Dictionary<string, object> metadata = null) { Entries.Add(new DocumentIndexEntry(name, value, Types.Vector, options) { Metadata = metadata, Dimensions = dimensions, }); } public void Set(string name, double? value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Number, options)); } public void Set(string name, decimal? value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.Number, options)); } public void Set(string name, GeoPoint value, DocumentIndexOptions options) { Entries.Add(new DocumentIndexEntry(name, value, Types.GeoPoint, options)); }
DocumentIndex
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Server/CrudUtils.cs
{ "start": 13808, "end": 13981 }
public class ____ { public string? Schema { get; set; } public string? NamedConnection { get; set; } public List<TableSchema> Tables { get; set; } = []; }
DbSchema
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/PropertyStore/EffectiveValue`1.cs
{ "start": 506, "end": 11106 }
internal sealed class ____<T> : EffectiveValue { private readonly StyledPropertyMetadata<T> _metadata; private T? _baseValue; private readonly UncommonFields? _uncommon; public EffectiveValue( AvaloniaObject owner, StyledProperty<T> property, EffectiveValue<T>? inherited) : base(property) { Priority = BindingPriority.Unset; BasePriority = BindingPriority.Unset; _metadata = property.GetMetadata(owner); var value = inherited is null ? _metadata.DefaultValue : inherited.Value; if (_metadata.CoerceValue is { } coerce) { HasCoercion = true; _uncommon = new() { _coerce = coerce, _uncoercedValue = value, _uncoercedBaseValue = value, }; } Value = value; } /// <summary> /// Gets the current effective value. /// </summary> public new T Value { get; private set; } public override void SetAndRaise( ValueStore owner, IValueEntry value, BindingPriority priority) { Debug.Assert(priority != BindingPriority.LocalValue); UpdateValueEntry(value, priority); SetAndRaiseCore(owner, (StyledProperty<T>)value.Property, GetValue(value), priority); if (priority > BindingPriority.LocalValue && value.GetDataValidationState(out var state, out var error)) { owner.Owner.OnUpdateDataValidation(value.Property, state, error); } } public override void SetLocalValueAndRaise( ValueStore owner, AvaloniaProperty property, object? value) { SetLocalValueAndRaise(owner, (StyledProperty<T>)property, (T)value!); } public void SetLocalValueAndRaise( ValueStore owner, StyledProperty<T> property, T value) { SetAndRaiseCore(owner, property, value, BindingPriority.LocalValue); } public void SetCurrentValueAndRaise( ValueStore owner, StyledProperty<T> property, T value) { SetAndRaiseCore(owner, property, value, Priority, isOverriddenCurrentValue: true); } public void SetCoercedDefaultValueAndRaise( ValueStore owner, StyledProperty<T> property, T value) { SetAndRaiseCore(owner, property, value, Priority, isCoercedDefaultValue: true); } public bool TryGetBaseValue([MaybeNullWhen(false)] out T value) { value = _baseValue!; return BasePriority != BindingPriority.Unset; } public override void RaiseInheritedValueChanged( AvaloniaObject owner, AvaloniaProperty property, EffectiveValue? oldValue, EffectiveValue? newValue) { Debug.Assert(oldValue is not null || newValue is not null); var p = (StyledProperty<T>)property; var o = oldValue is not null ? ((EffectiveValue<T>)oldValue).Value : _metadata.DefaultValue; var n = newValue is not null ? ((EffectiveValue<T>)newValue).Value : _metadata.DefaultValue; var priority = newValue is not null ? BindingPriority.Inherited : BindingPriority.Unset; if (!EqualityComparer<T>.Default.Equals(o, n)) { owner.RaisePropertyChanged(p, o, n, priority, true); } } public override void RemoveAnimationAndRaise(ValueStore owner, AvaloniaProperty property) { Debug.Assert(Priority != BindingPriority.Animation); Debug.Assert(BasePriority != BindingPriority.Unset); UpdateValueEntry(null, BindingPriority.Animation); SetAndRaiseCore(owner, (StyledProperty<T>)property, _baseValue!, BasePriority); } public override void CoerceValue(ValueStore owner, AvaloniaProperty property) { if (_uncommon is null) return; SetAndRaiseCore( owner, (StyledProperty<T>)property, _uncommon._uncoercedValue!, Priority, _uncommon._uncoercedBaseValue!, BasePriority); } public override void DisposeAndRaiseUnset(ValueStore owner, AvaloniaProperty property) { var clearDataValidation = ValueEntry?.GetDataValidationState(out _, out _) ?? BaseValueEntry?.GetDataValidationState(out _, out _) ?? false; ValueEntry?.Unsubscribe(); BaseValueEntry?.Unsubscribe(); var p = (StyledProperty<T>)property; BindingPriority priority; T newValue; if (property.Inherits && owner.TryGetInheritedValue(property, out var i)) { newValue = ((EffectiveValue<T>)i).Value; priority = BindingPriority.Inherited; } else { newValue = _metadata.DefaultValue; priority = BindingPriority.Unset; } if (!EqualityComparer<T>.Default.Equals(newValue, Value)) { owner.Owner.RaisePropertyChanged(p, Value, newValue, priority, true); if (property.Inherits) owner.OnInheritedEffectiveValueDisposed(p, Value, newValue); } if (clearDataValidation) owner.Owner.OnUpdateDataValidation(p, BindingValueType.UnsetValue, null); } protected override void CoerceDefaultValueAndRaise(ValueStore owner, AvaloniaProperty property) { Debug.Assert(_uncommon?._coerce is not null); Debug.Assert(Priority == BindingPriority.Unset); var coercedDefaultValue = _uncommon!._coerce!(owner.Owner, _metadata.DefaultValue); if (!EqualityComparer<T>.Default.Equals(_metadata.DefaultValue, coercedDefaultValue)) SetCoercedDefaultValueAndRaise(owner, (StyledProperty<T>)property, coercedDefaultValue); } protected override object? GetBoxedValue() => Value; private static T GetValue(IValueEntry entry) { if (entry is IValueEntry<T> typed) return typed.GetValue(); else return (T)entry.GetValue()!; } private void SetAndRaiseCore( ValueStore owner, StyledProperty<T> property, T value, BindingPriority priority, bool isOverriddenCurrentValue = false, bool isCoercedDefaultValue = false) { var oldValue = Value; var valueChanged = false; var baseValueChanged = false; var v = value; IsOverridenCurrentValue = isOverriddenCurrentValue; IsCoercedDefaultValue = isCoercedDefaultValue; if (!isCoercedDefaultValue && _uncommon?._coerce is { } coerce) v = coerce(owner.Owner, value); if (priority <= Priority) { valueChanged = !EqualityComparer<T>.Default.Equals(Value, v); Value = v; Priority = priority; if (!isCoercedDefaultValue && _uncommon is not null) _uncommon._uncoercedValue = value; } if (priority <= BasePriority && priority >= BindingPriority.LocalValue) { baseValueChanged = !EqualityComparer<T>.Default.Equals(_baseValue, v); _baseValue = v; BasePriority = priority; if (!isCoercedDefaultValue && _uncommon is not null) _uncommon._uncoercedBaseValue = value; } if (valueChanged) { NotifyValueChanged(owner, property, oldValue); } else if (baseValueChanged) { NotifyBaseValueChanged(owner, property); } } private void SetAndRaiseCore( ValueStore owner, StyledProperty<T> property, T value, BindingPriority priority, T baseValue, BindingPriority basePriority) { Debug.Assert(basePriority > BindingPriority.Animation); Debug.Assert(priority <= basePriority); var oldValue = Value; var valueChanged = false; var baseValueChanged = false; var v = value; var bv = baseValue; if (_uncommon?._coerce is { } coerce) { v = coerce(owner.Owner, value); if (priority != basePriority) bv = coerce(owner.Owner, baseValue); } if (!EqualityComparer<T>.Default.Equals(Value, v)) { Value = v; valueChanged = true; if (_uncommon is not null) _uncommon._uncoercedValue = value; } if (!EqualityComparer<T>.Default.Equals(_baseValue, bv)) { _baseValue = v; baseValueChanged = true; if (_uncommon is not null) _uncommon._uncoercedValue = baseValue; } Priority = priority; BasePriority = basePriority; if (valueChanged) { NotifyValueChanged(owner, property, oldValue); } if (baseValueChanged) { NotifyBaseValueChanged(owner, property); } } private void NotifyValueChanged(ValueStore owner, StyledProperty<T> property, T oldValue) { using var notifying = PropertyNotifying.Start(owner.Owner, property); owner.Owner.RaisePropertyChanged(property, oldValue, Value, Priority, true); if (property.Inherits) owner.OnInheritedEffectiveValueChanged(property, oldValue, this); } private void NotifyBaseValueChanged(ValueStore owner, StyledProperty<T> property) => owner.Owner.RaisePropertyChanged(property, default, _baseValue!, BasePriority, false);
EffectiveValue
csharp
dotnet__aspire
src/Components/Common/ManagedIdentityTokenCredentialHelpers.cs
{ "start": 236, "end": 5645 }
internal static class ____ { private const string AzureDatabaseForPostgresSqlScope = "https://ossrdbms-aad.database.windows.net/.default"; private const string AzureManagementScope = "https://management.azure.com/.default"; private static readonly TokenRequestContext s_databaseForPostgresSqlTokenRequestContext = new([AzureDatabaseForPostgresSqlScope]); private static readonly TokenRequestContext s_managementTokenRequestContext = new([AzureManagementScope]); public static bool ConfigureEntraIdAuthentication(this NpgsqlDataSourceBuilder dataSourceBuilder, TokenCredential? credential) { credential ??= new DefaultAzureCredential(); var configuredAuth = false; // The connection string requires the username to be provided. Since it will depend on the Managed Identity that is used // we attempt to get the username from the access token if it's not defined. if (string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Username)) { // Ensure to use the management scope, so the token contains user names for all managed identity types - e.g. user and service principal var token = credential.GetToken(s_managementTokenRequestContext, default); if (TryGetUsernameFromToken(token.Token, out var username)) { dataSourceBuilder.ConnectionStringBuilder.Username = username; configuredAuth = true; } else { // Otherwise check using the PostgresSql scope token = credential.GetToken(s_databaseForPostgresSqlTokenRequestContext, default); if (TryGetUsernameFromToken(token.Token, out username)) { dataSourceBuilder.ConnectionStringBuilder.Username = username; configuredAuth = true; } } // If we still don't have a username, we let Npgsql handle the error when trying to connect. // The user will be hinted to provide a username by using the configureDataSourceBuilder callback. } if (string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Password)) { // The token is not cached since it is refreshed for each new physical connection, or when it has expired. dataSourceBuilder.UsePasswordProvider( passwordProvider: _ => credential.GetToken(s_databaseForPostgresSqlTokenRequestContext, default).Token, passwordProviderAsync: async (_, ct) => (await credential.GetTokenAsync(s_databaseForPostgresSqlTokenRequestContext, default).ConfigureAwait(false)).Token ); configuredAuth = true; } return configuredAuth; } private static bool TryGetUsernameFromToken(string jwtToken, out string? username) { username = null; // Split the token into its parts (Header, Payload, Signature) var tokenParts = jwtToken.Split('.'); if (tokenParts.Length != 3) { return false; } // The payload is the second part, Base64Url encoded var payload = tokenParts[1]; // Add padding if necessary payload = AddBase64Padding(payload); // Decode the payload from Base64Url var decodedBytes = Convert.FromBase64String(payload); // Parse the decoded payload as JSON var reader = new Utf8JsonReader(decodedBytes); var payloadJson = JsonElement.ParseValue(ref reader); // Try to get the username from 'xms_mirid', 'upn', 'preferred_username', or 'unique_name' claims if (payloadJson.TryGetProperty("xms_mirid", out var xms_mirid) && xms_mirid.GetString() is string xms_miridString && ParsePrincipalName(xms_miridString) is string principalName) { username = principalName; } else if (payloadJson.TryGetProperty("upn", out var upn)) { username = upn.GetString(); } else if (payloadJson.TryGetProperty("preferred_username", out var preferredUsername)) { username = preferredUsername.GetString(); } else if (payloadJson.TryGetProperty("unique_name", out var uniqueName)) { username = uniqueName.GetString(); } return username != null; } // parse the xms_mirid claim which look like // /subscriptions/{subId}/resourcegroups/{resourceGroup}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{principalName} private static string? ParsePrincipalName(string xms_mirid) { var lastSlashIndex = xms_mirid.LastIndexOf('/'); if (lastSlashIndex == -1) { return null; } var beginning = xms_mirid.AsSpan(0, lastSlashIndex); var principalName = xms_mirid.AsSpan(lastSlashIndex + 1); if (principalName.IsEmpty || !beginning.EndsWith("providers/Microsoft.ManagedIdentity/userAssignedIdentities", StringComparison.OrdinalIgnoreCase)) { return null; } return principalName.ToString(); } private static string AddBase64Padding(string base64) => (base64.Length % 4) switch { 2 => base64 + "==", 3 => base64 + "=", _ => base64, }; }
ManagedIdentityTokenCredentialHelpers
csharp
microsoft__semantic-kernel
dotnet/src/SemanticKernel.Abstractions/KernelBuilder.cs
{ "start": 231, "end": 1589 }
internal sealed class ____ : IKernelBuilder, IKernelBuilderPlugins { /// <summary>The collection of services to be available through the <see cref="Kernel"/>.</summary> private IServiceCollection? _services; /// <summary>Initializes a new instance of the <see cref="KernelBuilder"/>.</summary> public KernelBuilder() { this.AllowBuild = true; } /// <summary>Initializes a new instance of the <see cref="KernelBuilder"/>.</summary> /// <param name="services"> /// The <see cref="IServiceCollection"/> to wrap and use for building the <see cref="Kernel"/>. /// </param> public KernelBuilder(IServiceCollection services) { Verify.NotNull(services); this._services = services; } /// <summary>Whether to allow a call to Build.</summary> /// <remarks>As a minor aid to help avoid misuse, we try to prevent Build from being called on instances returned from AddKernel.</remarks> internal bool AllowBuild { get; } /// <summary>Gets the collection of services to be built into the <see cref="Kernel"/>.</summary> public IServiceCollection Services => this._services ??= new ServiceCollection(); /// <summary>Gets a builder for plugins to be built as services into the <see cref="Kernel"/>.</summary> public IKernelBuilderPlugins Plugins => this; }
KernelBuilder
csharp
icsharpcode__ILSpy
ILSpy.AddIn.Shared/Guids.cs
{ "start": 86, "end": 499 }
static class ____ { #if VS2022 public const string guidILSpyAddInPkgString = "ebf12ca7-a1fd-4aee-a894-4a0c5682fc2f"; #else public const string guidILSpyAddInPkgString = "a9120dbe-164a-4891-842f-fb7829273838"; #endif public const string guidILSpyAddInCmdSetString = "85ddb8ca-a842-4b1c-ba1a-94141fdf19d0"; public static readonly Guid guidILSpyAddInCmdSet = new Guid(guidILSpyAddInCmdSetString); }; }
GuidList
csharp
dotnet__aspire
src/Aspire.Hosting/PublisherDistributedApplicationBuilderExtensions.cs
{ "start": 346, "end": 2164 }
internal static class ____ { /// <summary> /// Adds a publisher to the distributed application for use by the Aspire CLI. /// </summary> /// <typeparam name="TPublisher">The type of the publisher.</typeparam> /// <typeparam name="TPublisherOptions">The type of the publisher.</typeparam> /// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>. </param> /// <param name="name">The name of the publisher.</param> /// <param name="configureOptions">Callback to configure options for the publisher.</param> [Obsolete("IDistributedApplicationPublisher is obsolete. Use PipelineStep where applicable.")] internal static IDistributedApplicationBuilder AddPublisher<TPublisher, TPublisherOptions>(this IDistributedApplicationBuilder builder, string name, Action<TPublisherOptions>? configureOptions = null) where TPublisher : class, IDistributedApplicationPublisher where TPublisherOptions : class { // TODO: We need to add validation here since this needs to be something we refer to on the CLI. builder.Services.AddKeyedSingleton<IDistributedApplicationPublisher, TPublisher>(name); builder.Eventing.Subscribe<PublisherAdvertisementEvent>((e, ct) => { e.AddAdvertisement(name); return Task.CompletedTask; }); if (configureOptions is not null) { builder.Services.Configure(name, configureOptions); } builder.Services.Configure<TPublisherOptions>(name, builder.Configuration.GetSection(nameof(PublishingOptions.Publishing))); builder.Services.Configure<TPublisherOptions>(name, options => { configureOptions?.Invoke(options); }); return builder; } }
PublisherDistributedApplicationBuilderExtensions
csharp
dotnet__orleans
src/api/Orleans.Core/Orleans.Core.cs
{ "start": 79738, "end": 81334 }
partial class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<Invokable_IMembershipTable_GrainReference_B1A52D2B>, global::Orleans.Serialization.Codecs.IFieldCodec { public Codec_Invokable_IMembershipTable_GrainReference_B1A52D2B(global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { } public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, Invokable_IMembershipTable_GrainReference_B1A52D2B instance) { } public Invokable_IMembershipTable_GrainReference_B1A52D2B ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; } public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, Invokable_IMembershipTable_GrainReference_B1A52D2B instance) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, Invokable_IMembershipTable_GrainReference_B1A52D2B value) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } } [System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public sealed
Codec_Invokable_IMembershipTable_GrainReference_B1A52D2B
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Specs/Primitives/DateTimeOffsetAssertionSpecs.cs
{ "start": 774, "end": 1327 }
public class ____ { [Fact] public void Should_throw_a_helpful_error_when_accidentally_using_equals() { // Arrange DateTimeOffset someDateTimeOffset = new(2022, 9, 25, 13, 48, 42, 0, TimeSpan.Zero); // Act var action = () => someDateTimeOffset.Should().Equals(null); // Assert action.Should().Throw<NotSupportedException>() .WithMessage("Equals is not part of Fluent Assertions. Did you mean Be() instead?"); } } }
Miscellaneous
csharp
dotnet__aspire
tests/ConfigurationSchemaGenerator.Tests/GeneratorTests.cs
{ "start": 17775, "end": 18179 }
public sealed class ____ { public TreeOfString TestProperty1 { get; } = new(); public IDictionary<string, TreeOfString> TestProperty2 { get; } = new Dictionary<string, TreeOfString>(StringComparer.OrdinalIgnoreCase); } [DebuggerDisplay("{ToString(),nq}")] [TypeConverter(typeof(TreeOfStringConverter))]
TestSettings
csharp
unoplatform__uno
src/Uno.UI/UI/Input/WinRT/PointerPointProperties.cs
{ "start": 463, "end": 9227 }
private static class ____ { // Buttons // Note: Buttons must be first flags for the HasMultipleButtonsPressed to work public const int LeftButton = 1; // This has to be the first one, as it's the most common public const int MiddleButton = 1 << 1; public const int RightButton = 1 << 2; public const int XButton1 = 1 << 3; public const int XButton2 = 1 << 4; public const int BarrelButton = 1 << 5; public const int ButtonsCount = 6; public const int AllButtons = LeftButton | MiddleButton | RightButton | XButton1 | XButton2 | BarrelButton; // Pointer kind public const int HorizontalMouseWheel = 1 << 6; public const int Eraser = 1 << 7; public const int TouchPad = 1 << 8; // Misc core properties public const int Cancelled = 1 << 9; public const int Primary = 1 << 10; public const int InRange = 1 << 11; public const int TouchConfidence = 1 << 12; } internal int _flags; private bool GetFlag(int mask) => (_flags & mask) != 0; private void SetFlag(int mask, bool value) => _flags = value ? _flags | mask : _flags & ~mask; internal PointerPointProperties() { } internal PointerPointProperties(global::Windows.UI.Input.PointerPointProperties properties) { if (properties is null) { return; } _flags = properties._flags; // Set by _flags: IsPrimary = properties.IsPrimary; // Set by _flags: IsInRange = properties.IsInRange; // Set by _flags: IsLeftButtonPressed = properties.IsLeftButtonPressed; // Set by _flags: IsMiddleButtonPressed = properties.IsMiddleButtonPressed; // Set by _flags: IsRightButtonPressed = properties.IsRightButtonPressed; // Set by _flags: IsHorizontalMouseWheel = properties.IsHorizontalMouseWheel; // Set by _flags: IsXButton1Pressed = properties.IsXButton1Pressed; // Set by _flags: IsXButton2Pressed = properties.IsXButton2Pressed; // Set by _flags: IsBarrelButtonPressed = properties.IsBarrelButtonPressed; // Set by _flags: IsEraser = properties.IsEraser; // Set by _flags: IsTouchPad = properties.IsTouchPad; Pressure = properties.Pressure; Orientation = properties.Orientation; ContactRect = properties.ContactRect; // Set by _flags: TouchConfidence = properties.TouchConfidence; // Set by _flags: IsCanceled = properties.IsCanceled; PointerUpdateKind = (PointerUpdateKind)properties.PointerUpdateKind; XTilt = properties.XTilt; YTilt = properties.YTilt; MouseWheelDelta = properties.MouseWheelDelta; } #if HAS_UNO_WINUI && IS_UNO_UI_PROJECT public static explicit operator global::Windows.UI.Input.PointerPointProperties(Microsoft.UI.Input.PointerPointProperties muxProps) { var props = new global::Windows.UI.Input.PointerPointProperties(); props._flags = muxProps._flags; // Set by _flags : props.IsPrimary = muxProps.IsPrimary; // Set by _flags : props.IsInRange = muxProps.IsInRange; // Set by _flags : props.IsLeftButtonPressed = muxProps.IsLeftButtonPressed; // Set by _flags : props.IsMiddleButtonPressed = muxProps.IsMiddleButtonPressed; // Set by _flags : props.IsRightButtonPressed = muxProps.IsRightButtonPressed; // Set by _flags : props.IsHorizontalMouseWheel = muxProps.IsHorizontalMouseWheel; // Set by _flags : props.IsXButton1Pressed = muxProps.IsXButton1Pressed; // Set by _flags : props.IsXButton2Pressed = muxProps.IsXButton2Pressed; // Set by _flags : props.IsBarrelButtonPressed = muxProps.IsBarrelButtonPressed; // Set by _flags : props.IsEraser = muxProps.IsEraser; // Set by _flags : props.IsTouchPad = muxProps.IsTouchPad; props.Pressure = muxProps.Pressure; props.Orientation = muxProps.Orientation; props.ContactRect = muxProps.ContactRect; // Set by _flags: props.TouchConfidence = muxProps.TouchConfidence; // Set by _flags: props.IsCanceled = muxProps.IsCanceled; props.PointerUpdateKind = (global::Windows.UI.Input.PointerUpdateKind)muxProps.PointerUpdateKind; props.XTilt = muxProps.XTilt; props.YTilt = muxProps.YTilt; props.MouseWheelDelta = muxProps.MouseWheelDelta; return props; } #endif /// <summary> /// This is actually equivalent to pointer.IsInContact /// </summary> internal bool HasPressedButton => (_flags & Mask.AllButtons) != 0; internal bool HasMultipleButtonsPressed { get { var buttons = _flags & Mask.AllButtons; if (buttons <= 1) // So we catch the common case where we only have the left button pressed { return false; } // Iterate flags until we find a button that is pressed for (var i = 0; i < Mask.ButtonsCount; i++) { var buttonMask = 1 << i; if ((_flags & buttonMask) != 0) { // Button is pressed, check if any other button is pressed return (buttons & ~buttonMask & Mask.AllButtons) != 0; } } return false; } } public bool IsPrimary { get => GetFlag(Mask.Primary); internal set => SetFlag(Mask.Primary, value); } public bool IsInRange { get => GetFlag(Mask.InRange); internal set => SetFlag(Mask.InRange, value); } public bool IsLeftButtonPressed { get => GetFlag(Mask.LeftButton); internal set => SetFlag(Mask.LeftButton, value); } public bool IsMiddleButtonPressed { get => GetFlag(Mask.MiddleButton); internal set => SetFlag(Mask.MiddleButton, value); } public bool IsRightButtonPressed { get => GetFlag(Mask.RightButton); internal set => SetFlag(Mask.RightButton, value); } public bool IsXButton1Pressed { get => GetFlag(Mask.XButton1); internal set => SetFlag(Mask.XButton1, value); } public bool IsXButton2Pressed { get => GetFlag(Mask.XButton2); internal set => SetFlag(Mask.XButton2, value); } public bool IsBarrelButtonPressed { get => GetFlag(Mask.BarrelButton); internal set => SetFlag(Mask.BarrelButton, value); } /// <summary> /// This is necessary for InteractionTracker, which behaves differently on mouse, touch and trackpad inputs. /// </summary> internal bool IsTouchPad { get => GetFlag(Mask.TouchPad); set => SetFlag(Mask.TouchPad, value); } public bool IsHorizontalMouseWheel { get => GetFlag(Mask.HorizontalMouseWheel); internal set => SetFlag(Mask.HorizontalMouseWheel, value); } public bool IsEraser { get => GetFlag(Mask.Eraser); internal set => SetFlag(Mask.Eraser, value); } public float Pressure { get; internal set; } = 0.5f; // According to the doc, the default value is .5 [NotImplemented] // This is not implemented, it can only be set using injected inputs public float Orientation { get; internal set; } [NotImplemented] // This is not implemented, it can only be set using injected inputs public Rect ContactRect { get; internal set; } [NotImplemented] // This is not implemented, it can only be set using injected inputs public bool TouchConfidence { get => GetFlag(Mask.TouchConfidence); internal set => SetFlag(Mask.TouchConfidence, value); } [NotImplemented] // This is not implemented, it can only be set using injected inputs public bool IsCanceled { get => GetFlag(Mask.Cancelled); internal set => SetFlag(Mask.Cancelled, value); } public PointerUpdateKind PointerUpdateKind { get; internal set; } // Supported only on MacOS [NotImplemented("__ANDROID__", "__APPLE_UIKIT__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public float XTilt { get; internal set; } // Supported only on MacOS [NotImplemented("__ANDROID__", "__APPLE_UIKIT__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public float YTilt { get; internal set; } [NotImplemented("__ANDROID__", "__APPLE_UIKIT__")] public int MouseWheelDelta { get; internal set; } /// <inheritdoc /> public override string ToString() { var builder = new StringBuilder(); // Common if (IsPrimary) builder.Append("primary "); if (IsInRange) builder.Append("in_range "); if (IsLeftButtonPressed) builder.Append("left "); if (IsMiddleButtonPressed) builder.Append("middle "); if (IsRightButtonPressed) builder.Append("right "); // Mouse if (IsXButton1Pressed) builder.Append("alt_butt_1 "); if (IsXButton2Pressed) builder.Append("alt_butt_2"); if (MouseWheelDelta != 0) { builder.Append("scroll"); builder.Append(IsHorizontalMouseWheel ? "X (" : "Y ("); builder.Append(MouseWheelDelta); builder.Append("px) "); } // Pen if (IsBarrelButtonPressed) builder.Append("barrel "); if (IsEraser) builder.Append("eraser "); if (IsTouchPad) builder.Append("touchpad "); // Misc builder.Append('('); builder.Append(PointerUpdateKind); builder.Append(')'); return builder.ToString(); } } } #endif
Mask
csharp
microsoft__PowerToys
src/settings-ui/Settings.UI/ViewModels/MouseWithoutBordersViewModel.cs
{ "start": 38004, "end": 43427 }
private enum ____ { Disable = 0, Enable = 1, Ctrl = 2, Shift = 3, } private EasyMouseOption _easyMouseOptionIndex; public int EasyMouseOptionIndex { get { return (int)_easyMouseOptionIndex; } set { if (value != (int)_easyMouseOptionIndex) { _easyMouseOptionIndex = (EasyMouseOption)value; Settings.Properties.EasyMouse.Value = value; NotifyPropertyChanged(nameof(EasyMouseOptionIndex)); } } } public bool EasyMouseEnabled => (EasyMouseOption)EasyMouseOptionIndex != EasyMouseOption.Disable; public bool IsEasyMouseBlockingOnFullscreenEnabled => EasyMouseEnabled && DisableEasyMouseWhenForegroundWindowIsFullscreen; public bool DisableEasyMouseWhenForegroundWindowIsFullscreen { get { return Settings.Properties.DisableEasyMouseWhenForegroundWindowIsFullscreen; } set { if (Settings.Properties.DisableEasyMouseWhenForegroundWindowIsFullscreen == value) { return; } Settings.Properties.DisableEasyMouseWhenForegroundWindowIsFullscreen = value; NotifyPropertyChanged(); } } public HotkeySettings ToggleEasyMouseShortcut { get => Settings.Properties.ToggleEasyMouseShortcut; set { if (Settings.Properties.ToggleEasyMouseShortcut != value) { Settings.Properties.ToggleEasyMouseShortcut = value ?? MouseWithoutBordersProperties.DefaultHotKeyToggleEasyMouse; NotifyPropertyChanged(); NotifyModuleUpdatedSettings(); } } } public HotkeySettings LockMachinesShortcut { get => Settings.Properties.LockMachineShortcut; set { if (Settings.Properties.LockMachineShortcut != value) { Settings.Properties.LockMachineShortcut = value; Settings.Properties.LockMachineShortcut = value ?? MouseWithoutBordersProperties.DefaultHotKeyLockMachine; NotifyPropertyChanged(); NotifyModuleUpdatedSettings(); } } } public HotkeySettings ReconnectShortcut { get => Settings.Properties.ReconnectShortcut; set { if (Settings.Properties.ReconnectShortcut != value) { Settings.Properties.ReconnectShortcut = value; Settings.Properties.ReconnectShortcut = value ?? MouseWithoutBordersProperties.DefaultHotKeyReconnect; NotifyPropertyChanged(); NotifyModuleUpdatedSettings(); } } } public HotkeySettings HotKeySwitch2AllPC { get => Settings.Properties.Switch2AllPCShortcut; set { if (Settings.Properties.Switch2AllPCShortcut != value) { Settings.Properties.Switch2AllPCShortcut = value; Settings.Properties.Switch2AllPCShortcut = value ?? MouseWithoutBordersProperties.DefaultHotKeySwitch2AllPC; NotifyPropertyChanged(); NotifyModuleUpdatedSettings(); } } } private int _selectedSwitchBetweenMachineShortcutOptionsIndex; public int SelectedSwitchBetweenMachineShortcutOptionsIndex { get { return _selectedSwitchBetweenMachineShortcutOptionsIndex; } set { if (_selectedSwitchBetweenMachineShortcutOptionsIndex != value) { _selectedSwitchBetweenMachineShortcutOptionsIndex = value; Settings.Properties.HotKeySwitchMachine.Value = _switchBetweenMachineShortcutOptions[value]; NotifyPropertyChanged(); } } } public bool MoveMouseRelatively { get { return Settings.Properties.MoveMouseRelatively; } set { if (Settings.Properties.MoveMouseRelatively != value) { Settings.Properties.MoveMouseRelatively = value; NotifyPropertyChanged(); } } } public bool BlockMouseAtScreenCorners { get { return Settings.Properties.BlockMouseAtScreenCorners; } set { if (Settings.Properties.BlockMouseAtScreenCorners != value) { Settings.Properties.BlockMouseAtScreenCorners = value; NotifyPropertyChanged(); } } } private IndexedObservableCollection<DeviceViewModel> machineMatrixString;
EasyMouseOption
csharp
protobuf-net__protobuf-net
src/Examples/InheritanceExtensible.cs
{ "start": 11440, "end": 11717 }
public abstract class ____ : Extensible { [ProtoMember(1)] public int Id { get; set; } } [ProtoContract] [ProtoInclude(10, typeof(SomeLeafType))] [CompatibilityLevel(CompatibilityLevel.Level300)]
SomeBaseType
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/IO/WrappingBsonWriter.cs
{ "start": 671, "end": 807 }
class ____ an IBsonWriter that wraps another IBsonWriter. /// </summary> /// <seealso cref="MongoDB.Bson.IO.IBsonWriter" />
for
csharp
grandnode__grandnode2
src/Core/Grand.SharedKernel/Extensions/LanguageSchema.cs
{ "start": 43, "end": 855 }
public static class ____ { public const string SchemaXsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Language'> <xs:complexType> <xs:sequence> <xs:element name='Resource' maxOccurs='unbounded'> <xs:complexType> <xs:sequence> <xs:element name='Value' type='xs:string' /> </xs:sequence> <xs:attribute name='Name' type='xs:string' use='required' /> <xs:attribute name='Area' type='xs:string' use='optional' /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name='Name' type='xs:string' use='required' /> </xs:complexType> </xs:element> </xs:schema>"; }
LanguageSchema
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Execution.Abstractions/Execution/IRequestExecutor.cs
{ "start": 234, "end": 2356 }
public interface ____ : IFeatureProvider { /// <summary> /// Gets an <see cref="ulong"/> representing the version of the executor. /// When a schema is updated and a new executor is created, the version is incremented. /// </summary> ulong Version { get; } /// <summary> /// Gets the schema definition that this executor operates on. /// </summary> ISchemaDefinition Schema { get; } /// <summary> /// Executes the given GraphQL <paramref name="request" />. /// </summary> /// <param name="request"> /// The GraphQL request object. /// </param> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// Returns the execution result of the given GraphQL <paramref name="request" />. /// /// If the request operation is a simple query or mutation the result is a /// <see cref="IOperationResult" />. /// /// If the request operation is a query or mutation where data is deferred, streamed or /// includes live data the result is a <see cref="IResponseStream" /> where each result /// that the <see cref="IResponseStream" /> yields is a <see cref="IOperationResult" />. /// /// If the request operation is a subscription the result is a /// <see cref="IResponseStream" /> where each result that the /// <see cref="IResponseStream" /> yields is a /// <see cref="IOperationResult" />. /// </returns> Task<IExecutionResult> ExecuteAsync( IOperationRequest request, CancellationToken cancellationToken = default); /// <summary> /// Executes the given GraphQL <paramref name="requestBatch" />. /// </summary> /// <param name="requestBatch"> /// The GraphQL request batch. /// </param> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// Returns a stream of query results. /// </returns> Task<IResponseStream> ExecuteBatchAsync( OperationRequestBatch requestBatch, CancellationToken cancellationToken = default); }
IRequestExecutor