repo
stringclasses
17 values
instance_id
stringlengths
10
43
base_commit
stringlengths
40
40
patch
stringlengths
530
154k
test_patch
stringlengths
377
76.4k
problem_statement
stringlengths
97
33k
hints_text
stringlengths
3
18.4k
created_at
stringdate
2020-06-16 21:09:47
2025-04-20 13:41:07
version
stringclasses
4 values
FAIL_TO_PASS
stringlengths
2
3.71k
PASS_TO_PASS
stringlengths
2
5.8k
AvaloniaUI/Avalonia
avaloniaui__avalonia-16575
4c2d9fcda7bb703600e4146cefb790c5cbbb3bb6
diff --git a/src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs b/src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs index 0edc7984949..f0dde6925d5 100644 --- a/src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs +++ b/src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs @@ -479,7 +479,7 @@ protected virtual void OnFormatStringChanged(string? oldValue, string? newValue) { if (IsInitialized) { - SyncTextAndValueProperties(false, null); + SyncTextAndValueProperties(false, null, true); } }
diff --git a/tests/Avalonia.Controls.UnitTests/NumericUpDownTests.cs b/tests/Avalonia.Controls.UnitTests/NumericUpDownTests.cs index 24f246d188d..10139be0d45 100644 --- a/tests/Avalonia.Controls.UnitTests/NumericUpDownTests.cs +++ b/tests/Avalonia.Controls.UnitTests/NumericUpDownTests.cs @@ -62,6 +62,24 @@ public void Increment_Decrement_Tests(decimal min, decimal max, decimal? value, Assert.Equal(control.Value, expected); } + [Fact] + public void FormatString_Is_Applied_Immediately() + { + RunTest((control, textbox) => + { + const decimal value = 10.11m; + + // Establish and verify initial conditions. + control.FormatString = "F0"; + control.Value = value; + Assert.Equal(value.ToString("F0"), control.Text); + + // Check that FormatString is applied. + control.FormatString = "F2"; + Assert.Equal(value.ToString("F2"), control.Text); + }); + } + public static IEnumerable<object[]> Increment_Decrement_TestData() { // if min and max are not defined and value was null, 0 should be ne new value after spin
NumericUpDown - Changes to FormatString are not reflected immediately ### Describe the bug When FormatString binding value is changed, the new format is applied only after focusing or interacting with the control. ### To Reproduce 1. Create NumericUpDown with binding to FormatString. 2. Change bound value 3. The content of NumericUpDown stays the same. ### Expected behavior Content of NumericUpDown changes accoring to the new format string immediately. ### Avalonia version 11.1.1 ### OS Windows 10 ### Additional context I believe that the problem is in `SyncTextAndValueProperties` call in `OnFormatStringChanged`. The call should set `forceTextUpdate=true`, ie. ``` protected virtual void OnFormatStringChanged(string? oldValue, string? newValue) { if (IsInitialized) { SyncTextAndValueProperties(false, null, true); } } ```
null
2024-08-02T08:41:45Z
0.1
['Avalonia.Controls.UnitTests.NumericUpDownTests.FormatString_Is_Applied_Immediately']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16564
b1489aaca28d3f35cb69c33f1202a62a08c3f70a
diff --git a/src/Avalonia.Controls/ToolTipService.cs b/src/Avalonia.Controls/ToolTipService.cs index d01114be6fb..d99d185bedc 100644 --- a/src/Avalonia.Controls/ToolTipService.cs +++ b/src/Avalonia.Controls/ToolTipService.cs @@ -78,7 +78,7 @@ public void Update(IInputRoot root, Visual? candidateToolTipHost) { var currentToolTip = _tipControl?.GetValue(ToolTip.ToolTipProperty); - if (root == currentToolTip?.VisualRoot) + if (root == currentToolTip?.PopupHost?.HostedVisualTreeRoot) { // Don't update while the pointer is over a tooltip return;
diff --git a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs index 6199a208720..12ecbb0c68f 100644 --- a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; +using System.Reactive; using System.Runtime.CompilerServices; +using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.Raw; +using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.UnitTests; @@ -15,18 +18,65 @@ namespace Avalonia.Controls.UnitTests public class ToolTipTests_Popup : ToolTipTests { protected override TestServices ConfigureServices(TestServices baseServices) => baseServices; + + protected override void SetupWindowMock(Mock<IWindowImpl> windowImpl) { } + + protected override void VerifyToolTipType(Control control) + { + var toolTip = control.GetValue(ToolTip.ToolTipProperty); + Assert.IsType<PopupRoot>(toolTip.PopupHost); + Assert.Same(toolTip.VisualRoot, toolTip.PopupHost); + } } - public class ToolTipTests_Overlay : ToolTipTests + public class ToolTipTests_Overlay : ToolTipTests, IDisposable { + private readonly IDisposable _toolTipOpenSubscription; + + public ToolTipTests_Overlay() + { + _toolTipOpenSubscription = ToolTip.IsOpenProperty.Changed.Subscribe(new AnonymousObserver<AvaloniaPropertyChangedEventArgs<bool>>(e => + { + if (e.Sender is Visual { VisualRoot: {} root } visual) + OverlayLayer.GetOverlayLayer(visual).Measure(root.ClientSize); + })); + } + + public void Dispose() + { + _toolTipOpenSubscription.Dispose(); + } + protected override TestServices ConfigureServices(TestServices baseServices) => baseServices.With(windowingPlatform: new MockWindowingPlatform(popupImpl: window => null)); + + protected override void SetupWindowMock(Mock<IWindowImpl> windowImpl) + { + windowImpl.Setup(x => x.CreatePopup()).Returns(default(IPopupImpl)); + } + + protected override void VerifyToolTipType(Control control) + { + var toolTip = control.GetValue(ToolTip.ToolTipProperty); + Assert.IsType<OverlayPopupHost>(toolTip.PopupHost); + Assert.Same(toolTip.VisualRoot, control.VisualRoot); + } } public abstract class ToolTipTests { protected abstract TestServices ConfigureServices(TestServices baseServices); + protected abstract void SetupWindowMock(Mock<IWindowImpl> windowImpl); + + protected abstract void VerifyToolTipType(Control control); + + private void AssertToolTipOpen(Control control) + { + Assert.True(ToolTip.GetIsOpen(control)); + VerifyToolTipType(control); + } + private static readonly MouseDevice s_mouseDevice = new(new Pointer(0, PointerType.Mouse, true)); [Fact] @@ -46,7 +96,7 @@ public void Should_Close_When_Control_Detaches() SetupWindowAndActivateToolTip(panel, target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); panel.Children.Remove(target); @@ -74,7 +124,7 @@ public void Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree() mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); panel.Children.Remove(target); @@ -95,7 +145,7 @@ public void Should_Open_On_Pointer_Enter() SetupWindowAndActivateToolTip(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); } } @@ -112,7 +162,7 @@ public void Content_Should_Update_When_Tip_Property_Changes_And_Already_Open() SetupWindowAndActivateToolTip(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); Assert.Equal("Tip", target.GetValue(ToolTip.ToolTipProperty).Content); ToolTip.SetTip(target, "Tip1"); @@ -139,7 +189,7 @@ public void Should_Open_On_Pointer_Enter_With_Delay() timer.ForceFire(); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); } } @@ -188,6 +238,7 @@ public void Setting_IsOpen_Should_Add_Open_Class() ToolTip.SetIsOpen(decorator, true); Assert.Equal(new[] { ":open" }, toolTip.Classes); + VerifyToolTipType(decorator); } } @@ -197,8 +248,11 @@ public void Clearing_IsOpen_Should_Remove_Open_Class() using (UnitTestApplication.Start(ConfigureServices(TestServices.StyledWindow))) { var toolTip = new ToolTip(); - var window = new Window(); + var windowImpl = MockWindowingPlatform.CreateWindowMock(); + SetupWindowMock(windowImpl); + var window = new Window(windowImpl.Object); + var decorator = new Decorator() { [ToolTip.TipProperty] = toolTip @@ -211,6 +265,7 @@ public void Clearing_IsOpen_Should_Remove_Open_Class() window.Presenter.ApplyTemplate(); ToolTip.SetIsOpen(decorator, true); + AssertToolTipOpen(decorator); ToolTip.SetIsOpen(decorator, false); Assert.Empty(toolTip.Classes); @@ -230,7 +285,7 @@ public void Should_Close_On_Null_Tip() SetupWindowAndActivateToolTip(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); target[ToolTip.TipProperty] = null; @@ -253,13 +308,13 @@ public void Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip() mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); mouseEnter(tooltip); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); } } @@ -277,16 +332,16 @@ public void Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Cont var mouseEnter = SetupWindowAndGetMouseEnterAction(target); mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); mouseEnter(tooltip); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); } } @@ -311,12 +366,12 @@ public void Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control() var mouseEnter = SetupWindowAndGetMouseEnterAction(panel); mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); mouseEnter(tooltip); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); mouseEnter(other); @@ -352,7 +407,7 @@ public void New_ToolTip_Replaces_Other_ToolTip_Immediately() Assert.False(ToolTip.GetIsOpen(other)); // long delay mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); // no delay + AssertToolTipOpen(target); // no delay mouseEnter(other); Assert.True(ToolTip.GetIsOpen(other)); // delay skipped, a tooltip was already open @@ -360,7 +415,7 @@ public void New_ToolTip_Replaces_Other_ToolTip_Immediately() // Now disable the between-show system mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); ToolTip.SetBetweenShowDelay(other, -1); @@ -389,7 +444,7 @@ public void ToolTip_Events_Order_Is_Defined() SetupWindowAndActivateToolTip(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); target[ToolTip.TipProperty] = null; @@ -442,7 +497,7 @@ public void ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event() SetupWindowAndActivateToolTip(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); target[ToolTip.TipProperty] = null; @@ -463,7 +518,7 @@ public void Should_Close_When_Pointer_Leaves_Window() var mouseEnter = SetupWindowAndGetMouseEnterAction(target); mouseEnter(target); - Assert.True(ToolTip.GetIsOpen(target)); + AssertToolTipOpen(target); var topLevel = TopLevel.GetTopLevel(target); topLevel.PlatformImpl.Input(new RawPointerEventArgs(s_mouseDevice, (ulong)DateTime.Now.Ticks, topLevel, @@ -476,6 +531,8 @@ public void Should_Close_When_Pointer_Leaves_Window() private Action<Control> SetupWindowAndGetMouseEnterAction(Control windowContent, [CallerMemberName] string testName = null) { var windowImpl = MockWindowingPlatform.CreateWindowMock(); + SetupWindowMock(windowImpl); + var hitTesterMock = new Mock<IHitTester>(); var window = new Window(windowImpl.Object)
The ToolTip Popup not close when pointer exit the control,Is that a feature or bug? I have a new problem when set 'OverlayPopups =true',the ToolTip Popup not close when pointer exit the control,Is that a feature or bug? ![tooltip](https://github.com/user-attachments/assets/5035f341-8a81-4c46-99b6-ddcb89e03f21) @maxkatz6 _Originally posted by @ZSYMAX in https://github.com/AvaloniaUI/Avalonia/discussions/15212#discussioncomment-10175448_
null
2024-08-01T12:24:10Z
0.1
['Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Close_When_Control_Detaches', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Open_On_Pointer_Enter', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Content_Should_Update_When_Tip_Property_Changes_And_Already_Open', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Open_On_Pointer_Enter_With_Delay', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Clearing_IsOpen_Should_Remove_Open_Class', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Close_On_Null_Tip', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Control', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.New_ToolTip_Replaces_Other_ToolTip_Immediately', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.ToolTip_Events_Order_Is_Defined', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.Should_Close_When_Pointer_Leaves_Window', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Close_When_Control_Detaches', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Open_On_Pointer_Enter', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Content_Should_Update_When_Tip_Property_Changes_And_Already_Open', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Open_On_Pointer_Enter_With_Delay', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Setting_IsOpen_Should_Add_Open_Class', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Clearing_IsOpen_Should_Remove_Open_Class', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Close_On_Null_Tip', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Control', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.New_ToolTip_Replaces_Other_ToolTip_Immediately', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.ToolTip_Events_Order_Is_Defined', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.Should_Close_When_Pointer_Leaves_Window']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16557
98e60e89c7d49c7b2d2028953e95d3ac56503930
diff --git a/src/Avalonia.Base/Input/Navigation/XYFocus.Impl.cs b/src/Avalonia.Base/Input/Navigation/XYFocus.Impl.cs index 867e80f1762..b2a79aa3b96 100644 --- a/src/Avalonia.Base/Input/Navigation/XYFocus.Impl.cs +++ b/src/Avalonia.Base/Input/Navigation/XYFocus.Impl.cs @@ -92,6 +92,11 @@ internal void UpdateManifolds( return null; } + if(!(XYFocusHelpers.FindXYSearchRoot(inputElement, keyDeviceType) is InputElement searchRoot)) + { + return null; + } + _instance.SetManifoldsFromBounds(bounds); return _instance.GetNextFocusableElement(direction, inputElement, engagedControl, true, new XYFocusOptions @@ -99,7 +104,7 @@ internal void UpdateManifolds( KeyDeviceType = keyDeviceType, FocusedElementBounds = bounds, UpdateManifold = true, - SearchRoot = owner as InputElement ?? inputElement.GetVisualRoot() as InputElement + SearchRoot = searchRoot }); } diff --git a/src/Avalonia.Base/Input/Navigation/XYFocusHelpers.cs b/src/Avalonia.Base/Input/Navigation/XYFocusHelpers.cs index 1914f6f6c63..7bdcfc8fb9e 100644 --- a/src/Avalonia.Base/Input/Navigation/XYFocusHelpers.cs +++ b/src/Avalonia.Base/Input/Navigation/XYFocusHelpers.cs @@ -1,4 +1,5 @@ using System; +using Avalonia.VisualTree; namespace Avalonia.Input; @@ -13,11 +14,25 @@ private static bool IsAllowedXYNavigationMode(XYFocusNavigationModes modes, KeyD { return keyDeviceType switch { - null => true, // programmatic input, allow any subtree. + null => !modes.Equals(XYFocusNavigationModes.Disabled), // programmatic input, allow any subtree except Disabled. KeyDeviceType.Keyboard => modes.HasFlag(XYFocusNavigationModes.Keyboard), KeyDeviceType.Gamepad => modes.HasFlag(XYFocusNavigationModes.Gamepad), KeyDeviceType.Remote => modes.HasFlag(XYFocusNavigationModes.Remote), _ => throw new ArgumentOutOfRangeException(nameof(keyDeviceType), keyDeviceType, null) }; } + + internal static InputElement? FindXYSearchRoot(this InputElement visual, KeyDeviceType? keyDeviceType) + { + InputElement candidate = visual; + InputElement? candidateParent = visual.FindAncestorOfType<InputElement>(); + + while (candidateParent is not null && candidateParent.IsAllowedXYNavigationMode(keyDeviceType)) + { + candidate = candidateParent; + candidateParent = candidate.FindAncestorOfType<InputElement>(); + } + + return candidate; + } }
diff --git a/tests/Avalonia.Base.UnitTests/Input/KeyboardNavigationTests_XY.cs b/tests/Avalonia.Base.UnitTests/Input/KeyboardNavigationTests_XY.cs index 2ea3a51908f..fa5286a8d80 100644 --- a/tests/Avalonia.Base.UnitTests/Input/KeyboardNavigationTests_XY.cs +++ b/tests/Avalonia.Base.UnitTests/Input/KeyboardNavigationTests_XY.cs @@ -418,4 +418,45 @@ public void Can_Focus_Any_Element_If_Nothing_Was_Focused() Assert.Equal(candidate, FocusManager.GetFocusManager(window)!.GetFocusedElement()); } + + [Fact] + public void Cannot_Focus_Across_XYFocus_Boundaries() + { + using var _ = UnitTestApplication.Start(TestServices.FocusableWindow); + + var current = new Button() { Height = 20 }; + var candidate = new Button() { Height = 20 }; + var currentParent = new StackPanel + { + [XYFocus.NavigationModesProperty] = XYFocusNavigationModes.Enabled, + Orientation = Orientation.Vertical, + Spacing = 20, + Children = { current } + }; + var candidateParent = new StackPanel + { + [XYFocus.NavigationModesProperty] = XYFocusNavigationModes.Enabled, + Orientation = Orientation.Vertical, + Spacing = 20, + Children = { candidate } + }; + + var grandparent = new StackPanel + { + [XYFocus.NavigationModesProperty] = XYFocusNavigationModes.Disabled, + Orientation = Orientation.Vertical, + Spacing = 20, + Children = { currentParent, candidateParent } + }; + + var window = new Window + { + [XYFocus.NavigationModesProperty] = XYFocusNavigationModes.Enabled, + Content = grandparent, + Height = 300 + }; + window.Show(); + + Assert.Null(KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down)); + } }
XYFocus cannot easily be restricted to branches of the visual tree. ### Describe the bug At present when using XYFocus, the search for valid candidate controls to focus next always starts at the TopLevel. While the search does restrict its results to controls that allow XYFocus, there's no simple way for a developer to restrict results to specific branches of the Visual tree. That means that at present "modal" dialogs like DialogHost.Avalonia can't trap XYFocus within a displayed dialog, as any XYFocus enabled control that is a descendant of the same TopLevel is returned as a valid focus candidate. Tab based navigation can be trapped with KeyboardNavigation.TabNavigation="Contained", and pointer based focus is also intercepted by the DialogHost overlay to prevent pointer events reaching "disabled" controls. ### To Reproduce 1. Clone https://github.com/IanRawley/XYFocusSearchIssue.git and compile. 2. Open the dialog with the button. Focus will be placed on the first button within the dialog. 3. Use XYFocus to navigate. Any attempts to navigate down from inside the dialog will focus the TextBox outside the dialog which should not be possible. ### Expected behavior Some API for a developer to limit the XYFocus search for candidates to a specific subtree of the Visual Tree. ### Avalonia version 11.1.0 ### OS _No response_ ### Additional context I've been thinking of how this would be implemented, and had a few ideas. 1. When searching for candidates, choose the highest level ancestor of the initiating control which has XYFocus enabled, but whose parent does not. While this would work generally, I think there are valid cases for having XYFocus able to move between neighbouring branches on the Visual tree but not to their parent or other sibling branches which this would prevent. 2. Focus engagement. From what I understand Focus Engagement as a mechanic is intended for individual controls rather than branches, and would probably cause issues with nested controls that require engagement to function properly. 3. An attached property to set a search boundary. XYFocus.TryDirectionalFocus() would then search upwards from the element that initiated navigation, and use the first control with the property set as the search root, or the current behaviour of the KeyboardNavigationHandler owner or TopLevel as fallbacks. A similar sort of idea to Grid.IsSharedSizeScope. This is something I think I could implement as a PR. 4. FocusScopes? But that seems like it's got a lot of other issues attached to it, and being an effectively internal API doesn't allow app developers much control at the moment. 5. The developer turns XYFocus on and off on branches as views change, having XYFocus enabled only on branches that should be navigable to at any given time. This gets messy quickly if you start having multiple DialogHost controls and XYFocus enabled in various branches that cannot be aware of each other. My current preference is option 3 above, the attached property, which as I said I can probably make a PR for if it's deemed an appropriate option.
One more idea for me actually, implement ICustomKeyboardNavigation somewhere appropriate and use that to trap XYFocus within a tree. EDIT: Won't work. None of the XYFocus methods that would be needed are public. They're all internal / private. https://learn.microsoft.com/en-us/windows/apps/design/input/focus-navigation#enabled Looks like UWP behavior is supposed to prevent XY navigation between 2 sibling XYFocusKeyboardNavigation="Enabled" subtrees if their parent is explicitly disabled. See the second image in the linked section. I'm not sure I think that's the right way to do it. Personally I feel having more explicit control over boundaries without having to disable XYFocus is the better way. If desired though I could probably do a PR to implement UWP behaviour here as well. Digging into WinUI 3 code it behaves the same way, bubbling an XY navigation event up from the source until it finds a candidate to focus or hits a parent that isn't XY navigation enabled. See https://github.com/microsoft/microsoft-ui-xaml/blob/66a7b0ae71c19f89c6a7d86a1986794ad1a1bf09/src/dxaml/xcp/core/dll/eventmgr.cpp#L1385C9-L1401C6 and here https://github.com/microsoft/microsoft-ui-xaml/blob/66a7b0ae71c19f89c6a7d86a1986794ad1a1bf09/src/dxaml/xcp/components/focus/inc/FocusSelection.h#L77-L80
2024-07-31T23:43:32Z
0.1
['Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Cannot_Focus_Across_XYFocus_Boundaries']
['Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.RectilinearDistance_Focus_Depending_On_Direction', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.NavigationDirectionDistance_Focus_Depending_On_Direction', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Clipped_Element_Should_Not_Be_Focused', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Parent_Can_Override_Navigation_When_Directional_Is_Set', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Uses_XY_Directional_Overrides', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Arrow_Key_Should_Not_Be_Handled_If_No_Focus', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Arrow_Key_Should_Focus_Element', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Projection_Focus_Depending_On_Direction', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Can_Focus_Any_Element_If_Nothing_Was_Focused', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Can_Focus_Child_Of_Current_Focused', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.XY_Directional_Override_Discarded_If_Not_Part_Of_The_Same_Root', 'Avalonia.Base.UnitTests.Input.KeyboardNavigationTests_XY.Clipped_Element_Should_Not_Focused_If_Inside_Of_ScrollViewer']
AvaloniaUI/Avalonia
avaloniaui__avalonia-16214
6ea50d95fb725c726fa8dfa38282457144be1bb0
diff --git a/src/Avalonia.Base/Data/BindingOperations.cs b/src/Avalonia.Base/Data/BindingOperations.cs index 9170fbfaa06..b0a97e5c000 100644 --- a/src/Avalonia.Base/Data/BindingOperations.cs +++ b/src/Avalonia.Base/Data/BindingOperations.cs @@ -101,6 +101,25 @@ public static IDisposable Apply( return Apply(target, property, binding); } + /// <summary> + /// Retrieves the <see cref="BindingExpressionBase"/> that is currently active on the + /// specified property. + /// </summary> + /// <param name="target"> + /// The <see cref="AvaloniaObject"/> from which to retrieve the binding expression. + /// </param> + /// <param name="property"> + /// The binding target property from which to retrieve the binding expression. + /// </param> + /// <returns> + /// The <see cref="BindingExpressionBase"/> object that is active on the given property or + /// null if no binding expression is active on the given property. + /// </returns> + public static BindingExpressionBase? GetBindingExpressionBase(AvaloniaObject target, AvaloniaProperty property) + { + return target.GetValueStore().GetExpression(property); + } + private sealed class TwoWayBindingDisposable : IDisposable { private readonly IDisposable _toTargetSubscription; diff --git a/src/Avalonia.Base/PropertyStore/ValueStore.cs b/src/Avalonia.Base/PropertyStore/ValueStore.cs index 67d176eceac..789383b860a 100644 --- a/src/Avalonia.Base/PropertyStore/ValueStore.cs +++ b/src/Avalonia.Base/PropertyStore/ValueStore.cs @@ -292,6 +292,42 @@ public T GetValue<T>(StyledProperty<T> property) return property.GetDefaultValue(Owner); } + public BindingExpressionBase? GetExpression(AvaloniaProperty property) + { + var evaluatedLocalValue = false; + + bool TryGetLocalValue(out BindingExpressionBase? result) + { + if (!evaluatedLocalValue) + { + evaluatedLocalValue = true; + + if (_localValueBindings?.TryGetValue(property.Id, out var o) == true) + { + result = o as BindingExpressionBase; + return true; + } + } + + result = null; + return false; + } + + for (var i = _frames.Count - 1; i >= 0; --i) + { + var frame = _frames[i]; + + if (frame.Priority > BindingPriority.LocalValue && TryGetLocalValue(out var localExpression)) + return localExpression; + + if (frame.TryGetEntryIfActive(property, out var entry, out _)) + return entry as BindingExpressionBase; + } + + TryGetLocalValue(out var e); + return e; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static EffectiveValue<T> CastEffectiveValue<T>(EffectiveValue value) {
diff --git a/tests/Avalonia.Base.UnitTests/Data/BindingOperationsTests.cs b/tests/Avalonia.Base.UnitTests/Data/BindingOperationsTests.cs new file mode 100644 index 00000000000..ac39e2b56d3 --- /dev/null +++ b/tests/Avalonia.Base.UnitTests/Data/BindingOperationsTests.cs @@ -0,0 +1,147 @@ +using Avalonia.Controls; +using Avalonia.Data; +using Avalonia.Data.Converters; +using Avalonia.Styling; +using Avalonia.UnitTests; +using Xunit; + +namespace Avalonia.Base.UnitTests.Data; + +public class BindingOperationsTests +{ + [Fact] + public void GetBindingExpressionBase_Returns_Null_When_Not_Bound() + { + var target = new Control(); + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.Null(expression); + } + + [Theory] + [InlineData(BindingPriority.Animation)] + [InlineData(BindingPriority.LocalValue)] + [InlineData(BindingPriority.Style)] + [InlineData(BindingPriority.StyleTrigger)] + public void GetBindingExpressionBase_Returns_Expression_When_Bound(BindingPriority priority) + { + var data = new { Tag = "foo" }; + var target = new Control { DataContext = data }; + var binding = new Binding("Tag") { Priority = priority }; + target.Bind(Control.TagProperty, binding); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Expression_When_Bound_Locally_With_Binding_Error() + { + // Target has no data context so binding will fail. + var target = new Control(); + var binding = new Binding("Tag"); + target.Bind(Control.TagProperty, binding); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Expression_When_Bound_To_MultiBinding() + { + var data = new { Tag = "foo" }; + var target = new Control { DataContext = data }; + var binding = new MultiBinding + { + Converter = new FuncMultiValueConverter<object, string>(x => string.Join(',', x)), + Bindings = + { + new Binding("Tag"), + new Binding("Tag"), + } + }; + + target.Bind(Control.TagProperty, binding); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme() + { + var target = new Control(); + var binding = new Binding("Tag"); + var theme = new ControlTheme(typeof(Control)) + { + Setters = { new Setter(Control.TagProperty, binding) }, + }; + + target.Theme = theme; + var root = new TestRoot(target); + root.UpdateLayout(); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme_TemplateBinding() + { + var target = new Control(); + var binding = new TemplateBinding(Control.TagProperty); + var theme = new ControlTheme(typeof(Control)) + { + Setters = { new Setter(Control.TagProperty, binding) }, + }; + + target.Theme = theme; + var root = new TestRoot(target); + root.UpdateLayout(); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme_Style() + { + var target = new Control { Classes = { "foo" } }; + var binding = new Binding("Tag"); + var theme = new ControlTheme(typeof(Control)) + { + Children = + { + new Style(x => x.Nesting().Class("foo")) + { + Setters = { new Setter(Control.TagProperty, binding) }, + }, + } + }; + + target.Theme = theme; + var root = new TestRoot(target); + root.UpdateLayout(); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } + + [Fact] + public void GetBindingExpressionBase_Returns_Binding_When_Bound_Via_Style() + { + var target = new Control(); + var binding = new Binding("Tag"); + var style = new Style(x => x.OfType<Control>()) + { + Setters = { new Setter(Control.TagProperty, binding) }, + }; + + var root = new TestRoot(); + root.Styles.Add(style); + root.Child = target; + root.UpdateLayout(); + + var expression = BindingOperations.GetBindingExpressionBase(target, Control.TagProperty); + Assert.NotNull(expression); + } +}
Allow accessing BindingExpressions to make proper use of `UpdateSourceTrigger=Explicit` ### Is your feature request related to a problem? Please describe. I'm trying to use the new `UpdateSourceTrigger=Explicit` parameter for some bindings. At the moment, I can't seem to find a way to access BindingExpressions for existing bindings defined in XAML, but I need that to call `BindingExpressionBase.UpdateSource`. ### Describe the solution you'd like WPF has a public API to retrieve binding expressions: ``` control.GetBindingExpression(Control.TargetProperty) ``` Maybe something similar could be implemented. ### Describe alternatives you've considered -- ### Additional context #13734 also requested this functionality, and although it was closed, there doesn't seem to be any public API for that particular use case yet.
@ThePBone which version did you test? 11.1 beta may have that API now I tested 11.1 beta-1. `UpdateSourceTrigger.Explicit` and `BindingExpressionBase.UpdateSource` are available as mentioned in PR #13970. However, I don't think there is currently a way to obtain a reference to a BindingExpressionBase for an existing binding using the public API, so the `UpdateSource` method can't actually be accessed, as far as I can see. @ThePBone I think you are right. Most likely an oversight /cc @grokys Any idea when this will be added? I find myself in need of being able to access the binding(s) of a control
2024-07-03T09:54:01Z
0.1
['Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme_TemplateBinding', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Null_When_Not_Bound', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme_Style', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Expression_When_Bound_To_MultiBinding', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Expression_When_Bound_Locally_With_Binding_Error', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Binding_When_Bound_Via_ControlTheme', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Expression_When_Bound', 'Avalonia.Base.UnitTests.Data.BindingOperationsTests.GetBindingExpressionBase_Returns_Binding_When_Bound_Via_Style']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16168
3b235f9aa82dbcae024c0e75486e7d91df1be13d
diff --git a/src/Avalonia.Controls/Utils/RealizedStackElements.cs b/src/Avalonia.Controls/Utils/RealizedStackElements.cs index b8f088f0909..fab10b0ad96 100644 --- a/src/Avalonia.Controls/Utils/RealizedStackElements.cs +++ b/src/Avalonia.Controls/Utils/RealizedStackElements.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Avalonia.Layout; using Avalonia.Utilities; namespace Avalonia.Controls.Utils @@ -42,16 +43,17 @@ internal class RealizedStackElements public IReadOnlyList<double> SizeU => _sizes ??= new List<double>(); /// <summary> - /// Gets the position of the first element on the primary axis. + /// Gets the position of the first element on the primary axis, or NaN if the position is + /// unstable. /// </summary> - public double StartU => _startU; + public double StartU => _startUUnstable ? double.NaN : _startU; /// <summary> /// Adds a newly realized element to the collection. /// </summary> /// <param name="index">The index of the element.</param> /// <param name="element">The element.</param> - /// <param name="u">The position of the elemnt on the primary axis.</param> + /// <param name="u">The position of the element on the primary axis.</param> /// <param name="sizeU">The size of the element on the primary axis.</param> public void Add(int index, Control element, double u, double sizeU) { @@ -99,76 +101,6 @@ public void Add(int index, Control element, double u, double sizeU) return null; } - /// <summary> - /// Gets or estimates the index and start U position of the anchor element for the - /// specified viewport. - /// </summary> - /// <param name="viewportStartU">The U position of the start of the viewport.</param> - /// <param name="viewportEndU">The U position of the end of the viewport.</param> - /// <param name="itemCount">The number of items in the list.</param> - /// <param name="estimatedElementSizeU">The current estimated element size.</param> - /// <returns> - /// A tuple containing: - /// - The index of the anchor element, or -1 if an anchor could not be determined - /// - The U position of the start of the anchor element, if determined - /// </returns> - /// <remarks> - /// This method tries to find an existing element in the specified viewport from which - /// element realization can start. Failing that it estimates the first element in the - /// viewport. - /// </remarks> - public (int index, double position) GetOrEstimateAnchorElementForViewport( - double viewportStartU, - double viewportEndU, - int itemCount, - ref double estimatedElementSizeU) - { - // We have no elements, nothing to do here. - if (itemCount <= 0) - return (-1, 0); - - // If we're at 0 then display the first item. - if (MathUtilities.IsZero(viewportStartU)) - return (0, 0); - - if (_sizes is not null && !_startUUnstable) - { - var u = _startU; - - for (var i = 0; i < _sizes.Count; ++i) - { - var size = _sizes[i]; - - if (double.IsNaN(size)) - break; - - var endU = u + size; - - if (endU > viewportStartU && u < viewportEndU) - return (FirstIndex + i, u); - - u = endU; - } - } - - // We don't have any realized elements in the requested viewport, or can't rely on - // StartU being valid. Estimate the index using only the estimated size. First, - // estimate the element size, using defaultElementSizeU if we don't have any realized - // elements. - var estimatedSize = EstimateElementSizeU() switch - { - -1 => estimatedElementSizeU, - double v => v, - }; - - // Store the estimated size for the next layout pass. - estimatedElementSizeU = estimatedSize; - - // Estimate the element at the start of the viewport. - var index = Math.Min((int)(viewportStartU / estimatedSize), itemCount - 1); - return (index, index * estimatedSize); - } - /// <summary> /// Gets the position of the element with the requested index on the primary axis, if realized. /// </summary> @@ -193,61 +125,6 @@ public double GetElementU(int index) return u; } - public double GetOrEstimateElementU(int index, ref double estimatedElementSizeU) - { - // Return the position of the existing element if realized. - var u = GetElementU(index); - - if (!double.IsNaN(u)) - return u; - - // Estimate the element size, using defaultElementSizeU if we don't have any realized - // elements. - var estimatedSize = EstimateElementSizeU() switch - { - -1 => estimatedElementSizeU, - double v => v, - }; - - // Store the estimated size for the next layout pass. - estimatedElementSizeU = estimatedSize; - - // TODO: Use _startU to work this out. - return index * estimatedSize; - } - - /// <summary> - /// Estimates the average U size of all elements in the source collection based on the - /// realized elements. - /// </summary> - /// <returns> - /// The estimated U size of an element, or -1 if not enough information is present to make - /// an estimate. - /// </returns> - public double EstimateElementSizeU() - { - var total = 0.0; - var divisor = 0.0; - - // Average the size of the realized elements. - if (_sizes is not null) - { - foreach (var size in _sizes) - { - if (double.IsNaN(size)) - continue; - total += size; - ++divisor; - } - } - - // We don't have any elements on which to base our estimate. - if (divisor == 0 || total == 0) - return -1; - - return total / divisor; - } - /// <summary> /// Gets the index of the specified element. /// </summary> @@ -538,6 +415,34 @@ public void ResetForReuse() _elements?.Clear(); _sizes?.Clear(); } - } + /// <summary> + /// Validates that <see cref="StartU"/> is still valid. + /// </summary> + /// <param name="orientation">The panel orientation.</param> + /// <remarks> + /// If the U size of any element in the realized elements has changed, then the value of + /// <see cref="StartU"/> should be considered unstable. + /// </remarks> + public void ValidateStartU(Orientation orientation) + { + if (_elements is null || _sizes is null || _startUUnstable) + return; + + for (var i = 0; i < _elements.Count; ++i) + { + if (_elements[i] is not { } element) + continue; + + var sizeU = orientation == Orientation.Horizontal ? + element.DesiredSize.Width : element.DesiredSize.Height; + + if (sizeU != _sizes[i]) + { + _startUUnstable = true; + break; + } + } + } + } } diff --git a/src/Avalonia.Controls/VirtualizingPanel.cs b/src/Avalonia.Controls/VirtualizingPanel.cs index 779aa811b41..1cd676ed4f4 100644 --- a/src/Avalonia.Controls/VirtualizingPanel.cs +++ b/src/Avalonia.Controls/VirtualizingPanel.cs @@ -192,6 +192,12 @@ protected void RemoveInternalChildRange(int index, int count) Children.RemoveRange(index, count); } + private protected override void InvalidateMeasureOnChildrenChanged() + { + // Don't invalidate measure when children are added or removed: the panel is responsible + // for managing its children. + } + internal void Attach(ItemsControl itemsControl) { if (ItemsControl is not null) diff --git a/src/Avalonia.Controls/VirtualizingStackPanel.cs b/src/Avalonia.Controls/VirtualizingStackPanel.cs index 4c1a1ccb9ab..e235d314748 100644 --- a/src/Avalonia.Controls/VirtualizingStackPanel.cs +++ b/src/Avalonia.Controls/VirtualizingStackPanel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; +using System.Drawing; using System.Linq; using Avalonia.Controls.Primitives; using Avalonia.Controls.Utils; @@ -159,6 +160,7 @@ protected override Size MeasureOverride(Size availableSize) try { + _realizedElements?.ValidateStartU(Orientation); _realizedElements ??= new(); _measureElements ??= new(); @@ -179,6 +181,10 @@ protected override Size MeasureOverride(Size availableSize) (_measureElements, _realizedElements) = (_realizedElements, _measureElements); _measureElements.ResetForReuse(); + // If there is a focused element is outside the visible viewport (i.e. + // _focusedElement is non-null), ensure it's measured. + _focusedElement?.Measure(availableSize); + return CalculateDesiredSize(orientation, items.Count, viewport); } finally @@ -215,6 +221,16 @@ protected override Size ArrangeOverride(Size finalSize) } } + // Ensure that the focused element is in the correct position. + if (_focusedElement is not null && _focusedIndex >= 0) + { + u = GetOrEstimateElementU(_focusedIndex); + var rect = orientation == Orientation.Horizontal ? + new Rect(u, 0, _focusedElement.DesiredSize.Width, finalSize.Height) : + new Rect(0, u, finalSize.Width, _focusedElement.DesiredSize.Height); + _focusedElement.Arrange(rect); + } + return finalSize; } finally @@ -389,7 +405,7 @@ protected internal override int IndexFromContainer(Control container) scrollToElement.Measure(Size.Infinity); // Get the expected position of the element and put it in place. - var anchorU = _realizedElements.GetOrEstimateElementU(index, ref _lastEstimatedElementSizeU); + var anchorU = GetOrEstimateElementU(index); var rect = Orientation == Orientation.Horizontal ? new Rect(anchorU, 0, scrollToElement.DesiredSize.Width, scrollToElement.DesiredSize.Height) : new Rect(0, anchorU, scrollToElement.DesiredSize.Width, scrollToElement.DesiredSize.Height); @@ -472,11 +488,12 @@ private MeasureViewport CalculateMeasureViewport(IReadOnlyList<object?> items) } else { - (anchorIndex, anchorU) = _realizedElements.GetOrEstimateAnchorElementForViewport( + GetOrEstimateAnchorElementForViewport( viewportStart, viewportEnd, items.Count, - ref _lastEstimatedElementSizeU); + out anchorIndex, + out anchorU); } // Check if the anchor element is not within the currently realized elements. @@ -531,12 +548,98 @@ private double EstimateElementSizeU() if (_realizedElements is null) return _lastEstimatedElementSizeU; - var result = _realizedElements.EstimateElementSizeU(); - if (result >= 0) - _lastEstimatedElementSizeU = result; - return _lastEstimatedElementSizeU; + var orientation = Orientation; + var total = 0.0; + var divisor = 0.0; + + // Average the desired size of the realized, measured elements. + foreach (var element in _realizedElements.Elements) + { + if (element is null || !element.IsMeasureValid) + continue; + var sizeU = orientation == Orientation.Horizontal ? + element.DesiredSize.Width : + element.DesiredSize.Height; + total += sizeU; + ++divisor; + } + + // Check we have enough information on which to base our estimate. + if (divisor == 0 || total == 0) + return _lastEstimatedElementSizeU; + + // Store and return the estimate. + return _lastEstimatedElementSizeU = total / divisor; + } + + private void GetOrEstimateAnchorElementForViewport( + double viewportStartU, + double viewportEndU, + int itemCount, + out int index, + out double position) + { + // We have no elements, or we're at the start of the viewport. + if (itemCount <= 0 || MathUtilities.IsZero(viewportStartU)) + { + index = 0; + position = 0; + return; + } + + // If we have realised elements and a valid StartU then try to use this information to + // get the anchor element. + if (_realizedElements?.StartU is { } u && !double.IsNaN(u)) + { + var orientation = Orientation; + + for (var i = 0; i < _realizedElements.Elements.Count; ++i) + { + if (_realizedElements.Elements[i] is not { } element) + continue; + + var sizeU = orientation == Orientation.Horizontal ? + element.DesiredSize.Width : + element.DesiredSize.Height; + var endU = u + sizeU; + + if (endU > viewportStartU && u < viewportEndU) + { + index = _realizedElements.FirstIndex + i; + position = u; + return; + } + + u = endU; + } + } + + // We don't have any realized elements in the requested viewport, or can't rely on + // StartU being valid. Estimate the index using only the estimated element size. + var estimatedSize = EstimateElementSizeU(); + + // Estimate the element at the start of the viewport. + var startIndex = Math.Min((int)(viewportStartU / estimatedSize), itemCount - 1); + index = startIndex; + position = startIndex * estimatedSize; } + private double GetOrEstimateElementU(int index) + { + // Return the position of the existing element if realized. + var u = _realizedElements?.GetElementU(index) ?? double.NaN; + + if (!double.IsNaN(u)) + return u; + + // Estimate the element size. + var estimatedSize = EstimateElementSizeU(); + + // TODO: Use _startU to work this out. + return index * estimatedSize; + } + + private void RealizeElements( IReadOnlyList<object?> items, Size availableSize,
diff --git a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs index 37d0f2ced45..d1ee1662f05 100644 --- a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs +++ b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs @@ -1192,6 +1192,112 @@ public void ScrollIntoView_Correctly_Scrolls_Down_To_A_Page_Of_Larger_Items() AssertRealizedItems(target, itemsControl, 15, 5); } + [Fact] + public void Extent_And_Offset_Should_Be_Updated_When_Containers_Resize() + { + using var app = App(); + + // All containers start off with a height of 50 (2 containers fit in viewport). + var items = Enumerable.Range(0, 20).Select(x => new ItemWithHeight(x, 50)).ToList(); + var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: CanvasWithHeightTemplate); + + // Scroll to the 5th item (containers 4 and 5 should be visible). + target.ScrollIntoView(5); + Assert.Equal(4, target.FirstRealizedIndex); + Assert.Equal(5, target.LastRealizedIndex); + + // The extent should be 500 (10 * 50) and the offset should be 200 (4 * 50). + var container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(5)); + Assert.Equal(new Rect(0, 250, 100, 50), container.Bounds); + Assert.Equal(new Size(100, 100), scroll.Viewport); + Assert.Equal(new Size(100, 1000), scroll.Extent); + Assert.Equal(new Vector(0, 200), scroll.Offset); + + // Update the height of all items to 25 and run a layout pass. + foreach (var item in items) + item.Height = 25; + target.UpdateLayout(); + + // The extent should be updated to reflect the new heights. The offset should be + // unchanged but the first realized index should be updated to 8 (200 / 25). + Assert.Equal(new Size(100, 100), scroll.Viewport); + Assert.Equal(new Size(100, 500), scroll.Extent); + Assert.Equal(new Vector(0, 200), scroll.Offset); + Assert.Equal(8, target.FirstRealizedIndex); + Assert.Equal(11, target.LastRealizedIndex); + } + + [Fact] + public void Focused_Container_Is_Positioned_Correctly_when_Container_Size_Change_Causes_It_To_Be_Moved_Out_Of_Visible_Viewport() + { + using var app = App(); + + // All containers start off with a height of 50 (2 containers fit in viewport). + var items = Enumerable.Range(0, 20).Select(x => new ItemWithHeight(x, 50)).ToList(); + var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: CanvasWithHeightTemplate); + + // Scroll to the 5th item (containers 4 and 5 should be visible). + target.ScrollIntoView(5); + Assert.Equal(4, target.FirstRealizedIndex); + Assert.Equal(5, target.LastRealizedIndex); + + // Focus the 5th item. + var container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(5)); + container.Focusable = true; + container.Focus(); + + // Update the height of all items to 25 and run a layout pass. + foreach (var item in items) + item.Height = 25; + target.UpdateLayout(); + + // The focused container should now be outside the realized range. + Assert.Equal(8, target.FirstRealizedIndex); + Assert.Equal(11, target.LastRealizedIndex); + + // The container should still exist and be positioned outside the visible viewport. + container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(5)); + Assert.Equal(new Rect(0, 125, 100, 25), container.Bounds); + } + + [Fact] + public void Focused_Container_Is_Positioned_Correctly_when_Container_Size_Change_Causes_It_To_Be_Moved_Into_Visible_Viewport() + { + using var app = App(); + + // All containers start off with a height of 25 (4 containers fit in viewport). + var items = Enumerable.Range(0, 20).Select(x => new ItemWithHeight(x, 25)).ToList(); + var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: CanvasWithHeightTemplate); + + // Scroll to the 5th item (containers 4-7 should be visible). + target.ScrollIntoView(7); + Assert.Equal(4, target.FirstRealizedIndex); + Assert.Equal(7, target.LastRealizedIndex); + + // Focus the 7th item. + var container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(7)); + container.Focusable = true; + container.Focus(); + + // Scroll up to the 3rd item (containers 3-6 should still be visible). + target.ScrollIntoView(3); + Assert.Equal(3, target.FirstRealizedIndex); + Assert.Equal(6, target.LastRealizedIndex); + + // Update the height of all items to 20 and run a layout pass. + foreach (var item in items) + item.Height = 20; + target.UpdateLayout(); + + // The focused container should now be inside the realized range. + Assert.Equal(3, target.FirstRealizedIndex); + Assert.Equal(7, target.LastRealizedIndex); + + // The container should be positioned correctly. + container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(7)); + Assert.Equal(new Rect(0, 140, 100, 20), container.Bounds); + } + private static IReadOnlyList<int> GetRealizedIndexes(VirtualizingStackPanel target, ItemsControl itemsControl) { return target.GetRealizedElements() @@ -1354,8 +1460,10 @@ private static IControlTemplate ScrollViewerTemplate() private static IDisposable App() => UnitTestApplication.Start(TestServices.RealFocus); - private class ItemWithHeight + private class ItemWithHeight : NotifyingBase { + private double _height; + public ItemWithHeight(int index, double height = 10) { Caption = $"Item {index}"; @@ -1363,7 +1471,12 @@ public ItemWithHeight(int index, double height = 10) } public string Caption { get; set; } - public double Height { get; set; } + + public double Height + { + get => _height; + set => SetField(ref _height, value); + } } private class ItemWithIsVisible : NotifyingBase
Listbox virtualized with zoom in/out (using LayoutTransformControl) issues ### Describe the bug If we use a ListBox with a LayoutTransformControl in the ListBoxItem to be able to zoom in/out, there are some issues : 1) If I slide to an item, then zoom out and scroll to the first item, there are a space left before the first item : ![EmptySpaceUpAfterDezoom](https://github.com/AvaloniaUI/Avalonia/assets/4248852/5dafc0fa-a660-4a46-8250-8c1eb97def9e) 2) If I zoom out, select an item, then zoom in (until the selected item goes out of the viewport), the selected item will be still displayed with the old position ![SelectedItemFocusedMoveAtZoom](https://github.com/AvaloniaUI/Avalonia/assets/4248852/22e6316d-7d89-49bb-b7ee-5fb50dc279c4) 3) at launch, there are one ListBoxItem realized, if I zoom out, of course more items will be realized. But if I zoom in again, the max number of ListBoxItem will remain (of course they will be empty). It should be better to flush those item. ![TooMuchListboxItemInTheRecyclerWhenDezoomZoom](https://github.com/AvaloniaUI/Avalonia/assets/4248852/a0600594-b72b-4f20-9baa-8c277c4aa7a1) ### To Reproduce Here is the sample to reproduce : https://github.com/Whiletru3/Avalonia/tree/VirtualizationImagesSample/samples/VirtualizationImages ### Expected behavior The ListBox should react normally using a LayoutTransformControl ### Avalonia version 11.0.10, 11.1 ### OS Windows, macOS ### Additional context _No response_
Do you have any clue (to make a PR) for the resolution of this bug ?
2024-06-29T11:22:15Z
0.1
['Avalonia.Controls.UnitTests.VirtualizingStackPanelTests.Extent_And_Offset_Should_Be_Updated_When_Containers_Resize', 'Avalonia.Controls.UnitTests.VirtualizingStackPanelTests.Focused_Container_Is_Positioned_Correctly_when_Container_Size_Change_Causes_It_To_Be_Moved_Out_Of_Visible_Viewport', 'Avalonia.Controls.UnitTests.VirtualizingStackPanelTests.Focused_Container_Is_Positioned_Correctly_when_Container_Size_Change_Causes_It_To_Be_Moved_Into_Visible_Viewport']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16102
143399f65abc8b97b479b1f8ed9d74b1a6a65303
diff --git a/src/Avalonia.Base/Data/Core/UntypedObservableBindingExpression.cs b/src/Avalonia.Base/Data/Core/UntypedObservableBindingExpression.cs index 1e26caa0512..df529d8675e 100644 --- a/src/Avalonia.Base/Data/Core/UntypedObservableBindingExpression.cs +++ b/src/Avalonia.Base/Data/Core/UntypedObservableBindingExpression.cs @@ -30,5 +30,18 @@ protected override void StopCore() void IObserver<object?>.OnCompleted() { } void IObserver<object?>.OnError(Exception error) { } - void IObserver<object?>.OnNext(object? value) => PublishValue(value); + + void IObserver<object?>.OnNext(object? value) + { + if (value is BindingNotification n) + { + var v = n.Value; + var e = n.Error is not null ? new BindingError(n.Error, n.ErrorType) : null; + PublishValue(v, e); + } + else + { + PublishValue(value); + } + } }
diff --git a/tests/Avalonia.Markup.UnitTests/Data/MultiBindingTests.cs b/tests/Avalonia.Markup.UnitTests/Data/MultiBindingTests.cs index f6a4437a9ef..0a20c25b15f 100644 --- a/tests/Avalonia.Markup.UnitTests/Data/MultiBindingTests.cs +++ b/tests/Avalonia.Markup.UnitTests/Data/MultiBindingTests.cs @@ -180,6 +180,28 @@ public void MultiBinding_Without_StringFormat_And_Converter() Assert.Equal(target.ItemsView[2], source.C); } + [Fact] + public void Converter_Can_Return_BindingNotification() + { + var source = new { A = 1, B = 2, C = 3 }; + var target = new TextBlock { DataContext = source }; + + var binding = new MultiBinding + { + Converter = new BindingNotificationConverter(), + Bindings = new[] + { + new Binding { Path = "A" }, + new Binding { Path = "B" }, + new Binding { Path = "C" }, + }, + }; + + target.Bind(TextBlock.TextProperty, binding); + + Assert.Equal("1,2,3-BindingNotification", target.Text); + } + private class ConcatConverter : IMultiValueConverter { public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) @@ -203,5 +225,16 @@ public object Convert(IList<object> values, Type targetType, object parameter, C return null; } } + + private class BindingNotificationConverter : IMultiValueConverter + { + public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) + { + return new BindingNotification( + new ArgumentException(), + BindingErrorType.Error, + string.Join(",", values) + "-BindingNotification"); + } + } } }
Regression in 11.1: MultiValueConverter returning BindingNotification throws InvalidCastException ### Describe the bug In my application I have several `IMultiValueConverter`s that return a `BindingNotification` when values can't be converted. The [documentation](https://docs.avaloniaui.net/docs/guides/data-binding/how-to-create-a-custom-data-binding-converter#example) suggests this is a best practice. With 11.0.10 I have no issues, however when I tried 11.1.0-rc1, I started to get `InvalidCastException`s like the following when navigating through the application: <details> <summary><code>System.InvalidCastException: Unable to cast object of type 'MultiBindingBug.ViewModels.MainWindowViewModel' to type 'MultiBindingBug.ViewModels.MultiConverterViewModel'.</code></summary> ``` at CompiledAvaloniaXaml.XamlIlHelpers.MultiBindingBug.ViewModels.MultiConverterViewModel,MultiBindingBug.Welcome!Getter(Object) at Avalonia.Data.Core.ClrPropertyInfo.Get(Object target) at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.get_Value() at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SendCurrentValue() ``` </details> In the debugger, stepping up through the stack, I see that in `PropertyInfoAccessorFactory.SendCurrentValue` a different exception is being caught: <details> <summary><code>System.InvalidCastException: Unable to cast object of type 'Avalonia.Data.BindingNotification' to type 'System.String'.</code></summary> ``` at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(ValueStore owner, AvaloniaProperty property, Object value) at Avalonia.PropertyStore.ValueStore.SetLocalValue(AvaloniaProperty property, Object value) at Avalonia.PropertyStore.ValueStore.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(UntypedBindingExpressionBase instance, Boolean hasValueChanged, Boolean hasErrorChanged, Object value, BindingError error) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(Object value, BindingError error) at Avalonia.Data.Core.UntypedObservableBindingExpression.System.IObserver<System.Object>.OnNext(Object value) at Avalonia.Reactive.Observable.<>c__DisplayClass4_1`1.<Where>b__1(TSource input) at Avalonia.Reactive.AnonymousObserver`1.OnNext(T value) at Avalonia.Reactive.Observable.<>c__DisplayClass2_1`2.<Select>b__1(TSource input) at Avalonia.Reactive.AnonymousObserver`1.OnNext(T value) at Avalonia.Reactive.Operators.Sink`1.ForwardOnNext(TTarget value) at Avalonia.Reactive.Operators.CombineLatest`2._.OnNext(Int32 index, TSource value) at Avalonia.Reactive.Operators.CombineLatest`2._.SourceObserver.OnNext(TSource value) at Avalonia.Reactive.LightweightObservableBase`1.PublishNext(T value) at Avalonia.Data.Core.UntypedBindingExpressionBase.ObservableSink.PublishNext(Object value) at Avalonia.Data.Core.UntypedBindingExpressionBase.ObservableSink.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(UntypedBindingExpressionBase instance, Boolean hasValueChanged, Boolean hasErrorChanged, Object value, BindingError error) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(Object value, BindingError error) at Avalonia.Data.Core.BindingExpression.ConvertAndPublishValue(Object value, BindingError error) at Avalonia.Data.Core.BindingExpression.OnNodeError(Int32 nodeIndex, String error) at Avalonia.Data.Core.BindingExpression.OnNodeValueChanged(Int32 nodeIndex, Object value, Exception dataValidationError) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(Object value, Exception dataValidationError) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(Object valueOrNotification) at Avalonia.Data.Core.ExpressionNodes.DataContextNode.OnPropertyChanged(Object sender, AvaloniaPropertyChangedEventArgs e) at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue) at Avalonia.PropertyStore.EffectiveValue`1.RaiseInheritedValueChanged(AvaloniaObject owner, AvaloniaProperty property, EffectiveValue oldValue, EffectiveValue newValue) at Avalonia.PropertyStore.ValueStore.InheritedValueChanged(AvaloniaProperty property, EffectiveValue oldValue, EffectiveValue newValue) at Avalonia.PropertyStore.ValueStore.InheritedValueChanged(AvaloniaProperty property, EffectiveValue oldValue, EffectiveValue newValue) at Avalonia.PropertyStore.ValueStore.InheritedValueChanged(AvaloniaProperty property, EffectiveValue oldValue, EffectiveValue newValue) at Avalonia.PropertyStore.ValueStore.InheritedValueChanged(AvaloniaProperty property, EffectiveValue oldValue, EffectiveValue newValue) at Avalonia.PropertyStore.ValueStore.SetInheritanceParent(AvaloniaObject newParent) at Avalonia.AvaloniaObject.set_InheritanceParent(AvaloniaObject value) at Avalonia.StyledElement.Avalonia.Controls.ISetLogicalParent.SetParent(ILogical parent) at Avalonia.StyledElement.ClearLogicalParent(IList children) at Avalonia.StyledElement.LogicalChildrenCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at Avalonia.Visual.LogicalChildrenCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at Avalonia.Collections.AvaloniaList`1.NotifyRemove(T item, Int32 index) at Avalonia.Collections.AvaloniaList`1.Remove(T item) at Avalonia.Controls.Presenters.ContentPresenter.UpdateChild(Object content) at Avalonia.Controls.Presenters.ContentPresenter.ContentChanged(AvaloniaPropertyChangedEventArgs e) at Avalonia.Controls.Presenters.ContentPresenter.OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) at Avalonia.AvaloniaObject.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change) at Avalonia.Animation.Animatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change) at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaise(ValueStore owner, IValueEntry value, BindingPriority priority) at Avalonia.PropertyStore.ValueStore.ReevaluateEffectiveValue(AvaloniaProperty property, EffectiveValue current, IValueEntry changedValueEntry, Boolean ignoreLocalValue) at Avalonia.PropertyStore.ValueStore.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(UntypedBindingExpressionBase instance, Boolean hasValueChanged, Boolean hasErrorChanged, Object value, BindingError error) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(Object value, BindingError error) at Avalonia.Data.TemplateBinding.PublishValue() at Avalonia.Data.TemplateBinding.OnTemplatedParentPropertyChanged(Object sender, AvaloniaPropertyChangedEventArgs e) at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(ValueStore owner, StyledProperty`1 property, T value) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(ValueStore owner, AvaloniaProperty property, Object value) at Avalonia.PropertyStore.ValueStore.SetLocalValue(AvaloniaProperty property, Object value) at Avalonia.PropertyStore.ValueStore.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(UntypedBindingExpressionBase instance, Boolean hasValueChanged, Boolean hasErrorChanged, Object value, BindingError error) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(Object value, BindingError error) at Avalonia.Data.Core.BindingExpression.ConvertAndPublishValue(Object value, BindingError error) at Avalonia.Data.Core.BindingExpression.OnNodeValueChanged(Int32 nodeIndex, Object value, Exception dataValidationError) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(Object value, Exception dataValidationError) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(Object valueOrNotification) at Avalonia.Data.Core.ExpressionNodes.PropertyAccessorNode.OnValueChanged(Object newValue) at Avalonia.Data.Core.Plugins.PropertyAccessorBase.PublishValue(Object value) at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SendCurrentValue() ``` </details> This is what lead me to the conclusion that the problem was with the converter returning a `BindingNotification`. ### To Reproduce In my application, the exception occurs when navigating between views and seems to be triggered by changes in DataContext. I have tried to create a minimal repro: <details> <summary>MainWindow.xaml</summary> ```xaml <Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="using:MultiBindingBug.ViewModels" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:views="clr-namespace:MultiBindingBug.Views" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="MultiBindingBug.Views.MainWindow" x:DataType="vm:MainWindowViewModel" Title="MultiBindingBug"> <Grid ColumnDefinitions="Auto,*"> <StackPanel Grid.Column="0"> <Button Command="{Binding HomeCommand}">Home</Button> <Button Command="{Binding MultiConverterCommand}">MultiConverter</Button> </StackPanel> <ContentControl Content="{Binding SelectedContent}" Margin="0,0,2,0" Grid.Column="1"> <ContentControl.DataTemplates> <DataTemplate DataType="vm:HomeViewModel"> <views:HomeView /> </DataTemplate> <DataTemplate DataType="vm:MultiConverterViewModel"> <views:MultiConverterView /> </DataTemplate> </ContentControl.DataTemplates> </ContentControl> </Grid> </Window> ``` </details> <details> <summary>HomeView.xaml</summary> ```xaml <UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="MultiBindingBug.Views.HomeView"> Home </UserControl> ``` </details> <details> <summary>MultiConverter.xaml</summary> ```xaml <UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="using:MultiBindingBug.ViewModels" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="MultiBindingBug.Views.MultiConverterView" x:DataType="vm:MultiConverterViewModel"> <StackPanel> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock.Text> <MultiBinding Converter="{x:Static vm:MultiValueConverter.Instance}" ConverterParameter=" "> <Binding Path="Welcome" /> <Binding Path="To" /> <Binding Path="Avalonia" /> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </UserControl> ``` </details> <details> <summary>MainWindowViewModel.cs</summary> ```cs using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace MultiBindingBug.ViewModels; public partial class MainWindowViewModel : ObservableObject { private readonly HomeViewModel _home = new HomeViewModel(); private readonly MultiConverterViewModel _multiConverter = new MultiConverterViewModel(); public MainWindowViewModel() => SelectedContent = _home; [RelayCommand] public void Home() => SelectedContent = _home; [RelayCommand] public void MultiConverter() => SelectedContent = _multiConverter; [ObservableProperty] private object? _selectedContent; } ``` </details> <details> <summary>HomeViewModel.cs</summary> ```cs namespace MultiBindingBug.ViewModels; public class HomeViewModel { } ``` </details> <details> <summary>MultiConverterViewModel.cs</summary> ```cs namespace MultiBindingBug.ViewModels; public class MultiConverterViewModel { public string Welcome => "Welcome"; public string To => "to"; public string Avalonia => "Avalonia!"; } ``` </details> <details> <summary>MultiValueConverter.cs</summary> ```cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia.Data; using Avalonia.Data.Converters; namespace MultiBindingBug.ViewModels; public class MultiValueConverter : IMultiValueConverter { public static MultiValueConverter Instance { get; } = new(); public object Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture) { if (values.All(v => v is string) && parameter is string separator) { return string.Join(separator, values.Cast<string>()); } return new BindingNotification(new ArgumentException(), BindingErrorType.Error); } } ``` </details> Steps to reproduce: 1. Run the application. `HomeView` is displayed. 2. Click on the "MultiConverter" button to switch to `MultiConverterView`. 3. Click on the "Home" button. The exception is thrown. ### Expected behavior No exception is thrown. (If I'm doing something wrong in my `MultiValueConverter` please advise.) ### Avalonia version 11.1.0-rc1 ### OS Windows ### Additional context Workarounds: 1. Downgrade to Avalonia 11.0.10 2. Modify `MultiValueConverter.cs` to return `null` instead of a `BindingNotification`
Definitely looks like a regression introduced by the binding system refactor, will investigate. Not sure if this is a showstopper and needs to be fixed for 11.1.0 or whether it can wait for 11.1.1 though. > Definitely looks like a regression introduced by the binding system refactor, will investigate. > > Not sure if this is a showstopper and needs to be fixed for 11.0.0 or whether it can wait for 11.0.1 though. Assuming you mean 11.1.0 and 11.1.1? For me, I don't use the `BindingNotification`s my converters were returning, so I could return null. I'm also not in a big hurry to move to 11.1, so I could wait. I would suggest documenting this as a known issue though, because my application was very broken and it took me a long time to track it down to the `BindingNotifcation`s. > Assuming you mean 11.1.0 and 11.1.1? Yeah sorry, edited. I'll take a look and see how hard the fix is before we decide if it'll be in 11.1.0. It definitely feels like less of a showstopper than #16071 though.
2024-06-24T13:15:19Z
0.1
['Avalonia.Markup.UnitTests.Data.MultiBindingTests.Converter_Can_Return_BindingNotification']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16090
34558f25e0489e4c231c6217dfcf0c949b9ac5c6
diff --git a/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj b/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj index 734f126a1b2..9a67ee0161e 100644 --- a/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj +++ b/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/project.pbxproj @@ -34,7 +34,7 @@ 1AFD334123E03C4F0042899B /* controlhost.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1AFD334023E03C4F0042899B /* controlhost.mm */; }; 37155CE4233C00EB0034DCE9 /* menu.h in Headers */ = {isa = PBXBuildFile; fileRef = 37155CE3233C00EB0034DCE9 /* menu.h */; }; 37A517B32159597E00FBA241 /* Screens.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37A517B22159597E00FBA241 /* Screens.mm */; }; - 37C09D8821580FE4006A6758 /* SystemDialogs.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37C09D8721580FE4006A6758 /* SystemDialogs.mm */; }; + 37C09D8821580FE4006A6758 /* StorageProvider.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37C09D8721580FE4006A6758 /* StorageProvider.mm */; }; 37DDA9B0219330F8002E132B /* AvnString.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37DDA9AF219330F8002E132B /* AvnString.mm */; }; 37E2330F21583241000CB7E2 /* KeyTransform.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37E2330E21583241000CB7E2 /* KeyTransform.mm */; }; 520624B322973F4100C4DCEF /* menu.mm in Sources */ = {isa = PBXBuildFile; fileRef = 520624B222973F4100C4DCEF /* menu.mm */; }; @@ -95,7 +95,7 @@ 379860FE214DA0C000CD0246 /* KeyTransform.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = KeyTransform.h; sourceTree = "<group>"; }; 37A4E71A2178846A00EACBCD /* headers */ = {isa = PBXFileReference; lastKnownFileType = folder; name = headers; path = ../../inc; sourceTree = "<group>"; }; 37A517B22159597E00FBA241 /* Screens.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = Screens.mm; sourceTree = "<group>"; }; - 37C09D8721580FE4006A6758 /* SystemDialogs.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = SystemDialogs.mm; sourceTree = "<group>"; }; + 37C09D8721580FE4006A6758 /* StorageProvider.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = StorageProvider.mm; sourceTree = "<group>"; }; 37DDA9AF219330F8002E132B /* AvnString.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = AvnString.mm; sourceTree = "<group>"; }; 37DDA9B121933371002E132B /* AvnString.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AvnString.h; sourceTree = "<group>"; }; 37E2330E21583241000CB7E2 /* KeyTransform.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = KeyTransform.mm; sourceTree = "<group>"; }; @@ -202,7 +202,7 @@ 523484CB26EA68AA00EA0C2C /* trayicon.h */, 1A3E5EA723E9E83B00EDE661 /* rendertarget.mm */, 37A517B22159597E00FBA241 /* Screens.mm */, - 37C09D8721580FE4006A6758 /* SystemDialogs.mm */, + 37C09D8721580FE4006A6758 /* StorageProvider.mm */, EDF8CDCC2964CB01001EE34F /* PlatformSettings.mm */, AB7A61F02147C815003C5833 /* Products */, AB661C1C2148230E00291242 /* Frameworks */, @@ -339,7 +339,7 @@ 1AFD334123E03C4F0042899B /* controlhost.mm in Sources */, 1A465D10246AB61600C5858B /* dnd.mm in Sources */, AB00E4F72147CA920032A60A /* main.mm in Sources */, - 37C09D8821580FE4006A6758 /* SystemDialogs.mm in Sources */, + 37C09D8821580FE4006A6758 /* StorageProvider.mm in Sources */, 1839179A55FC1421BEE83330 /* WindowBaseImpl.mm in Sources */, F10084862BFF1FB40024303E /* TopLevelImpl.mm in Sources */, 1839125F057B0A4EB1760058 /* WindowImpl.mm in Sources */, diff --git a/native/Avalonia.Native/src/OSX/SystemDialogs.mm b/native/Avalonia.Native/src/OSX/StorageProvider.mm similarity index 85% rename from native/Avalonia.Native/src/OSX/SystemDialogs.mm rename to native/Avalonia.Native/src/OSX/StorageProvider.mm index 97c8108edcb..0fd77c6789e 100644 --- a/native/Avalonia.Native/src/OSX/SystemDialogs.mm +++ b/native/Avalonia.Native/src/OSX/StorageProvider.mm @@ -64,12 +64,91 @@ - (void)popupAction:(id)sender { @end -class SystemDialogs : public ComSingleObject<IAvnSystemDialogs, &IID_IAvnSystemDialogs> +class StorageProvider : public ComSingleObject<IAvnStorageProvider, &IID_IAvnStorageProvider> { ExtensionDropdownHandler* __strong _extension_dropdown_handler; public: FORWARD_IUNKNOWN() + + virtual HRESULT SaveBookmarkToBytes ( + IAvnString* fileUriStr, + void** err, + IAvnString** ppv + ) override + { + @autoreleasepool + { + if(ppv == nullptr) + return E_POINTER; + + NSError* error; + auto fileUri = [NSURL URLWithString: GetNSStringAndRelease(fileUriStr)]; + auto bookmarkData = [fileUri bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; + if (bookmarkData) + { + *ppv = CreateByteArray((void*)bookmarkData.bytes, (int)bookmarkData.length); + } + if (error != nil) + { + *err = CreateAvnString([error localizedDescription]); + } + return S_OK; + } + } + + virtual HRESULT ReadBookmarkFromBytes ( + void* ptr, + int len, + IAvnString** ppv + ) override { + @autoreleasepool + { + if(ppv == nullptr) + return E_POINTER; + + auto bookmarkData = [[NSData alloc] initWithBytes:ptr length:len]; + auto fileUri = [NSURL URLByResolvingBookmarkData: bookmarkData + options:NSURLBookmarkResolutionWithSecurityScope|NSURLBookmarkResolutionWithoutUI + relativeToURL:nil + bookmarkDataIsStale:nil + error:nil]; + + if (fileUri) + { + *ppv = CreateAvnString([fileUri absoluteString]); + } + return S_OK; + } + } + + virtual void ReleaseBookmark ( + IAvnString* fileUriStr + ) override { + // no-op + } + + virtual bool OpenSecurityScope ( + IAvnString* fileUriStr + ) override { + @autoreleasepool + { + auto fileUri = [NSURL URLWithString: GetNSStringAndRelease(fileUriStr)]; + auto success = [fileUri startAccessingSecurityScopedResource]; + return success; + } + } + + virtual void CloseSecurityScope ( + IAvnString* fileUriStr + ) override { + @autoreleasepool + { + auto fileUri = [NSURL URLWithString: GetNSStringAndRelease(fileUriStr)]; + [fileUri stopAccessingSecurityScopedResource]; + } + } + virtual void SelectFolderDialog (IAvnWindow* parentWindowHandle, IAvnSystemDialogEvents* events, bool allowMultiple, @@ -105,19 +184,9 @@ virtual void SelectFolderDialog (IAvnWindow* parentWindowHandle, if(urls.count > 0) { - void* strings[urls.count]; - - for(int i = 0; i < urls.count; i++) - { - auto url = [urls objectAtIndex:i]; - - auto string = [url path]; - - strings[i] = (void*)[string UTF8String]; - } - - events->OnCompleted((int)urls.count, &strings[0]); - + auto uriStrings = CreateAvnStringArray(urls); + events->OnCompleted(uriStrings); + [panel orderOut:panel]; if(parentWindowHandle != nullptr) @@ -130,7 +199,7 @@ virtual void SelectFolderDialog (IAvnWindow* parentWindowHandle, } } - events->OnCompleted(0, nullptr); + events->OnCompleted(nullptr); }; @@ -188,19 +257,9 @@ virtual void OpenFileDialog (IAvnWindow* parentWindowHandle, if(urls.count > 0) { - void* strings[urls.count]; - - for(int i = 0; i < urls.count; i++) - { - auto url = [urls objectAtIndex:i]; - - auto string = [url path]; - - strings[i] = (void*)[string UTF8String]; - } - - events->OnCompleted((int)urls.count, &strings[0]); - + auto uriStrings = CreateAvnStringArray(urls); + events->OnCompleted(uriStrings); + [panel orderOut:panel]; if(parentWindowHandle != nullptr) @@ -213,7 +272,7 @@ virtual void OpenFileDialog (IAvnWindow* parentWindowHandle, } } - events->OnCompleted(0, nullptr); + events->OnCompleted(nullptr); }; @@ -264,15 +323,11 @@ virtual void SaveFileDialog (IAvnWindow* parentWindowHandle, auto handler = ^(NSModalResponse result) { if(result == NSFileHandlingPanelOKButton) { - void* strings[1]; - auto url = [panel URL]; - - auto string = [url path]; - strings[0] = (void*)[string UTF8String]; - - events->OnCompleted(1, &strings[0]); - + auto urls = [NSArray<NSURL*> arrayWithObject:url]; + auto uriStrings = CreateAvnStringArray(urls); + events->OnCompleted(uriStrings); + [panel orderOut:panel]; if(parentWindowHandle != nullptr) @@ -284,7 +339,7 @@ virtual void SaveFileDialog (IAvnWindow* parentWindowHandle, return; } - events->OnCompleted(0, nullptr); + events->OnCompleted(nullptr); }; @@ -519,7 +574,7 @@ void SetAccessoryView(NSSavePanel* panel, }; }; -extern IAvnSystemDialogs* CreateSystemDialogs() +extern IAvnStorageProvider* CreateStorageProvider() { - return new SystemDialogs(); + return new StorageProvider(); } diff --git a/native/Avalonia.Native/src/OSX/common.h b/native/Avalonia.Native/src/OSX/common.h index fab11d6e4f7..36c157704de 100644 --- a/native/Avalonia.Native/src/OSX/common.h +++ b/native/Avalonia.Native/src/OSX/common.h @@ -14,7 +14,7 @@ extern void PostDispatcherCallback(IAvnActionCallback* cb); extern IAvnTopLevel* CreateAvnTopLevel(IAvnTopLevelEvents* events); extern IAvnWindow* CreateAvnWindow(IAvnWindowEvents*events); extern IAvnPopup* CreateAvnPopup(IAvnWindowEvents*events); -extern IAvnSystemDialogs* CreateSystemDialogs(); +extern IAvnStorageProvider* CreateStorageProvider(); extern IAvnScreens* CreateScreens(IAvnScreenEvents* cb); extern IAvnClipboard* CreateClipboard(NSPasteboard*, NSPasteboardItem*); extern NSPasteboardItem* TryGetPasteboardItem(IAvnClipboard*); diff --git a/native/Avalonia.Native/src/OSX/main.mm b/native/Avalonia.Native/src/OSX/main.mm index 47a5ba73c5f..d1dbe9d1862 100644 --- a/native/Avalonia.Native/src/OSX/main.mm +++ b/native/Avalonia.Native/src/OSX/main.mm @@ -276,13 +276,13 @@ virtual HRESULT CreatePlatformThreadingInterface(IAvnPlatformThreadingInterface* } } - virtual HRESULT CreateSystemDialogs(IAvnSystemDialogs** ppv) override + virtual HRESULT CreateStorageProvider(IAvnStorageProvider** ppv) override { START_COM_CALL; @autoreleasepool { - *ppv = ::CreateSystemDialogs(); + *ppv = ::CreateStorageProvider(); return S_OK; } } diff --git a/samples/ControlCatalog/Pages/DialogsPage.xaml.cs b/samples/ControlCatalog/Pages/DialogsPage.xaml.cs index fc66f533c6b..5b7814fb5d1 100644 --- a/samples/ControlCatalog/Pages/DialogsPage.xaml.cs +++ b/samples/ControlCatalog/Pages/DialogsPage.xaml.cs @@ -254,17 +254,24 @@ List<FileDialogFilter> GetFilters() if (file is not null) { - // Sync disposal of StreamWriter is not supported on WASM + try + { + // Sync disposal of StreamWriter is not supported on WASM #if NET6_0_OR_GREATER - await using var stream = await file.OpenWriteAsync(); - await using var writer = new System.IO.StreamWriter(stream); + await using var stream = await file.OpenWriteAsync(); + await using var writer = new System.IO.StreamWriter(stream); #else - using var stream = await file.OpenWriteAsync(); - using var writer = new System.IO.StreamWriter(stream); + using var stream = await file.OpenWriteAsync(); + using var writer = new System.IO.StreamWriter(stream); #endif - await writer.WriteLineAsync(openedFileContent.Text); + await writer.WriteLineAsync(openedFileContent.Text); - SetFolder(await file.GetParentAsync()); + SetFolder(await file.GetParentAsync()); + } + catch (Exception ex) + { + openedFileContent.Text = ex.ToString(); + } } await SetPickerResult(file is null ? null : new[] { file }); @@ -280,8 +287,6 @@ List<FileDialogFilter> GetFilters() }); await SetPickerResult(folders); - - SetFolder(folders.FirstOrDefault()); }; this.Get<Button>("OpenFileFromBookmark").Click += async delegate { @@ -298,7 +303,6 @@ List<FileDialogFilter> GetFilters() : null; await SetPickerResult(folder is null ? null : new[] { folder }); - SetFolder(folder); }; this.Get<Button>("LaunchUri").Click += async delegate @@ -360,16 +364,30 @@ async Task SetPickerResult(IReadOnlyCollection<IStorageItem>? items) Content: "; - resultText += await ReadTextFromFile(file, 500); + try + { + resultText += await ReadTextFromFile(file, 500); + } + catch (Exception ex) + { + resultText += ex.ToString(); + } } openedFileContent.Text = resultText; - var parent = await item.GetParentAsync(); - SetFolder(parent); - if (parent is not null) + if (item is IStorageFolder storageFolder) { - mappedResults.Add(FullPathOrName(parent)); + SetFolder(storageFolder); + } + else + { + var parent = await item.GetParentAsync(); + SetFolder(parent); + if (parent is not null) + { + mappedResults.Add(FullPathOrName(parent)); + } } foreach (var selectedItem in items) @@ -391,7 +409,7 @@ async Task SetPickerResult(IReadOnlyCollection<IStorageItem>? items) } } - public static async Task<string> ReadTextFromFile(IStorageFile file, int length) + internal static async Task<string> ReadTextFromFile(IStorageFile file, int length) { #if NET6_0_OR_GREATER await using var stream = await file.OpenReadAsync(); diff --git a/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs b/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs index 952717729ff..bb27379a702 100644 --- a/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs +++ b/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs @@ -10,6 +10,7 @@ using Android.Webkit; using Avalonia.Logging; using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; using Java.Lang; using AndroidUri = Android.Net.Uri; using Exception = System.Exception; @@ -53,7 +54,8 @@ protected AndroidStorageItem(Activity activity, AndroidUri uri, bool needsExtern } Activity.ContentResolver?.TakePersistableUriPermission(Uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission); - return Uri.ToString(); + + return StorageBookmarkHelper.EncodeBookmark(AndroidStorageProvider.AndroidKey, Uri.ToString()!); } public async Task ReleaseBookmarkAsync() diff --git a/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageProvider.cs b/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageProvider.cs index 64c9c3a3cb1..54d6afad43f 100644 --- a/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageProvider.cs +++ b/src/Android/Avalonia.Android/Platform/Storage/AndroidStorageProvider.cs @@ -1,12 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Threading.Tasks; using Android; using Android.App; using Android.Content; using Android.Provider; using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; using AndroidUri = Android.Net.Uri; using Exception = System.Exception; using JavaFile = Java.IO.File; @@ -15,6 +17,7 @@ namespace Avalonia.Android.Platform.Storage; internal class AndroidStorageProvider : IStorageProvider { + public static ReadOnlySpan<byte> AndroidKey => "android"u8; private readonly Activity _activity; public AndroidStorageProvider(Activity activity) @@ -30,8 +33,8 @@ public AndroidStorageProvider(Activity activity) public Task<IStorageBookmarkFolder?> OpenFolderBookmarkAsync(string bookmark) { - var uri = AndroidUri.Parse(bookmark) ?? throw new ArgumentException("Couldn't parse Bookmark value", nameof(bookmark)); - return Task.FromResult<IStorageBookmarkFolder?>(new AndroidStorageFolder(_activity, uri, false)); + var uri = DecodeUriFromBookmark(bookmark); + return Task.FromResult<IStorageBookmarkFolder?>(uri is null ? null : new AndroidStorageFolder(_activity, uri, false)); } public async Task<IStorageFile?> TryGetFileFromPathAsync(Uri filePath) @@ -129,8 +132,19 @@ public AndroidStorageProvider(Activity activity) public Task<IStorageBookmarkFile?> OpenFileBookmarkAsync(string bookmark) { - var uri = AndroidUri.Parse(bookmark) ?? throw new ArgumentException("Couldn't parse Bookmark value", nameof(bookmark)); - return Task.FromResult<IStorageBookmarkFile?>(new AndroidStorageFile(_activity, uri)); + var uri = DecodeUriFromBookmark(bookmark); + return Task.FromResult<IStorageBookmarkFile?>(uri is null ? null : new AndroidStorageFile(_activity, uri)); + } + + private static AndroidUri? DecodeUriFromBookmark(string bookmark) + { + return StorageBookmarkHelper.TryDecodeBookmark(AndroidKey, bookmark, out var bytes) switch + { + StorageBookmarkHelper.DecodeResult.Success => AndroidUri.Parse(Encoding.UTF8.GetString(bytes!)), + // Attempt to decode 11.0 android bookmarks + StorageBookmarkHelper.DecodeResult.InvalidFormat => AndroidUri.Parse(bookmark), + _ => null + }; } public async Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options) diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFile.cs b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFile.cs index 715fc182d64..c465dddb847 100644 --- a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFile.cs +++ b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFile.cs @@ -1,115 +1,10 @@ -using System; -using System.IO; -using System.Security; +using System.IO; using System.Threading.Tasks; namespace Avalonia.Platform.Storage.FileIO; -internal class BclStorageFile : IStorageBookmarkFile +internal sealed class BclStorageFile(FileInfo fileInfo) : BclStorageItem(fileInfo), IStorageBookmarkFile { - public BclStorageFile(FileInfo fileInfo) - { - FileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo)); - } - - public FileInfo FileInfo { get; } - - public string Name => FileInfo.Name; - - public virtual bool CanBookmark => true; - - public Uri Path - { - get - { - try - { - if (FileInfo.Directory is not null) - { - return StorageProviderHelpers.FilePathToUri(FileInfo.FullName); - } - } - catch (SecurityException) - { - } - return new Uri(FileInfo.Name, UriKind.Relative); - } - } - - public Task<StorageItemProperties> GetBasicPropertiesAsync() - { - if (FileInfo.Exists) - { - return Task.FromResult(new StorageItemProperties( - (ulong)FileInfo.Length, - FileInfo.CreationTimeUtc, - FileInfo.LastAccessTimeUtc)); - } - return Task.FromResult(new StorageItemProperties()); - } - - public Task<IStorageFolder?> GetParentAsync() - { - if (FileInfo.Directory is { } directory) - { - return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directory)); - } - return Task.FromResult<IStorageFolder?>(null); - } - - public Task<Stream> OpenReadAsync() - { - return Task.FromResult<Stream>(FileInfo.OpenRead()); - } - - public Task<Stream> OpenWriteAsync() - { - var stream = new FileStream(FileInfo.FullName, FileMode.Create, FileAccess.Write, FileShare.Write); - return Task.FromResult<Stream>(stream); - } - - public virtual Task<string?> SaveBookmarkAsync() - { - return Task.FromResult<string?>(FileInfo.FullName); - } - - public Task ReleaseBookmarkAsync() - { - // No-op - return Task.CompletedTask; - } - - protected virtual void Dispose(bool disposing) - { - } - - ~BclStorageFile() - { - Dispose(disposing: false); - } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public Task DeleteAsync() - { - FileInfo.Delete(); - return Task.CompletedTask; - } - - public Task<IStorageItem?> MoveAsync(IStorageFolder destination) - { - if (destination is BclStorageFolder storageFolder) - { - var newPath = System.IO.Path.Combine(storageFolder.DirectoryInfo.FullName, FileInfo.Name); - FileInfo.MoveTo(newPath); - - return Task.FromResult<IStorageItem?>(new BclStorageFile(new FileInfo(newPath))); - } - - return Task.FromResult<IStorageItem?>(null); - } + public Task<Stream> OpenReadAsync() => Task.FromResult<Stream>(OpenReadCore(fileInfo)); + public Task<Stream> OpenWriteAsync() => Task.FromResult<Stream>(OpenWriteCore(fileInfo)); } diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFolder.cs b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFolder.cs index a5727dc3cda..05572d60586 100644 --- a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFolder.cs +++ b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageFolder.cs @@ -1,128 +1,22 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Security; using System.Threading.Tasks; using Avalonia.Utilities; namespace Avalonia.Platform.Storage.FileIO; -internal class BclStorageFolder : IStorageBookmarkFolder +internal sealed class BclStorageFolder(DirectoryInfo directoryInfo) + : BclStorageItem(directoryInfo), IStorageBookmarkFolder { - public BclStorageFolder(DirectoryInfo directoryInfo) - { - DirectoryInfo = directoryInfo ?? throw new ArgumentNullException(nameof(directoryInfo)); - if (!DirectoryInfo.Exists) - { - throw new ArgumentException("Directory must exist", nameof(directoryInfo)); - } - } + public IAsyncEnumerable<IStorageItem> GetItemsAsync() => GetItemsCore(directoryInfo) + .Select(WrapFileSystemInfo) + .Where(f => f is not null) + .AsAsyncEnumerable()!; - public string Name => DirectoryInfo.Name; + public Task<IStorageFile?> CreateFileAsync(string name) => Task.FromResult( + (IStorageFile?)WrapFileSystemInfo(CreateFileCore(directoryInfo, name))); - public DirectoryInfo DirectoryInfo { get; } - - public bool CanBookmark => true; - - public Uri Path - { - get - { - try - { - return StorageProviderHelpers.FilePathToUri(DirectoryInfo.FullName); - } - catch (SecurityException) - { - return new Uri(DirectoryInfo.Name, UriKind.Relative); - } - } - } - - public Task<StorageItemProperties> GetBasicPropertiesAsync() - { - var props = new StorageItemProperties( - null, - DirectoryInfo.CreationTimeUtc, - DirectoryInfo.LastAccessTimeUtc); - return Task.FromResult(props); - } - - public Task<IStorageFolder?> GetParentAsync() - { - if (DirectoryInfo.Parent is { } directory) - { - return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directory)); - } - return Task.FromResult<IStorageFolder?>(null); - } - - public IAsyncEnumerable<IStorageItem> GetItemsAsync() - => DirectoryInfo.EnumerateDirectories() - .Select(d => (IStorageItem)new BclStorageFolder(d)) - .Concat(DirectoryInfo.EnumerateFiles().Select(f => new BclStorageFile(f))) - .AsAsyncEnumerable(); - - public virtual Task<string?> SaveBookmarkAsync() - { - return Task.FromResult<string?>(DirectoryInfo.FullName); - } - - public Task ReleaseBookmarkAsync() - { - // No-op - return Task.CompletedTask; - } - - protected virtual void Dispose(bool disposing) - { - } - - ~BclStorageFolder() - { - Dispose(disposing: false); - } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public Task DeleteAsync() - { - DirectoryInfo.Delete(true); - return Task.CompletedTask; - } - - public Task<IStorageItem?> MoveAsync(IStorageFolder destination) - { - if (destination is BclStorageFolder storageFolder) - { - var newPath = System.IO.Path.Combine(storageFolder.DirectoryInfo.FullName, DirectoryInfo.Name); - DirectoryInfo.MoveTo(newPath); - - return Task.FromResult<IStorageItem?>(new BclStorageFolder(new DirectoryInfo(newPath))); - } - - return Task.FromResult<IStorageItem?>(null); - } - - public Task<IStorageFile?> CreateFileAsync(string name) - { - var fileName = System.IO.Path.Combine(DirectoryInfo.FullName, name); - var newFile = new FileInfo(fileName); - - using var stream = newFile.Create(); - - return Task.FromResult<IStorageFile?>(new BclStorageFile(newFile)); - } - - public Task<IStorageFolder?> CreateFolderAsync(string name) - { - var newFolder = DirectoryInfo.CreateSubdirectory(name); - - return Task.FromResult<IStorageFolder?>(new BclStorageFolder(newFolder)); - } + public Task<IStorageFolder?> CreateFolderAsync(string name) => Task.FromResult( + (IStorageFolder?)WrapFileSystemInfo(CreateFolderCore(directoryInfo, name))); } diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageItem.cs b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageItem.cs new file mode 100644 index 00000000000..123d0e9283d --- /dev/null +++ b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageItem.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Security; +using System.Threading.Tasks; + +namespace Avalonia.Platform.Storage.FileIO; + +internal abstract class BclStorageItem(FileSystemInfo fileSystemInfo) : IStorageBookmarkItem, IStorageItemWithFileSystemInfo +{ + public FileSystemInfo FileSystemInfo { get; } = fileSystemInfo switch + { + null => throw new ArgumentNullException(nameof(fileSystemInfo)), + DirectoryInfo { Exists: false } => throw new ArgumentException("Directory must exist", nameof(fileSystemInfo)), + _ => fileSystemInfo + }; + + public string Name => FileSystemInfo.Name; + + public bool CanBookmark => true; + + public Uri Path => GetPathCore(FileSystemInfo); + + public Task<StorageItemProperties> GetBasicPropertiesAsync() + { + return Task.FromResult(GetBasicPropertiesAsyncCore(FileSystemInfo)); + } + + public Task<IStorageFolder?> GetParentAsync() => Task.FromResult( + (IStorageFolder?)WrapFileSystemInfo(GetParentCore(FileSystemInfo))); + + public Task DeleteAsync() + { + DeleteCore(FileSystemInfo); + return Task.CompletedTask; + } + + public Task<IStorageItem?> MoveAsync(IStorageFolder destination) => Task.FromResult( + WrapFileSystemInfo(MoveCore(FileSystemInfo, destination))); + + public Task<string?> SaveBookmarkAsync() + { + var path = FileSystemInfo.FullName; + return Task.FromResult<string?>(StorageBookmarkHelper.EncodeBclBookmark(path)); + } + + public Task ReleaseBookmarkAsync() => Task.CompletedTask; + + public void Dispose() { } + + [return: NotNullIfNotNull(nameof(fileSystemInfo))] + protected IStorageItem? WrapFileSystemInfo(FileSystemInfo? fileSystemInfo) => fileSystemInfo switch + { + DirectoryInfo directoryInfo => new BclStorageFolder(directoryInfo), + FileInfo fileInfo => new BclStorageFile(fileInfo), + _ => null + }; + + internal static void DeleteCore(FileSystemInfo fileSystemInfo) => fileSystemInfo.Delete(); + + internal static Uri GetPathCore(FileSystemInfo fileSystemInfo) + { + try + { + if (fileSystemInfo is DirectoryInfo { Parent: not null } or FileInfo { Directory: not null }) + { + return StorageProviderHelpers.UriFromFilePath(fileSystemInfo.FullName, fileSystemInfo is DirectoryInfo); + } + } + catch (SecurityException) + { + } + + return new Uri(fileSystemInfo.Name, UriKind.Relative); + } + + internal static StorageItemProperties GetBasicPropertiesAsyncCore(FileSystemInfo fileSystemInfo) + { + if (fileSystemInfo.Exists) + { + return new StorageItemProperties( + fileSystemInfo is FileInfo fileInfo ? (ulong)fileInfo.Length : 0, + fileSystemInfo.CreationTimeUtc, + fileSystemInfo.LastAccessTimeUtc); + } + + return new StorageItemProperties(); + } + + internal static DirectoryInfo? GetParentCore(FileSystemInfo fileSystemInfo) => fileSystemInfo switch + { + FileInfo { Directory: { } directory } => directory, + DirectoryInfo { Parent: { } parent } => parent, + _ => null + }; + + internal static FileSystemInfo? MoveCore(FileSystemInfo fileSystemInfo, IStorageFolder destination) + { + if (destination?.TryGetLocalPath() is { } destinationPath) + { + var newPath = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name); + if (fileSystemInfo is DirectoryInfo directoryInfo) + { + directoryInfo.MoveTo(newPath); + return new DirectoryInfo(newPath); + } + + if (fileSystemInfo is FileInfo fileInfo) + { + fileInfo.MoveTo(newPath); + return new FileInfo(newPath); + } + } + + return null; + } + + internal static FileStream OpenReadCore(FileInfo fileInfo) => fileInfo.OpenRead(); + + internal static FileStream OpenWriteCore(FileInfo fileInfo) => + new(fileInfo.FullName, FileMode.Create, FileAccess.Write, FileShare.Write); + + internal static IEnumerable<FileSystemInfo> GetItemsCore(DirectoryInfo directoryInfo) => directoryInfo + .EnumerateDirectories() + .OfType<FileSystemInfo>() + .Concat(directoryInfo.EnumerateFiles()); + + internal static FileInfo CreateFileCore(DirectoryInfo directoryInfo, string name) + { + var fileName = System.IO.Path.Combine(directoryInfo.FullName, name); + var newFile = new FileInfo(fileName); + + using var stream = newFile.Create(); + return newFile; + } + + internal static DirectoryInfo CreateFolderCore(DirectoryInfo directoryInfo, string name) => + directoryInfo.CreateSubdirectory(name); +} diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageProvider.cs b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageProvider.cs index 34409f5fdae..fd2f499d06f 100644 --- a/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageProvider.cs +++ b/src/Avalonia.Base/Platform/Storage/FileIO/BclStorageProvider.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; using System.Threading.Tasks; using Avalonia.Compatibility; +using Avalonia.Logging; namespace Avalonia.Platform.Storage.FileIO; @@ -20,18 +21,12 @@ internal abstract class BclStorageProvider : IStorageProvider public virtual Task<IStorageBookmarkFile?> OpenFileBookmarkAsync(string bookmark) { - var file = new FileInfo(bookmark); - return file.Exists - ? Task.FromResult<IStorageBookmarkFile?>(new BclStorageFile(file)) - : Task.FromResult<IStorageBookmarkFile?>(null); + return Task.FromResult(OpenBookmark(bookmark) as IStorageBookmarkFile); } public virtual Task<IStorageBookmarkFolder?> OpenFolderBookmarkAsync(string bookmark) { - var folder = new DirectoryInfo(bookmark); - return folder.Exists - ? Task.FromResult<IStorageBookmarkFolder?>(new BclStorageFolder(folder)) - : Task.FromResult<IStorageBookmarkFolder?>(null); + return Task.FromResult(OpenBookmark(bookmark) as IStorageBookmarkFolder); } public virtual Task<IStorageFile?> TryGetFileFromPathAsync(Uri filePath) @@ -63,6 +58,16 @@ internal abstract class BclStorageProvider : IStorageProvider } public virtual Task<IStorageFolder?> TryGetWellKnownFolderAsync(WellKnownFolder wellKnownFolder) + { + if (TryGetWellKnownFolderCore(wellKnownFolder) is { } directoryInfo) + { + return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directoryInfo)); + } + + return Task.FromResult<IStorageFolder?>(null); + } + + internal static DirectoryInfo? TryGetWellKnownFolderCore(WellKnownFolder wellKnownFolder) { // Note, this BCL API returns different values depending on the .NET version. // We should also document it. @@ -82,16 +87,16 @@ internal abstract class BclStorageProvider : IStorageProvider if (folderPath is null) { - return Task.FromResult<IStorageFolder?>(null); + return null; } var directory = new DirectoryInfo(folderPath); if (!directory.Exists) { - return Task.FromResult<IStorageFolder?>(null); + return null; } - - return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directory)); + + return directory; string GetFromSpecialFolder(Environment.SpecialFolder folder) => Environment.GetFolderPath(folder, Environment.SpecialFolderOption.Create); @@ -104,7 +109,7 @@ string GetFromSpecialFolder(Environment.SpecialFolder folder) => if (OperatingSystemEx.IsWindows()) { return Environment.OSVersion.Version.Major < 6 ? null : - SHGetKnownFolderPath(s_folderDownloads, 0, IntPtr.Zero); + Marshal.PtrToStringUni(SHGetKnownFolderPath(s_folderDownloads, 0, IntPtr.Zero)); } if (OperatingSystemEx.IsLinux()) @@ -123,8 +128,27 @@ string GetFromSpecialFolder(Environment.SpecialFolder folder) => return null; } - + + private IStorageBookmarkItem? OpenBookmark(string bookmark) + { + try + { + if (StorageBookmarkHelper.TryDecodeBclBookmark(bookmark, out var localPath)) + { + return StorageProviderHelpers.TryCreateBclStorageItem(localPath); + } + + return null; + } + catch (Exception ex) + { + Logger.TryGet(LogEventLevel.Information, LogArea.Platform)? + .Log(this, "Unable to read file bookmark: {Exception}", ex); + return null; + } + } + private static readonly Guid s_folderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B"); - [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)] - private static extern string SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid id, int flags, IntPtr token); + [DllImport("shell32.dll")] + private static extern IntPtr SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid id, int flags, IntPtr token); } diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/SecurityScopedStream.cs b/src/Avalonia.Base/Platform/Storage/FileIO/SecurityScopedStream.cs new file mode 100644 index 00000000000..0e0ffa3b1b3 --- /dev/null +++ b/src/Avalonia.Base/Platform/Storage/FileIO/SecurityScopedStream.cs @@ -0,0 +1,116 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Avalonia.Platform.Storage.FileIO; + +/// <summary> +/// Stream wrapper currently used by Apple platforms, +/// where in sandboxed scenario it's advised to call [NSUri startAccessingSecurityScopedResource]. +/// </summary> +internal sealed class SecurityScopedStream(FileStream _stream, IDisposable _securityScope) : Stream +{ + public override bool CanRead => _stream.CanRead; + + public override bool CanSeek => _stream.CanSeek; + + public override bool CanWrite => _stream.CanWrite; + + public override long Length => _stream.Length; + + public override long Position + { + get => _stream.Position; + set => _stream.Position = value; + } + + public override void Flush() => + _stream.Flush(); + + public override Task FlushAsync(CancellationToken cancellationToken) => + _stream.FlushAsync(cancellationToken); + + public override int ReadByte() => + _stream.ReadByte(); + + public override int Read(byte[] buffer, int offset, int count) => + _stream.Read(buffer, offset, count); + + public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + _stream.ReadAsync(buffer, offset, count, cancellationToken); + +#if NET6_0_OR_GREATER + public override int Read(Span<byte> buffer) => _stream.Read(buffer); + + public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) => + _stream.ReadAsync(buffer, cancellationToken); +#endif + + public override void Write(byte[] buffer, int offset, int count) => + _stream.Write(buffer, offset, count); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + _stream.WriteAsync(buffer, offset, count, cancellationToken); + +#if NET6_0_OR_GREATER + public override void Write(ReadOnlySpan<byte> buffer) => _stream.Write(buffer); + + public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => + _stream.WriteAsync(buffer, cancellationToken); +#endif + + public override void WriteByte(byte value) => _stream.WriteByte(value); + + public override long Seek(long offset, SeekOrigin origin) => + _stream.Seek(offset, origin); + + public override void SetLength(long value) => + _stream.SetLength(value); + +#if NET6_0_OR_GREATER + public override void CopyTo(Stream destination, int bufferSize) => _stream.CopyTo(destination, bufferSize); +#endif + + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => + _stream.CopyToAsync(destination, bufferSize, cancellationToken); + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => + _stream.BeginRead(buffer, offset, count, callback, state); + + public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult); + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => + _stream.BeginWrite(buffer, offset, count, callback, state); + + public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult); + + protected override void Dispose(bool disposing) + { + try + { + if (disposing) + { + _stream.Dispose(); + } + } + finally + { + _securityScope.Dispose(); + } + } + +#if NET6_0_OR_GREATER + public override async ValueTask DisposeAsync() + { + try + { + await _stream.DisposeAsync(); + } + finally + { + _securityScope.Dispose(); + } + } +#endif +} diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/StorageBookmarkHelper.cs b/src/Avalonia.Base/Platform/Storage/FileIO/StorageBookmarkHelper.cs new file mode 100644 index 00000000000..a71dd6f3e60 --- /dev/null +++ b/src/Avalonia.Base/Platform/Storage/FileIO/StorageBookmarkHelper.cs @@ -0,0 +1,153 @@ +using System; +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; + +namespace Avalonia.Platform.Storage.FileIO; + +/// <summary> +/// In order to have unique bookmarks across platforms, we prepend a platform specific suffix before native bookmark. +/// And always encoding them in base64 before returning to the user. +/// </summary> +/// <remarks> +/// Bookmarks are encoded as: +/// 0-6 - avalonia prefix with version number +/// 7-15 - platform key +/// 16+ - native bookmark value +/// Which is then encoded in Base64. +/// </remarks> +internal static class StorageBookmarkHelper +{ + private const int HeaderLength = 16; + private static ReadOnlySpan<byte> AvaHeaderPrefix => "ava.v1."u8; + private static ReadOnlySpan<byte> FakeBclBookmarkPlatform => "bcl"u8; + + [return: NotNullIfNotNull(nameof(nativeBookmark))] + public static string? EncodeBookmark(ReadOnlySpan<byte> platform, string? nativeBookmark) => + nativeBookmark is null ? null : EncodeBookmark(platform, Encoding.UTF8.GetBytes(nativeBookmark)); + + public static string? EncodeBookmark(ReadOnlySpan<byte> platform, ReadOnlySpan<byte> nativeBookmarkBytes) + { + if (nativeBookmarkBytes.Length == 0) + { + return null; + } + + if (platform.Length > HeaderLength) + { + throw new ArgumentException($"Platform name should not be longer than {HeaderLength} bytes", nameof(platform)); + } + + var arrayLength = HeaderLength + nativeBookmarkBytes.Length; + var arrayPool = ArrayPool<byte>.Shared.Rent(arrayLength); + try + { + // Write platform into first 16 bytes. + var arraySpan = arrayPool.AsSpan(0, arrayLength); + AvaHeaderPrefix.CopyTo(arraySpan); + platform.CopyTo(arraySpan.Slice(AvaHeaderPrefix.Length)); + + // Write bookmark bytes. + nativeBookmarkBytes.CopyTo(arraySpan.Slice(HeaderLength)); + + // We must use span overload because ArrayPool might return way too big array. +#if NET6_0_OR_GREATER + return Convert.ToBase64String(arraySpan); +#else + return Convert.ToBase64String(arraySpan.ToArray(), Base64FormattingOptions.None); +#endif + } + finally + { + ArrayPool<byte>.Shared.Return(arrayPool); + } + } + + public enum DecodeResult + { + Success = 0, + InvalidFormat, + InvalidPlatform + } + + public static DecodeResult TryDecodeBookmark(ReadOnlySpan<byte> platform, string? base64bookmark, out byte[]? nativeBookmark) + { + if (platform.Length > HeaderLength + || platform.Length == 0 + || base64bookmark is null + || base64bookmark.Length % 4 != 0) + { + nativeBookmark = null; + return DecodeResult.InvalidFormat; + } + + Span<byte> decodedBookmark; +#if NET6_0_OR_GREATER + // Each base64 character represents 6 bits, but to be safe, + var arrayPool = ArrayPool<byte>.Shared.Rent(HeaderLength + base64bookmark.Length * 6); + if (Convert.TryFromBase64Chars(base64bookmark, arrayPool, out int bytesWritten)) + { + decodedBookmark = arrayPool.AsSpan().Slice(0, bytesWritten); + } + else + { + nativeBookmark = null; + return DecodeResult.InvalidFormat; + } +#else + decodedBookmark = Convert.FromBase64String(base64bookmark).AsSpan(); +#endif + try + { + if (decodedBookmark.Length < HeaderLength + // Check if decoded string starts with the correct prefix, checking v1 at the same time. + && !AvaHeaderPrefix.SequenceEqual(decodedBookmark.Slice(0, AvaHeaderPrefix.Length))) + { + nativeBookmark = null; + return DecodeResult.InvalidFormat; + } + + var actualPlatform = decodedBookmark.Slice(AvaHeaderPrefix.Length, platform.Length); + if (!actualPlatform.SequenceEqual(platform)) + { + nativeBookmark = null; + return DecodeResult.InvalidPlatform; + } + + nativeBookmark = decodedBookmark.Slice(HeaderLength).ToArray(); + return DecodeResult.Success; + } + finally + { +#if NET6_0_OR_GREATER + ArrayPool<byte>.Shared.Return(arrayPool); +#endif + } + } + + public static string EncodeBclBookmark(string localPath) => EncodeBookmark(FakeBclBookmarkPlatform, localPath); + + public static bool TryDecodeBclBookmark(string nativeBookmark, [NotNullWhen(true)] out string? localPath) + { + var decodeResult = TryDecodeBookmark(FakeBclBookmarkPlatform, nativeBookmark, out var bytes); + if (decodeResult == DecodeResult.Success) + { + localPath = Encoding.UTF8.GetString(bytes!); + return true; + } + if (decodeResult == DecodeResult.InvalidFormat + && nativeBookmark.IndexOfAny(Path.GetInvalidPathChars()) < 0 + && !string.IsNullOrEmpty(Path.GetDirectoryName(nativeBookmark))) + { + // Attempt to restore old BCL bookmarks. + // Don't check for File.Exists here, as it will be done at later point in TryGetStorageItem. + // Just validate if it looks like a valid file path. + localPath = nativeBookmark; + return true; + } + + localPath = null; + return false; + } +} diff --git a/src/Avalonia.Base/Platform/Storage/FileIO/StorageProviderHelpers.cs b/src/Avalonia.Base/Platform/Storage/FileIO/StorageProviderHelpers.cs index 76323eb900e..48cc79672b8 100644 --- a/src/Avalonia.Base/Platform/Storage/FileIO/StorageProviderHelpers.cs +++ b/src/Avalonia.Base/Platform/Storage/FileIO/StorageProviderHelpers.cs @@ -8,7 +8,7 @@ namespace Avalonia.Platform.Storage.FileIO; internal static class StorageProviderHelpers { - public static IStorageItem? TryCreateBclStorageItem(string path) + public static BclStorageItem? TryCreateBclStorageItem(string path) { if (!string.IsNullOrWhiteSpace(path)) { @@ -28,28 +28,36 @@ internal static class StorageProviderHelpers return null; } - public static Uri FilePathToUri(string path) + public static string? TryGetPathFromFileUri(Uri? uri) + { + // android "content:", browser and ios relative links are ignored. + return uri is { IsAbsoluteUri: true, Scheme: "file" } ? uri.LocalPath : null; + } + + public static Uri UriFromFilePath(string path, bool isDirectory) { var uriPath = new StringBuilder(path) .Replace("%", $"%{(int)'%':X2}") .Replace("[", $"%{(int)'[':X2}") - .Replace("]", $"%{(int)']':X2}") - .ToString(); + .Replace("]", $"%{(int)']':X2}"); + + if (!path.EndsWith('/') && isDirectory) + { + uriPath.Append('/'); + } - return new UriBuilder("file", string.Empty) { Path = uriPath }.Uri; + return new UriBuilder("file", string.Empty) { Path = uriPath.ToString() }.Uri; } - - public static bool TryFilePathToUri(string path, [NotNullWhen(true)] out Uri? uri) + + public static Uri? TryGetUriFromFilePath(string path, bool isDirectory) { try { - uri = FilePathToUri(path); - return true; + return UriFromFilePath(path, isDirectory); } catch { - uri = null; - return false; + return null; } } diff --git a/src/Avalonia.Base/Platform/Storage/IStorageBookmarkItem.cs b/src/Avalonia.Base/Platform/Storage/IStorageBookmarkItem.cs index 40f2720ee8c..70c4f4bb0b3 100644 --- a/src/Avalonia.Base/Platform/Storage/IStorageBookmarkItem.cs +++ b/src/Avalonia.Base/Platform/Storage/IStorageBookmarkItem.cs @@ -1,8 +1,14 @@ -using System.Threading.Tasks; +using System.IO; +using System.Threading.Tasks; using Avalonia.Metadata; namespace Avalonia.Platform.Storage; +internal interface IStorageItemWithFileSystemInfo : IStorageItem +{ + FileSystemInfo FileSystemInfo { get; } +} + [NotClientImplementable] public interface IStorageBookmarkItem : IStorageItem { diff --git a/src/Avalonia.Base/Platform/Storage/StorageProviderExtensions.cs b/src/Avalonia.Base/Platform/Storage/StorageProviderExtensions.cs index 3933d23e4fb..8f0c890ed1f 100644 --- a/src/Avalonia.Base/Platform/Storage/StorageProviderExtensions.cs +++ b/src/Avalonia.Base/Platform/Storage/StorageProviderExtensions.cs @@ -17,7 +17,7 @@ public static class StorageProviderExtensions return Task.FromResult(StorageProviderHelpers.TryCreateBclStorageItem(filePath) as IStorageFile); } - if (StorageProviderHelpers.TryFilePathToUri(filePath, out var uri)) + if (StorageProviderHelpers.TryGetUriFromFilePath(filePath, false) is { } uri) { return provider.TryGetFileFromPathAsync(uri); } @@ -34,7 +34,7 @@ public static class StorageProviderExtensions return Task.FromResult(StorageProviderHelpers.TryCreateBclStorageItem(folderPath) as IStorageFolder); } - if (StorageProviderHelpers.TryFilePathToUri(folderPath, out var uri)) + if (StorageProviderHelpers.TryGetUriFromFilePath(folderPath, true) is { } uri) { return provider.TryGetFolderFromPathAsync(uri); } @@ -56,21 +56,11 @@ public static class StorageProviderExtensions { // We can avoid double escaping of the path by checking for BclStorageFolder. // Ideally, `folder.Path.LocalPath` should also work, as that's only available way for the users. - if (item is BclStorageFolder storageFolder) + if (item is IStorageItemWithFileSystemInfo storageItem) { - return storageFolder.DirectoryInfo.FullName; - } - if (item is BclStorageFile storageFile) - { - return storageFile.FileInfo.FullName; - } - - if (item.Path is { IsAbsoluteUri: true, Scheme: "file" } absolutePath) - { - return absolutePath.LocalPath; + return storageItem.FileSystemInfo.FullName; } - // android "content:", browser and ios relative links go here. - return null; + return StorageProviderHelpers.TryGetPathFromFileUri(item.Path); } } diff --git a/src/Avalonia.Diagnostics/Diagnostics/Conventions.cs b/src/Avalonia.Diagnostics/Diagnostics/Conventions.cs index 540f2b549da..691bf664ed1 100644 --- a/src/Avalonia.Diagnostics/Diagnostics/Conventions.cs +++ b/src/Avalonia.Diagnostics/Diagnostics/Conventions.cs @@ -1,21 +1,7 @@ -using System; -using System.IO; - -namespace Avalonia.Diagnostics +namespace Avalonia.Diagnostics { internal static class Conventions { - public static string DefaultScreenshotsRoot - { - get - { - var dir = System.IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Screenshots"); - Directory.CreateDirectory(dir); - return dir; - } - } - public static IScreenshotHandler DefaultScreenshotHandler { get; } = new Screenshots.FilePickerHandler(); } diff --git a/src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs b/src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs index 6ea46b6d54b..65998091e7f 100644 --- a/src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs +++ b/src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs @@ -15,7 +15,7 @@ namespace Avalonia.Diagnostics.Screenshots public sealed class FilePickerHandler : BaseRenderToStreamHandler { private readonly string _title; - private readonly string _screenshotRoot; + private readonly string? _screenshotRoot; /// <summary> /// Instance FilePickerHandler @@ -35,7 +35,7 @@ public FilePickerHandler( string? screenshotRoot = default) { _title = title ?? "Save Screenshot to ..."; - _screenshotRoot = screenshotRoot ?? Conventions.DefaultScreenshotsRoot; + _screenshotRoot = screenshotRoot; } private static TopLevel GetTopLevel(Control control) @@ -54,8 +54,15 @@ private static TopLevel GetTopLevel(Control control) protected override async Task<Stream?> GetStream(Control control) { var storageProvider = GetTopLevel(control).StorageProvider; - var defaultFolder = await storageProvider.TryGetFolderFromPathAsync(_screenshotRoot) - ?? await storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Pictures); + IStorageFolder? defaultFolder = null; + if (_screenshotRoot is not null) + { + defaultFolder = await storageProvider.TryGetFolderFromPathAsync(_screenshotRoot); + } + if (defaultFolder is null) + { + defaultFolder = await storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Pictures); + } var result = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { diff --git a/src/Avalonia.Native/AvaloniaNativeApplicationPlatform.cs b/src/Avalonia.Native/AvaloniaNativeApplicationPlatform.cs index 0a735f8f9ee..109a43c1ae5 100644 --- a/src/Avalonia.Native/AvaloniaNativeApplicationPlatform.cs +++ b/src/Avalonia.Native/AvaloniaNativeApplicationPlatform.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Controls.Platform; using Avalonia.Native.Interop; using Avalonia.Platform; using Avalonia.Platform.Storage; @@ -17,13 +18,15 @@ void IAvnApplicationEvents.FilesOpened(IAvnStringArray urls) { ((IApplicationPlatformEvents)Application.Current)?.RaiseUrlsOpened(urls.ToStringArray()); - if (AvaloniaLocator.Current.GetService<IActivatableLifetime>() is ActivatableLifetimeBase lifetime) + if (AvaloniaLocator.Current.GetService<IActivatableLifetime>() is ActivatableLifetimeBase lifetime + && AvaloniaLocator.Current.GetService<IStorageProviderFactory>() is StorageProviderApi storageApi) { var filePaths = urls.ToStringArray(); var files = new List<IStorageItem>(filePaths.Length); foreach (var filePath in filePaths) { - if (StorageProviderHelpers.TryCreateBclStorageItem(filePath) is { } file) + if (StorageProviderHelpers.TryGetUriFromFilePath(filePath, false) is { } fileUri + && storageApi.TryGetStorageItem(fileUri) is { } file) { files.Add(file); } @@ -41,7 +44,8 @@ void IAvnApplicationEvents.UrlsOpened(IAvnStringArray urls) // Raise the urls opened event to be compatible with legacy behavior. ((IApplicationPlatformEvents)Application.Current)?.RaiseUrlsOpened(urls.ToStringArray()); - if (AvaloniaLocator.Current.GetService<IActivatableLifetime>() is ActivatableLifetimeBase lifetime) + if (AvaloniaLocator.Current.GetService<IActivatableLifetime>() is ActivatableLifetimeBase lifetime + && AvaloniaLocator.Current.GetService<IStorageProviderFactory>() is StorageProviderApi storageApi) { var files = new List<IStorageItem>(); var uris = new List<Uri>(); @@ -51,7 +55,7 @@ void IAvnApplicationEvents.UrlsOpened(IAvnStringArray urls) { if (uri.Scheme == Uri.UriSchemeFile) { - if (StorageProviderHelpers.TryCreateBclStorageItem(uri.LocalPath) is { } file) + if (storageApi.TryGetStorageItem(uri) is { } file) { files.Add(file); } diff --git a/src/Avalonia.Native/AvaloniaNativePlatform.cs b/src/Avalonia.Native/AvaloniaNativePlatform.cs index f8696d3a1c1..00b57350cde 100644 --- a/src/Avalonia.Native/AvaloniaNativePlatform.cs +++ b/src/Avalonia.Native/AvaloniaNativePlatform.cs @@ -107,8 +107,7 @@ void DoInitialize(AvaloniaNativePlatformOptions options) } AvaloniaLocator.CurrentMutable - .Bind<IDispatcherImpl>() - .ToConstant(new DispatcherImpl(_factory.CreatePlatformThreadingInterface())) + .Bind<IDispatcherImpl>().ToConstant(new DispatcherImpl(_factory.CreatePlatformThreadingInterface())) .Bind<ICursorFactory>().ToConstant(new CursorFactory(_factory.CreateCursorFactory())) .Bind<IScreenImpl>().ToConstant(new ScreenImpl(_factory.CreateScreens)) .Bind<IPlatformIconLoader>().ToSingleton<IconLoader>() @@ -121,7 +120,8 @@ void DoInitialize(AvaloniaNativePlatformOptions options) .Bind<IPlatformDragSource>().ToConstant(new AvaloniaNativeDragSource(_factory)) .Bind<IPlatformLifetimeEventsImpl>().ToConstant(applicationPlatform) .Bind<INativeApplicationCommands>().ToConstant(new MacOSNativeMenuCommands(_factory.CreateApplicationCommands())) - .Bind<IActivatableLifetime>().ToSingleton<MacOSActivatableLifetime>(); + .Bind<IActivatableLifetime>().ToSingleton<MacOSActivatableLifetime>() + .Bind<IStorageProviderFactory>().ToConstant(new StorageProviderApi(_factory.CreateStorageProvider(), options.AppSandboxEnabled)); var hotkeys = new PlatformHotkeyConfiguration(KeyModifiers.Meta, wholeWordTextActionModifiers: KeyModifiers.Alt); hotkeys.MoveCursorToTheStartOfLine.Add(new KeyGesture(Key.Left, hotkeys.CommandModifiers)); diff --git a/src/Avalonia.Native/AvaloniaNativePlatformExtensions.cs b/src/Avalonia.Native/AvaloniaNativePlatformExtensions.cs index 67da919a01c..f8974865a7d 100644 --- a/src/Avalonia.Native/AvaloniaNativePlatformExtensions.cs +++ b/src/Avalonia.Native/AvaloniaNativePlatformExtensions.cs @@ -80,6 +80,13 @@ public class AvaloniaNativePlatformOptions /// and make your Avalonia app run with it. The default value is null. /// </summary> public string AvaloniaNativeLibraryPath { get; set; } + + /// <summary> + /// If you distribute your app in App Store - it should be with sandbox enabled. + /// This parameter enables <see cref="Avalonia.Platform.Storage.IStorageItem.SaveBookmarkAsync"/> and related APIs, + /// as well as wrapping all storage related calls in secure context. The default value is true. + /// </summary> + public bool AppSandboxEnabled { get; set; } = true; } // ReSharper disable once InconsistentNaming diff --git a/src/Avalonia.Native/ClipboardImpl.cs b/src/Avalonia.Native/ClipboardImpl.cs index 5b9c3acaaf5..0fc4d762242 100644 --- a/src/Avalonia.Native/ClipboardImpl.cs +++ b/src/Avalonia.Native/ClipboardImpl.cs @@ -2,18 +2,21 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Logging; using Avalonia.Native.Interop; using Avalonia.Platform.Storage; using Avalonia.Platform.Storage.FileIO; +using MicroCom.Runtime; namespace Avalonia.Native { class ClipboardImpl : IClipboard, IDisposable { private IAvnClipboard _native; + // TODO hide native types behind IAvnClipboard abstraction, so managed side won't depend on macOS. private const string NSPasteboardTypeString = "public.utf8-plain-text"; private const string NSFilenamesPboardType = "NSFilenamesPboardType"; @@ -86,7 +89,13 @@ public IEnumerable<string> GetFileNames() public IEnumerable<IStorageItem> GetFiles() { - return GetFileNames()?.Select(f => StorageProviderHelpers.TryCreateBclStorageItem(f)!) + var storageApi = (StorageProviderApi)AvaloniaLocator.Current.GetRequiredService<IStorageProviderFactory>(); + + // TODO: use non-deprecated AppKit API to get NSUri instead of file names. + return GetFileNames()? + .Select(f => StorageProviderHelpers.TryGetUriFromFilePath(f, false) is { } uri + ? storageApi.TryGetStorageItem(uri) + : null) .Where(f => f is not null); } diff --git a/src/Avalonia.Native/StorageItem.cs b/src/Avalonia.Native/StorageItem.cs new file mode 100644 index 00000000000..12e4cc0a5e4 --- /dev/null +++ b/src/Avalonia.Native/StorageItem.cs @@ -0,0 +1,152 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading.Tasks; +using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; +using Avalonia.Utilities; + +namespace Avalonia.Native; + +internal class StorageItem : IStorageBookmarkItem, IStorageItemWithFileSystemInfo +{ + private readonly StorageProviderApi _storageProviderApi; + private readonly FileSystemInfo _fileSystemInfo; + + protected StorageItem(StorageProviderApi storageProviderApi, FileSystemInfo fileSystemInfo, Uri uri, Uri scopeOwnerUri) + { + _storageProviderApi = storageProviderApi; + Path = uri; + _fileSystemInfo = fileSystemInfo; + ScopeOwnerUri = scopeOwnerUri; + } + + public string Name => _fileSystemInfo.Name; + public Uri Path { get; } + public Uri ScopeOwnerUri { get; } + + public Task<StorageItemProperties> GetBasicPropertiesAsync() + { + using var scope = OpenScope(); + return Task.FromResult( + BclStorageItem.GetBasicPropertiesAsyncCore(_fileSystemInfo)); + } + + public bool CanBookmark => true; + public FileSystemInfo FileSystemInfo => _fileSystemInfo; + + protected IDisposable? OpenScope() + { + return _storageProviderApi.OpenSecurityScope(ScopeOwnerUri.AbsoluteUri); + } + + public Task<string?> SaveBookmarkAsync() + { + using var scope = OpenScope(); + return Task.FromResult(_storageProviderApi.SaveBookmark(Path)); + } + + public Task ReleaseBookmarkAsync() + { + _storageProviderApi.ReleaseBookmark(Path); + return Task.CompletedTask; + } + + public Task<IStorageFolder?> GetParentAsync() + { + using var scope = OpenScope(); + var parent = BclStorageItem.GetParentCore(_fileSystemInfo); + return Task.FromResult((IStorageFolder?)WrapFileSystemInfo(parent, null)); + } + + public Task DeleteAsync() + { + using var scope = OpenScope(); + BclStorageItem.DeleteCore(_fileSystemInfo); + return Task.CompletedTask; + } + + public Task<IStorageItem?> MoveAsync(IStorageFolder destination) + { + using var destinationScope = (destination as StorageItem)?.OpenScope(); + using var scope = OpenScope(); + var item = WrapFileSystemInfo(BclStorageItem.MoveCore(_fileSystemInfo, destination), null); + return Task.FromResult(item); + } + + [return: NotNullIfNotNull(nameof(fileSystemInfo))] + protected IStorageItem? WrapFileSystemInfo(FileSystemInfo? fileSystemInfo, Uri? scopedOwner) + { + if (fileSystemInfo is null) return null; + + // It might not be always correct to assume NSUri from the file path, but that's the best we have here without using native API directly. + var fileUri = BclStorageItem.GetPathCore(fileSystemInfo); + return fileSystemInfo switch + { + DirectoryInfo directoryInfo => new StorageFolder( + _storageProviderApi, directoryInfo, fileUri, scopedOwner ?? fileUri), + FileInfo fileInfo => new StorageFile( + _storageProviderApi, fileInfo, fileUri, scopedOwner ?? fileUri), + _ => throw new ArgumentOutOfRangeException(nameof(fileSystemInfo), fileSystemInfo, null) + }; + } + + public void Dispose() + { + } +} + +internal class StorageFile( + StorageProviderApi storageProviderApi, FileInfo fileInfo, Uri uri, Uri scopeOwnerUri) + : StorageItem(storageProviderApi, fileInfo, uri, scopeOwnerUri), IStorageBookmarkFile +{ + public Task<Stream> OpenReadAsync() + { + var scope = OpenScope(); + var innerStream = BclStorageItem.OpenReadCore(fileInfo); + return Task.FromResult<Stream>(scope is not null ? new SecurityScopedStream(innerStream, scope) : innerStream); + } + + public Task<Stream> OpenWriteAsync() + { + var scope = OpenScope(); + var innerStream = BclStorageItem.OpenWriteCore(fileInfo); + return Task.FromResult<Stream>(scope is not null ? new SecurityScopedStream(innerStream, scope) : innerStream); + } +} + +internal class StorageFolder( + StorageProviderApi storageProviderApi, DirectoryInfo directoryInfo, Uri uri, Uri scopeOwnerUri) + : StorageItem(storageProviderApi, directoryInfo, uri, scopeOwnerUri), IStorageBookmarkFolder +{ + public IAsyncEnumerable<IStorageItem> GetItemsAsync() + { + return GetItems().AsAsyncEnumerable(); + + IEnumerable<IStorageItem> GetItems() + { + using var scope = OpenScope(); + foreach (var item in BclStorageItem.GetItemsCore(directoryInfo)) + { + yield return WrapFileSystemInfo(item, ScopeOwnerUri); + } + } + } + + public Task<IStorageFile?> CreateFileAsync(string name) + { + using var scope = OpenScope(); + var file = BclStorageItem.CreateFileCore(directoryInfo, name); + return Task.FromResult((IStorageFile?)WrapFileSystemInfo(file, ScopeOwnerUri)); + } + + public Task<IStorageFolder?> CreateFolderAsync(string name) + { + using var scope = OpenScope(); + var folder = BclStorageItem.CreateFolderCore(directoryInfo, name); + return Task.FromResult((IStorageFolder?)WrapFileSystemInfo(folder, ScopeOwnerUri)); + } +} diff --git a/src/Avalonia.Native/StorageProviderApi.cs b/src/Avalonia.Native/StorageProviderApi.cs new file mode 100644 index 00000000000..4d326ee8c34 --- /dev/null +++ b/src/Avalonia.Native/StorageProviderApi.cs @@ -0,0 +1,289 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Controls.Platform; +using Avalonia.Logging; +using Avalonia.Native.Interop; +using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; +using Avalonia.Reactive; +using MicroCom.Runtime; + +namespace Avalonia.Native; + +internal class StorageProviderApi(IAvnStorageProvider native, bool sandboxEnabled) : IStorageProviderFactory, IDisposable +{ + private readonly Dictionary<string, int> _openScopes = new(); + private readonly IAvnStorageProvider _native = native; + + public IStorageProvider CreateProvider(TopLevel topLevel) + { + return new StorageProviderImpl((TopLevelImpl)topLevel.PlatformImpl!, this); + } + + public IStorageItem? TryGetStorageItem(Uri? itemUri, bool create = false) + { + if (itemUri is not null && StorageProviderHelpers.TryGetPathFromFileUri(itemUri) is { } itemPath) + { + if (new FileInfo(itemPath) is { } fileInfo + && (create || fileInfo.Exists)) + { + return sandboxEnabled + ? new StorageFile(this, fileInfo, itemUri, itemUri) + : new BclStorageFile(fileInfo); + } + if (new DirectoryInfo(itemPath) is { } directoryInfo + && (create || directoryInfo.Exists)) + { + return sandboxEnabled + ? new StorageFolder(this, directoryInfo, itemUri, itemUri) + : new BclStorageFolder(directoryInfo); + } + } + + return null; + } + + public IDisposable? OpenSecurityScope(string uriString) + { + // Multiple entries are possible. + // For example, user might open OpenRead stream, and read file properties before closing the file. + // If we don't check for nested scopes, inner closing scope will break access of the outer scope. + if (AddUse(this, uriString) == 1) + { + using var nsUriString = new AvnString(uriString); + var scopeOpened = _native.OpenSecurityScope(nsUriString).FromComBool(); + if (!scopeOpened) + { + RemoveUse(this, uriString); + Logger.TryGet(LogEventLevel.Information, LogArea.macOSPlatform)? + .Log(this, "OpenSecurityScope returned false for the {Uri}", uriString); + return null; + } + } + + return Disposable.Create((api: this, uriString), static state => + { + if (RemoveUse(state.api, state.uriString) == 0) + { + using var nsUriString = new AvnString(state.uriString); + state.api._native.CloseSecurityScope(nsUriString); + } + }); + + static int AddUse(StorageProviderApi api, string uriString) + { + lock (api) + { + api._openScopes.TryGetValue(uriString, out var useValue); + api._openScopes[uriString] = ++useValue; + return useValue; + } + } + static int RemoveUse(StorageProviderApi api, string uriString) + { + lock (api) + { + api._openScopes.TryGetValue(uriString, out var useValue); + useValue--; + if (useValue == 0) + api._openScopes.Remove(uriString); + else + api._openScopes[uriString] = useValue; + return useValue; + } + } + } + + // Avalonia.Native technically can be used for more than just macOS, + // In which case we should provide different bookmark platform keys, and parse accordingly. + private static ReadOnlySpan<byte> MacOSKey => "macOS"u8; + public unsafe string? SaveBookmark(Uri uri) + { + void* error = null; + using var uriString = new AvnString(uri.AbsoluteUri); + using var bookmarkStr = _native.SaveBookmarkToBytes(uriString, &error); + + if (error != null) + { + using var errorStr = MicroComRuntime.CreateProxyOrNullFor<IAvnString>(error, true); + Logger.TryGet(LogEventLevel.Warning, LogArea.macOSPlatform)? + .Log(this, "SaveBookmark for {Uri} failed with an error\r\n{Error}", uri, errorStr.String); + return null; + } + + return StorageBookmarkHelper.EncodeBookmark(MacOSKey, bookmarkStr?.Bytes); + } + + // Support both kinds of bookmarks when reading. + // Since "save bookmark" implementation will be different depending on the configuration. + public unsafe Uri? ReadBookmark(string bookmark, bool isDirectory) + { + if (StorageBookmarkHelper.TryDecodeBookmark(MacOSKey, bookmark, out var bytes) == StorageBookmarkHelper.DecodeResult.Success) + { + fixed (byte* ptr = bytes) + { + using var uriString = _native.ReadBookmarkFromBytes(ptr, bytes.Length); + return uriString is not null && Uri.TryCreate(uriString.String, UriKind.Absolute, out var uri) ? + uri : + null; + } + } + if (StorageBookmarkHelper.TryDecodeBclBookmark(bookmark, out var path)) + { + return StorageProviderHelpers.UriFromFilePath(path, isDirectory); + } + + return null; + } + + public void ReleaseBookmark(Uri uri) + { + using var uriString = new AvnString(uri.AbsoluteUri); + _native.ReleaseBookmark(uriString); + } + + public void Dispose() + { + _native.Dispose(); + } + + public async Task<IReadOnlyList<IStorageFile>> OpenFileDialog(TopLevelImpl? topLevel, FilePickerOpenOptions options) + { + using var fileTypes = new FilePickerFileTypesWrapper(options.FileTypeFilter, null); + var suggestedDirectory = options.SuggestedStartLocation?.Path.AbsoluteUri ?? string.Empty; + + var results = await OpenDialogAsync(events => + { + _native.OpenFileDialog((IAvnWindow?)topLevel?.Native, + events, + options.AllowMultiple.AsComBool(), + options.Title ?? string.Empty, + suggestedDirectory, + options.SuggestedFileName ?? string.Empty, + fileTypes); + }); + + return results.OfType<IStorageFile>().ToArray(); + } + + public async Task<IStorageFile?> SaveFileDialog(TopLevelImpl? topLevel, FilePickerSaveOptions options) + { + using var fileTypes = new FilePickerFileTypesWrapper(options.FileTypeChoices, options.DefaultExtension); + var suggestedDirectory = options.SuggestedStartLocation?.Path.AbsoluteUri ?? string.Empty; + + var results = await OpenDialogAsync(events => + { + _native.SaveFileDialog((IAvnWindow?)topLevel?.Native, + events, + options.Title ?? string.Empty, + suggestedDirectory, + options.SuggestedFileName ?? string.Empty, + fileTypes); + }, create: true); + + return results.OfType<IStorageFile>().FirstOrDefault(); + } + + public async Task<IReadOnlyList<IStorageFolder>> SelectFolderDialog(TopLevelImpl? topLevel, FolderPickerOpenOptions options) + { + var suggestedDirectory = options.SuggestedStartLocation?.Path.AbsoluteUri ?? string.Empty; + + var results = await OpenDialogAsync(events => + { + _native.SelectFolderDialog((IAvnWindow?)topLevel?.Native, + events, + options.AllowMultiple.AsComBool(), + options.Title ?? "", + suggestedDirectory); + }); + + return results.OfType<IStorageFolder>().ToArray(); + } + + public async Task<IEnumerable<IStorageItem>> OpenDialogAsync(Action<SystemDialogEvents> runDialog, bool create = false) + { + using var events = new SystemDialogEvents(); + runDialog(events); + var result = await events.Task.ConfigureAwait(false); + return (result? + .Select(f => Uri.TryCreate(f, UriKind.Absolute, out var uri) ? TryGetStorageItem(uri, create) : null) + .Where(f => f is not null) ?? [])!; + } + + internal class FilePickerFileTypesWrapper( + IReadOnlyList<FilePickerFileType>? types, + string? defaultExtension) + : NativeCallbackBase, IAvnFilePickerFileTypes + { + private readonly List<IDisposable> _disposables = new(); + + public int Count => types?.Count ?? 0; + + public int IsDefaultType(int index) => (defaultExtension is not null && + types![index].TryGetExtensions()?.Any(defaultExtension.EndsWith) == true).AsComBool(); + + public int IsAnyType(int index) => + (types![index].Patterns?.Contains("*.*") == true || types[index].MimeTypes?.Contains("*.*") == true) + .AsComBool(); + + public IAvnString GetName(int index) + { + return EnsureDisposable(types![index].Name.ToAvnString()); + } + + public IAvnStringArray GetPatterns(int index) + { + return EnsureDisposable(new AvnStringArray(types![index].Patterns ?? Array.Empty<string>())); + } + + public IAvnStringArray GetExtensions(int index) + { + return EnsureDisposable(new AvnStringArray(types![index].TryGetExtensions() ?? Array.Empty<string>())); + } + + public IAvnStringArray GetMimeTypes(int index) + { + return EnsureDisposable(new AvnStringArray(types![index].MimeTypes ?? Array.Empty<string>())); + } + + public IAvnStringArray GetAppleUniformTypeIdentifiers(int index) + { + return EnsureDisposable(new AvnStringArray(types![index].AppleUniformTypeIdentifiers ?? Array.Empty<string>())); + } + + protected override void Destroyed() + { + foreach (var disposable in _disposables) + { + disposable.Dispose(); + } + } + + private T EnsureDisposable<T>(T input) where T : IDisposable + { + _disposables.Add(input); + return input; + } + } + + internal class SystemDialogEvents : NativeCallbackBase, IAvnSystemDialogEvents + { + private readonly TaskCompletionSource<string[]> _tcs = new(); + + public Task<string[]> Task => _tcs.Task; + + public void OnCompleted(IAvnStringArray? ppv) + { + using (ppv) + { + _tcs.SetResult(ppv?.ToStringArray() ?? []); + } + } + } +} diff --git a/src/Avalonia.Native/StorageProviderImpl.cs b/src/Avalonia.Native/StorageProviderImpl.cs new file mode 100644 index 00000000000..2773eddf24f --- /dev/null +++ b/src/Avalonia.Native/StorageProviderImpl.cs @@ -0,0 +1,63 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; + +namespace Avalonia.Native; + +internal sealed class StorageProviderImpl(TopLevelImpl topLevel, StorageProviderApi native) : IStorageProvider +{ + public bool CanOpen => true; + + public bool CanSave => true; + + public bool CanPickFolder => true; + + public Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options) + { + return native.OpenFileDialog(topLevel, options); + } + + public Task<IStorageFile?> SaveFilePickerAsync(FilePickerSaveOptions options) + { + return native.SaveFileDialog(topLevel, options); + } + + public Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPickerOpenOptions options) + { + return native.SelectFolderDialog(topLevel, options); + } + + public Task<IStorageBookmarkFile?> OpenFileBookmarkAsync(string bookmark) + { + return Task.FromResult(native.TryGetStorageItem(native.ReadBookmark(bookmark, false)) as IStorageBookmarkFile); + } + + public Task<IStorageBookmarkFolder?> OpenFolderBookmarkAsync(string bookmark) + { + return Task.FromResult(native.TryGetStorageItem(native.ReadBookmark(bookmark, true)) as IStorageBookmarkFolder); + } + + public Task<IStorageFile?> TryGetFileFromPathAsync(Uri fileUri) + { + return Task.FromResult(native.TryGetStorageItem(fileUri) as IStorageFile); + } + + public Task<IStorageFolder?> TryGetFolderFromPathAsync(Uri folderPath) + { + return Task.FromResult(native.TryGetStorageItem(folderPath) as IStorageFolder); + } + + public Task<IStorageFolder?> TryGetWellKnownFolderAsync(WellKnownFolder wellKnownFolder) + { + if (BclStorageProvider.TryGetWellKnownFolderCore(wellKnownFolder) is { } directoryInfo) + { + return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directoryInfo)); + } + + return Task.FromResult<IStorageFolder?>(null); + } +} diff --git a/src/Avalonia.Native/SystemDialogs.cs b/src/Avalonia.Native/SystemDialogs.cs deleted file mode 100644 index bf898178814..00000000000 --- a/src/Avalonia.Native/SystemDialogs.cs +++ /dev/null @@ -1,181 +0,0 @@ -#nullable enable - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using Avalonia.Native.Interop; -using Avalonia.Platform.Storage; -using Avalonia.Platform.Storage.FileIO; - -namespace Avalonia.Native -{ - internal class SystemDialogs : BclStorageProvider - { - private readonly TopLevelImpl _topLevel; - private readonly IAvnSystemDialogs _native; - - public SystemDialogs(TopLevelImpl topLevel, IAvnSystemDialogs native) - { - _topLevel = topLevel; - _native = native; - } - - public override bool CanOpen => true; - - public override bool CanSave => true; - - public override bool CanPickFolder => true; - - public override async Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options) - { - using var events = new SystemDialogEvents(); - using var fileTypes = new FilePickerFileTypesWrapper(options.FileTypeFilter, null); - - var suggestedDirectory = options.SuggestedStartLocation?.TryGetLocalPath() ?? string.Empty; - - _native.OpenFileDialog((IAvnWindow)_topLevel.Native, - events, - options.AllowMultiple.AsComBool(), - options.Title ?? string.Empty, - suggestedDirectory, - options.SuggestedFileName ?? string.Empty, - fileTypes); - - var result = await events.Task.ConfigureAwait(false); - - return result?.Select(f => new BclStorageFile(new FileInfo(f))).ToArray() - ?? Array.Empty<IStorageFile>(); - } - - public override async Task<IStorageFile?> SaveFilePickerAsync(FilePickerSaveOptions options) - { - using var events = new SystemDialogEvents(); - using var fileTypes = new FilePickerFileTypesWrapper(options.FileTypeChoices, options.DefaultExtension); - - var suggestedDirectory = options.SuggestedStartLocation?.TryGetLocalPath() ?? string.Empty; - - _native.SaveFileDialog((IAvnWindow)_topLevel.Native, - events, - options.Title ?? string.Empty, - suggestedDirectory, - options.SuggestedFileName ?? string.Empty, - fileTypes); - - var result = await events.Task.ConfigureAwait(false); - return result.FirstOrDefault() is string file - ? new BclStorageFile(new FileInfo(file)) - : null; - } - - public override async Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPickerOpenOptions options) - { - using var events = new SystemDialogEvents(); - - var suggestedDirectory = options.SuggestedStartLocation?.TryGetLocalPath() ?? string.Empty; - - _native.SelectFolderDialog((IAvnWindow)_topLevel.Native, events, options.AllowMultiple.AsComBool(), options.Title ?? "", suggestedDirectory); - - var result = await events.Task.ConfigureAwait(false); - return result?.Select(f => new BclStorageFolder(new DirectoryInfo(f))).ToArray() - ?? Array.Empty<IStorageFolder>(); - } - } - - internal class FilePickerFileTypesWrapper : NativeCallbackBase, IAvnFilePickerFileTypes - { - private readonly IReadOnlyList<FilePickerFileType>? _types; - private readonly string? _defaultExtension; - private readonly List<IDisposable> _disposables; - - public FilePickerFileTypesWrapper( - IReadOnlyList<FilePickerFileType>? types, - string? defaultExtension) - { - _types = types; - _defaultExtension = defaultExtension; - _disposables = new List<IDisposable>(); - } - - public int Count => _types?.Count ?? 0; - - public int IsDefaultType(int index) => (_defaultExtension is not null && - _types![index].TryGetExtensions()?.Any(ext => _defaultExtension.EndsWith(ext)) == true).AsComBool(); - - public int IsAnyType(int index) => - (_types![index].Patterns?.Contains("*.*") == true || _types[index].MimeTypes?.Contains("*.*") == true) - .AsComBool(); - - public IAvnString GetName(int index) - { - return EnsureDisposable(_types![index].Name.ToAvnString()); - } - - public IAvnStringArray GetPatterns(int index) - { - return EnsureDisposable(new AvnStringArray(_types![index].Patterns ?? Array.Empty<string>())); - } - - public IAvnStringArray GetExtensions(int index) - { - return EnsureDisposable(new AvnStringArray(_types![index].TryGetExtensions() ?? Array.Empty<string>())); - } - - public IAvnStringArray GetMimeTypes(int index) - { - return EnsureDisposable(new AvnStringArray(_types![index].MimeTypes ?? Array.Empty<string>())); - } - - public IAvnStringArray GetAppleUniformTypeIdentifiers(int index) - { - return EnsureDisposable(new AvnStringArray(_types![index].AppleUniformTypeIdentifiers ?? Array.Empty<string>())); - } - - protected override void Destroyed() - { - foreach (var disposable in _disposables) - { - disposable.Dispose(); - } - } - - private T EnsureDisposable<T>(T input) where T : IDisposable - { - _disposables.Add(input); - return input; - } - } - - internal unsafe class SystemDialogEvents : NativeCallbackBase, IAvnSystemDialogEvents - { - private readonly TaskCompletionSource<string[]> _tcs; - - public SystemDialogEvents() - { - _tcs = new TaskCompletionSource<string[]>(); - } - - public Task<string[]> Task => _tcs.Task; - - public void OnCompleted(int numResults, void* trFirstResultRef) - { - string[] results = new string[numResults]; - - unsafe - { - var ptr = (IntPtr*)trFirstResultRef; - - for (int i = 0; i < numResults; i++) - { - results[i] = Marshal.PtrToStringAnsi(*ptr) ?? string.Empty; - - ptr++; - } - } - - _tcs.SetResult(results); - } - } -} diff --git a/src/Avalonia.Native/TopLevelImpl.cs b/src/Avalonia.Native/TopLevelImpl.cs index c7d3305efdf..8c65a3bd760 100644 --- a/src/Avalonia.Native/TopLevelImpl.cs +++ b/src/Avalonia.Native/TopLevelImpl.cs @@ -65,7 +65,6 @@ internal class TopLevelImpl : ITopLevelImpl, IFramebufferPlatformSurface { protected IInputRoot? _inputRoot; private NativeControlHostImpl? _nativeControlHost; - private IStorageProvider? _storageProvider; private PlatformBehaviorInhibition? _platformBehaviorInhibition; private readonly MouseDevice? _mouse; @@ -98,7 +97,6 @@ internal virtual void Init(MacOSTopLevelHandle handle) _savedLogicalSize = ClientSize; _savedScaling = RenderScaling; _nativeControlHost = new NativeControlHostImpl(Native!.CreateNativeControlHost()); - _storageProvider = new SystemDialogs(this, Factory.CreateSystemDialogs()); _platformBehaviorInhibition = new PlatformBehaviorInhibition(Factory.CreatePlatformBehaviorInhibition()); _surfaces = new object[] { new GlPlatformSurface(Native), new MetalPlatformSurface(Native), this }; InputMethod = new AvaloniaNativeTextInputMethod(Native); @@ -338,11 +336,6 @@ public void SetTransparencyLevelHint(IReadOnlyList<WindowTransparencyLevel> tran return _nativeControlHost; } - if (featureType == typeof(IStorageProvider)) - { - return _storageProvider; - } - if (featureType == typeof(IPlatformBehaviorInhibition)) { return _platformBehaviorInhibition; diff --git a/src/Avalonia.Native/avn.idl b/src/Avalonia.Native/avn.idl index 7e9d7f0b96c..902c477a9be 100644 --- a/src/Avalonia.Native/avn.idl +++ b/src/Avalonia.Native/avn.idl @@ -677,6 +677,7 @@ interface IAvaloniaNativeFactory : IUnknown HRESULT CreateWindow(IAvnWindowEvents* cb, IAvnWindow** ppv); HRESULT CreatePopup(IAvnWindowEvents* cb, IAvnPopup** ppv); HRESULT CreatePlatformThreadingInterface(IAvnPlatformThreadingInterface** ppv); + HRESULT CreateStorageProvider(IAvnStorageProvider** ppv); HRESULT CreateSystemDialogs(IAvnSystemDialogs** ppv); HRESULT CreateScreens(IAvnScreenEvents* cb, IAvnScreens** ppv); HRESULT CreateClipboard(IAvnClipboard** ppv); @@ -888,18 +889,18 @@ interface IAvnPlatformThreadingInterface : IUnknown [uuid(6c621a6e-e4c1-4ae3-9749-83eeeffa09b6)] interface IAvnSystemDialogEvents : IUnknown { - void OnCompleted(int numResults, void* ptrFirstResult); + void OnCompleted(IAvnStringArray*array); } [uuid(4d7a47db-a944-4061-abe7-62cb6aa0ffd5)] -interface IAvnSystemDialogs : IUnknown +interface IAvnStorageProvider : IUnknown { void SelectFolderDialog(IAvnWindow* parentWindowHandle, IAvnSystemDialogEvents* events, bool allowMultiple, [const] char* title, [const] char* initialPath); - + void OpenFileDialog(IAvnWindow* parentWindowHandle, IAvnSystemDialogEvents* events, bool allowMultiple, @@ -907,13 +908,21 @@ interface IAvnSystemDialogs : IUnknown [const] char* initialDirectory, [const] char* initialFile, IAvnFilePickerFileTypes* filters); - + void SaveFileDialog(IAvnWindow* parentWindowHandle, IAvnSystemDialogEvents* events, [const] char* title, [const] char* initialDirectory, [const] char* initialFile, IAvnFilePickerFileTypes* filters); + + HRESULT SaveBookmarkToBytes(IAvnString*fileUri, void**err, IAvnString**ppv); + HRESULT ReadBookmarkFromBytes(void* ptr, int len, IAvnString**ppv); + + void ReleaseBookmark(IAvnString*fileUri); + + bool OpenSecurityScope(IAvnString*fileUri); + void CloseSecurityScope(IAvnString*fileUri); } [uuid(4d7ab7db-a111-406f-abeb-11cb6aa033d5)] diff --git a/src/Browser/Avalonia.Browser/Storage/BrowserStorageProvider.cs b/src/Browser/Avalonia.Browser/Storage/BrowserStorageProvider.cs index b594cad46ac..6a89a13e023 100644 --- a/src/Browser/Avalonia.Browser/Storage/BrowserStorageProvider.cs +++ b/src/Browser/Avalonia.Browser/Storage/BrowserStorageProvider.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices.JavaScript; +using System.Text; using System.Threading.Tasks; using Avalonia.Browser.Interop; using Avalonia.Platform.Storage; @@ -12,6 +13,7 @@ namespace Avalonia.Browser.Storage; internal class BrowserStorageProvider : IStorageProvider { + internal static ReadOnlySpan<byte> BrowserBookmarkKey => "browser"u8; internal const string PickerCancelMessage = "The user aborted a request"; internal const string NoPermissionsMessage = "Permissions denied"; @@ -104,16 +106,12 @@ public async Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPic public async Task<IStorageBookmarkFile?> OpenFileBookmarkAsync(string bookmark) { - await AvaloniaModule.ImportStorage(); - var item = await StorageHelper.OpenBookmark(bookmark); - return item is not null ? new JSStorageFile(item) : null; + return await DecodeBookmark(bookmark) as IStorageBookmarkFile; } - + public async Task<IStorageBookmarkFolder?> OpenFolderBookmarkAsync(string bookmark) { - await AvaloniaModule.ImportStorage(); - var item = await StorageHelper.OpenBookmark(bookmark); - return item is not null ? new JSStorageFolder(item) : null; + return await DecodeBookmark(bookmark) as IStorageBookmarkFolder; } public Task<IStorageFile?> TryGetFileFromPathAsync(Uri filePath) @@ -158,6 +156,24 @@ private static (JSObject[]? types, bool excludeAllOption) ConvertFileTypes(IEnum return (types, !includeAll); } + + private async Task<IStorageBookmarkItem?> DecodeBookmark(string bookmark) + { + await AvaloniaModule.ImportStorage(); + var item = StorageBookmarkHelper.TryDecodeBookmark(BrowserBookmarkKey, bookmark, out var bytes) switch + { + StorageBookmarkHelper.DecodeResult.Success => await StorageHelper.OpenBookmark(Encoding.UTF8.GetString(bytes!)), + // Attempt to decode 11.0 browser bookmarks + StorageBookmarkHelper.DecodeResult.InvalidFormat => await StorageHelper.OpenBookmark(bookmark), + _ => null + }; + return item?.GetPropertyAsString("kind") switch + { + "directory" => new JSStorageFolder(item), + "file" => new JSStorageFile(item), + _ => null + }; + } } internal abstract class JSStorageItem : IStorageBookmarkItem @@ -188,14 +204,16 @@ public async Task<StorageItemProperties> GetBasicPropertiesAsync() public bool CanBookmark => StorageHelper.HasNativeFilePicker(); - public Task<string?> SaveBookmarkAsync() + public async Task<string?> SaveBookmarkAsync() { if (!CanBookmark) { - return Task.FromResult<string?>(null); + return null; } - return StorageHelper.SaveBookmark(FileHandle); + var nativeBookmark = await StorageHelper.SaveBookmark(FileHandle); + return nativeBookmark is null ? null + : StorageBookmarkHelper.EncodeBookmark(BrowserStorageProvider.BrowserBookmarkKey, nativeBookmark); } public Task<IStorageFolder?> GetParentAsync() diff --git a/src/iOS/Avalonia.iOS/Storage/IOSSecurityScopedStream.cs b/src/iOS/Avalonia.iOS/Storage/IOSSecurityScopedStream.cs deleted file mode 100644 index 424ec7589a9..00000000000 --- a/src/iOS/Avalonia.iOS/Storage/IOSSecurityScopedStream.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.IO; - -using Foundation; - -using UIKit; - -#nullable enable - -namespace Avalonia.iOS.Storage; - -internal sealed class IOSSecurityScopedStream : Stream -{ - private readonly UIDocument _document; - private readonly FileStream _stream; - private readonly NSUrl _url; - private readonly NSUrl _securityScopedAncestorUrl; - - internal IOSSecurityScopedStream(NSUrl url, NSUrl securityScopedAncestorUrl, FileAccess access) - { - _document = new UIDocument(url); - var path = _document.FileUrl.Path!; - _url = url; - _securityScopedAncestorUrl = securityScopedAncestorUrl; - _securityScopedAncestorUrl.StartAccessingSecurityScopedResource(); - _stream = File.Open(path, FileMode.Open, access); - } - - public override bool CanRead => _stream.CanRead; - - public override bool CanSeek => _stream.CanSeek; - - public override bool CanWrite => _stream.CanWrite; - - public override long Length => _stream.Length; - - public override long Position - { - get => _stream.Position; - set => _stream.Position = value; - } - - public override void Flush() => - _stream.Flush(); - - public override int Read(byte[] buffer, int offset, int count) => - _stream.Read(buffer, offset, count); - - public override long Seek(long offset, SeekOrigin origin) => - _stream.Seek(offset, origin); - - public override void SetLength(long value) => - _stream.SetLength(value); - - public override void Write(byte[] buffer, int offset, int count) => - _stream.Write(buffer, offset, count); - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (disposing) - { - _stream.Dispose(); - _document.Dispose(); - _securityScopedAncestorUrl.StopAccessingSecurityScopedResource(); - } - } -} diff --git a/src/iOS/Avalonia.iOS/Storage/IOSStorageItem.cs b/src/iOS/Avalonia.iOS/Storage/IOSStorageItem.cs index cf124aa1012..fa086c7d61f 100644 --- a/src/iOS/Avalonia.iOS/Storage/IOSStorageItem.cs +++ b/src/iOS/Avalonia.iOS/Storage/IOSStorageItem.cs @@ -5,6 +5,8 @@ using System.Threading.Tasks; using Avalonia.Logging; using Avalonia.Platform.Storage; +using Avalonia.Platform.Storage.FileIO; +using Avalonia.Reactive; using Foundation; using UIKit; @@ -132,7 +134,7 @@ public Task ReleaseBookmarkAsync() return Task.CompletedTask; } - public Task<string?> SaveBookmarkAsync() + public unsafe Task<string?> SaveBookmarkAsync() { try { @@ -141,7 +143,7 @@ public Task ReleaseBookmarkAsync() return Task.FromResult<string?>(null); } - var newBookmark = Url.CreateBookmarkData(NSUrlBookmarkCreationOptions.SuitableForBookmarkFile, Array.Empty<string>(), null, out var bookmarkError); + using var newBookmark = Url.CreateBookmarkData(NSUrlBookmarkCreationOptions.SuitableForBookmarkFile, [], null, out var bookmarkError); if (bookmarkError is not null) { Logger.TryGet(LogEventLevel.Error, LogArea.IOSPlatform)?. @@ -149,8 +151,9 @@ public Task ReleaseBookmarkAsync() return Task.FromResult<string?>(null); } + var bytes = new Span<byte>((void*)newBookmark.Bytes, (int)newBookmark.Length); return Task.FromResult<string?>( - newBookmark.GetBase64EncodedString(NSDataBase64EncodingOptions.None)); + StorageBookmarkHelper.EncodeBookmark(IOSStorageProvider.PlatformKey, bytes)); } finally { @@ -171,12 +174,28 @@ public IOSStorageFile(NSUrl url, NSUrl? securityScopedAncestorUrl = null) : base public Task<Stream> OpenReadAsync() { - return Task.FromResult<Stream>(new IOSSecurityScopedStream(Url, SecurityScopedAncestorUrl, FileAccess.Read)); + return Task.FromResult(CreateStream(FileAccess.Read)); } public Task<Stream> OpenWriteAsync() { - return Task.FromResult<Stream>(new IOSSecurityScopedStream(Url, SecurityScopedAncestorUrl, FileAccess.Write)); + return Task.FromResult(CreateStream(FileAccess.Write)); + } + + private Stream CreateStream(FileAccess fileAccess) + { + var document = new UIDocument(Url); + var path = document.FileUrl.Path!; + var scopeCreated = SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource(); + var stream = File.Open(path, FileMode.Open, fileAccess); + + return scopeCreated ? + new SecurityScopedStream(stream, Disposable.Create(() => + { + document.Dispose(); + SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource(); + })) : + stream; } } diff --git a/src/iOS/Avalonia.iOS/Storage/IOSStorageProvider.cs b/src/iOS/Avalonia.iOS/Storage/IOSStorageProvider.cs index 6d9d2b1e37c..4c1bf97c6fd 100644 --- a/src/iOS/Avalonia.iOS/Storage/IOSStorageProvider.cs +++ b/src/iOS/Avalonia.iOS/Storage/IOSStorageProvider.cs @@ -10,11 +10,14 @@ using UTTypeLegacy = MobileCoreServices.UTType; using UTType = UniformTypeIdentifiers.UTType; using System.Runtime.Versioning; +using Avalonia.Platform.Storage.FileIO; namespace Avalonia.iOS.Storage; internal class IOSStorageProvider : IStorageProvider { + public static ReadOnlySpan<byte> PlatformKey => "ios"u8; + private readonly AvaloniaView _view; public IOSStorageProvider(AvaloniaView view) { @@ -217,20 +220,41 @@ private Task<NSUrl[]> ShowPicker(UIViewController picker, TaskCompletionSource<N return tcs.Task; } - private NSUrl? GetBookmarkedUrl(string bookmark) + private unsafe NSUrl? GetBookmarkedUrl(string bookmark) { - var url = NSUrl.FromBookmarkData(new NSData(bookmark, NSDataBase64DecodingOptions.None), - NSUrlBookmarkResolutionOptions.WithoutUI, null, out var isStale, out var error); - if (isStale) + return StorageBookmarkHelper.TryDecodeBookmark(PlatformKey, bookmark, out var bytes) switch + { + StorageBookmarkHelper.DecodeResult.Success => DecodeFromBytes(bytes!), + // Attempt to decode 11.0 ios bookmarks + StorageBookmarkHelper.DecodeResult.InvalidFormat => DecodeFromNSData(new NSData(bookmark, NSDataBase64DecodingOptions.None)), + _ => null + }; + + NSUrl DecodeFromBytes(byte[] bytes) { - Logger.TryGet(LogEventLevel.Warning, LogArea.IOSPlatform)?.Log(this, "Stale bookmark detected"); + fixed (byte* ptr = bytes) + { + using var data = new NSData(new IntPtr(ptr), new UIntPtr((uint)bytes.Length), null); + return DecodeFromNSData(data); + } } - - if (error != null) + + NSUrl DecodeFromNSData(NSData nsData) { - throw new NSErrorException(error); + var url = NSUrl.FromBookmarkData(nsData, + NSUrlBookmarkResolutionOptions.WithoutUI, null, out var isStale, out var error); + if (isStale) + { + Logger.TryGet(LogEventLevel.Warning, LogArea.IOSPlatform)?.Log(this, "Stale bookmark detected"); + } + + if (error != null) + { + throw new NSErrorException(error); + } + + return url; } - return url; } private static string[] FileTypesToUTTypeLegacy(IReadOnlyList<FilePickerFileType>? filePickerFileTypes)
diff --git a/tests/Avalonia.Base.UnitTests/Utilities/UriExtensionsTests.cs b/tests/Avalonia.Base.UnitTests/Utilities/UriExtensionsTests.cs index b648b0d1782..83380bf6a02 100644 --- a/tests/Avalonia.Base.UnitTests/Utilities/UriExtensionsTests.cs +++ b/tests/Avalonia.Base.UnitTests/Utilities/UriExtensionsTests.cs @@ -36,7 +36,7 @@ public void Assembly_Name_From_Empty_Query_Not_Parsed() [InlineData("C:\\\\Work\\Projects.txt")] public void Should_Convert_File_Path_To_Uri_And_Back(string path) { - var uri = StorageProviderHelpers.FilePathToUri(path); + var uri = StorageProviderHelpers.UriFromFilePath(path, false); Assert.Equal(path, uri.LocalPath); } diff --git a/tests/Avalonia.Controls.UnitTests/Platform/StorageProviderHelperTests.cs b/tests/Avalonia.Controls.UnitTests/Platform/StorageProviderHelperTests.cs new file mode 100644 index 00000000000..301301f61dd --- /dev/null +++ b/tests/Avalonia.Controls.UnitTests/Platform/StorageProviderHelperTests.cs @@ -0,0 +1,74 @@ +using System; +using System.Linq; +using System.Text; +using Avalonia.Platform.Storage.FileIO; +using Xunit; + +namespace Avalonia.Controls.UnitTests.Platform; + +public class StorageProviderHelperTests +{ + [Fact] + public void Can_Encode_And_Decode_Bookmark() + { + var platform = "test"u8; + var nativeBookmark = "bookmark"u8; + + var bookmark = StorageBookmarkHelper.EncodeBookmark(platform, nativeBookmark); + + Assert.NotNull(bookmark); + + Assert.Equal( + StorageBookmarkHelper.DecodeResult.Success, + StorageBookmarkHelper.TryDecodeBookmark(platform, bookmark, out var nativeBookmarkRet)); + + Assert.NotNull(nativeBookmarkRet); + + Assert.True(nativeBookmark.SequenceEqual(nativeBookmarkRet)); + } + + [Theory] + [InlineData("C://file.txt", "YXZhLnYxLnRlc3QAAAAAAEM6Ly9maWxlLnR4dA==")] + public void Can_Encode_Bookmark(string nativeBookmark, string expectedEncodedBookmark) + { + var platform = "test"u8; + + var bookmark = StorageBookmarkHelper.EncodeBookmark(platform, nativeBookmark); + + Assert.Equal(expectedEncodedBookmark, bookmark); + Assert.NotNull(bookmark); + } + + [Theory] + [InlineData("YXZhLnYxLnRlc3QAAAAAAEM6Ly9maWxlLnR4dA==", "C://file.txt")] + public void Can_Decode_Bookmark(string encodedBookmark, string expectedNativeBookmark) + { + var platform = "test"u8; + var expectedNativeBookmarkBytes = Encoding.UTF8.GetBytes(expectedNativeBookmark); + + Assert.Equal( + StorageBookmarkHelper.DecodeResult.Success, + StorageBookmarkHelper.TryDecodeBookmark(platform, encodedBookmark, out var nativeBookmark)); + + Assert.Equal(expectedNativeBookmarkBytes, nativeBookmark); + } + + [Theory] + [InlineData("YXZhLnYxLmJjbAAAAAAAAEM6Ly9maWxlLnR4dA==", "C://file.txt")] + [InlineData("C://file.txt", "C://file.txt")] + public void Can_Decode_Bcl_Bookmarks(string bookmark, string expected) + { + var a = StorageBookmarkHelper.EncodeBclBookmark(expected); + Assert.True(StorageBookmarkHelper.TryDecodeBclBookmark(bookmark, out var localPath)); + Assert.Equal(expected, localPath); + } + + [Theory] + [InlineData("YXZhLnYxLnRlc3QAAAAAAEM6Ly9maWxlLnR4dA==")] // "test" platform passed instead of "bcl" + [InlineData("ZYXasHKJASd87124")] + public void Fails_To_Decode_Invalid_Bcl_Bookmarks(string bookmark) + { + Assert.False(StorageBookmarkHelper.TryDecodeBclBookmark(bookmark, out var localPath)); + Assert.Null(localPath); + } +}
Mac App Store SandBox File Access with Bookmarks feature **Is your feature request related to a problem? Please describe.** OSX native lib can have support for managing file access bookmarks in sandbox. **What is sandbox bookmarks?** By default your app in sandbox have no access to any file in the system. You can request access to Downloads/Desktop/Home folders in your entitlements - but this is a bad practice. Best practice - is to get access to the files only over system OpenFileDialog and SaveFileDialog. This is tricky: 1. you should get`NSURL` from dialog and put it into bookmarks 2. result of creation a bookmark - is byte array with bookmark identifier. You should save it anywhere so you can create a `NSURL` object from it later, after app restart for instance. 3. Before and after access to the file you should call startAccess and StopAccess methods of `NSURL`. [Sandbox Bookmarks Apple Documentation](https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) **Describe the solution you'd like** 1. analyze code in https://github.com/leighmcculloch/AppSandboxFileAccess . It's an objectiveC library with all logic we need realized. 2. enrich `IAvnSystemDialogs` to support sandbox, create an interface to work with NSURL objects (get bookmark data, create url from bookmark data, delete bookmark, open bookmark, close bookmark, etc.). 3. create it in osx native lib and register it correctly to fulfill COM requirements (is there any guide for this?) 4. realize interface and test it in real sandboxed app **Direct API changes(my thoughts):** 1. Add MacOSSandbox flag into `MacOSPlatformOptions`. 2. Check this flag in `IAvnSystemDialogs` realization and if it's true - add all selected `NSURL` to bookmarks and return bookmark data `byte[][]` for every `NSURL`. 3. Add `IAvnSandBoxBookmarks` interface with: * bool DeleteBookmark(byte[]) * IDisposable OpenBookmark(byte[]) - dispose will close bookmark
I've found wtf is `.idl` and how to edit COM API between OSX native lib and Avalonia.Native. So I've started to implementing this feature. This PR #6540 already contains COM API changes.
2024-06-23T00:55:39Z
0.1
[]
['Avalonia.Base.UnitTests.Utilities.UriExtensionsTests.Assembly_Name_From_Empty_Query_Not_Parsed', 'Avalonia.Base.UnitTests.Utilities.UriExtensionsTests.Assembly_Name_From_Query_Parsed', 'Avalonia.Base.UnitTests.Utilities.UriExtensionsTests.Should_Convert_File_Path_To_Uri_And_Back']
AvaloniaUI/Avalonia
avaloniaui__avalonia-15726
38d810b36f9f3f914e4b3f03908729f1a76ebd0f
diff --git a/src/Avalonia.Base/Animation/Animators/Animator`1.cs b/src/Avalonia.Base/Animation/Animators/Animator`1.cs index 8a4469d0209..954b62f9bca 100644 --- a/src/Avalonia.Base/Animation/Animators/Animator`1.cs +++ b/src/Avalonia.Base/Animation/Animators/Animator`1.cs @@ -28,57 +28,70 @@ protected T InterpolationHandler(double animationTime, T neutralValue) if (Count == 0) return neutralValue; - var (beforeKeyFrame, afterKeyFrame) = FindKeyFrames(animationTime); + var (from, to) = GetKeyFrames(animationTime, neutralValue); - double beforeTime, afterTime; - T beforeValue, afterValue; + var progress = (animationTime - from.Time) / (to.Time - from.Time); - if (beforeKeyFrame is null) - { - beforeTime = 0.0; - beforeValue = afterKeyFrame is { FillBefore: true, Value: T fillValue } ? fillValue : neutralValue; - } - else - { - beforeTime = beforeKeyFrame.Cue.CueValue; - beforeValue = beforeKeyFrame.Value is T value ? value : neutralValue; - } - - if (afterKeyFrame is null) - { - afterTime = 1.0; - afterValue = beforeKeyFrame is { FillAfter: true, Value: T fillValue } ? fillValue : neutralValue; - } - else - { - afterTime = afterKeyFrame.Cue.CueValue; - afterValue = afterKeyFrame.Value is T value ? value : neutralValue; - } - - var progress = (animationTime - beforeTime) / (afterTime - beforeTime); - - if (afterKeyFrame?.KeySpline is { } keySpline) + if (to.KeySpline is { } keySpline) progress = keySpline.GetSplineProgress(progress); - return Interpolate(progress, beforeValue, afterValue); + return Interpolate(progress, from.Value, to.Value); } - private (AnimatorKeyFrame? Before, AnimatorKeyFrame? After) FindKeyFrames(double time) + private (KeyFrameInfo From, KeyFrameInfo To) GetKeyFrames(double time, T neutralValue) { Debug.Assert(Count >= 1); - for (var i = 0; i < Count; i++) + // Before or right at the first frame which isn't at time 0.0: interpolate between 0.0 and the first frame. + var firstFrame = this[0]; + var firstTime = firstFrame.Cue.CueValue; + if (time <= firstTime && firstTime > 0.0) { - var keyFrame = this[i]; - var keyFrameTime = keyFrame.Cue.CueValue; + var beforeValue = firstFrame.FillBefore ? GetTypedValue(firstFrame.Value, neutralValue) : neutralValue; + return ( + new KeyFrameInfo(0.0, beforeValue, firstFrame.KeySpline), + KeyFrameInfo.FromKeyFrame(firstFrame, neutralValue)); + } - if (time < keyFrameTime || keyFrameTime == 1.0) - return (i > 0 ? this[i - 1] : null, keyFrame); + // Between two frames: interpolate between the previous frame and the next frame. + for (var i = 1; i < Count; ++i) + { + var frame = this[i]; + if (time <= frame.Cue.CueValue) + { + return ( + KeyFrameInfo.FromKeyFrame(this[i - 1], neutralValue), + KeyFrameInfo.FromKeyFrame(this[i], neutralValue)); + } + } + + // Past the last frame which is at time 1.0: interpolate between the last two frames. + var lastFrame = this[Count - 1]; + if (lastFrame.Cue.CueValue >= 1.0) + { + if (Count == 1) + { + var beforeValue = lastFrame.FillBefore ? GetTypedValue(lastFrame.Value, neutralValue) : neutralValue; + return ( + new KeyFrameInfo(0.0, beforeValue, lastFrame.KeySpline), + KeyFrameInfo.FromKeyFrame(lastFrame, neutralValue)); + } + + return ( + KeyFrameInfo.FromKeyFrame(this[Count - 2], neutralValue), + KeyFrameInfo.FromKeyFrame(lastFrame, neutralValue)); } - return (this[Count - 1], null); + // Past the last frame which isn't at time 1.0: interpolate between the last frame and 1.0. + var afterValue = lastFrame.FillAfter ? GetTypedValue(lastFrame.Value, neutralValue) : neutralValue; + return ( + KeyFrameInfo.FromKeyFrame(lastFrame, neutralValue), + new KeyFrameInfo(1.0, afterValue, lastFrame.KeySpline)); } + private static T GetTypedValue(object? untypedValue, T neutralValue) + => untypedValue is T value ? value : neutralValue; + public virtual IDisposable BindAnimation(Animatable control, IObservable<T> instance) { if (Property is null) @@ -107,5 +120,15 @@ internal IDisposable Run(Animation animation, Animatable control, IClock? clock, /// Interpolates in-between two key values given the desired progress time. /// </summary> public abstract T Interpolate(double progress, T oldValue, T newValue); + + private readonly struct KeyFrameInfo(double time, T value, KeySpline? keySpline) + { + public readonly double Time = time; + public readonly T Value = value; + public readonly KeySpline? KeySpline = keySpline; + + public static KeyFrameInfo FromKeyFrame(AnimatorKeyFrame source, T neutralValue) + => new(source.Cue.CueValue, GetTypedValue(source.Value, neutralValue), source.KeySpline); + } } }
diff --git a/tests/Avalonia.Base.UnitTests/Animation/KeySplineTests.cs b/tests/Avalonia.Base.UnitTests/Animation/KeySplineTests.cs index 61e8103bd59..8af1f7ec020 100644 --- a/tests/Avalonia.Base.UnitTests/Animation/KeySplineTests.cs +++ b/tests/Avalonia.Base.UnitTests/Animation/KeySplineTests.cs @@ -213,5 +213,109 @@ public void Check_KeySpline_Parsing_Is_Correct() expected = 1.8016358493761722; Assert.True(Math.Abs(rotateTransform.Angle - expected) <= tolerance); } + + // https://github.com/AvaloniaUI/Avalonia/issues/15704 + [Theory] + [InlineData(nameof(BackEaseIn))] + [InlineData(nameof(BackEaseOut))] + [InlineData(nameof(BackEaseInOut))] + [InlineData(nameof(ElasticEaseIn))] + [InlineData(nameof(ElasticEaseOut))] + [InlineData(nameof(ElasticEaseInOut))] + public void KeySpline_Progress_Less_Than_Zero_Or_Greater_Than_One_Works(string easingType) + { + var easing = Easing.Parse(easingType); + + var animation = new Avalonia.Animation.Animation + { + Duration = TimeSpan.FromSeconds(1.0), + Children = + { + new KeyFrame + { + Cue = new Cue(0.0), + Setters = { new Setter(TranslateTransform.YProperty, 10.0) } + }, + new KeyFrame + { + Cue = new Cue(1.0), + Setters = { new Setter(TranslateTransform.YProperty, 20.0) } + } + }, + IterationCount = new IterationCount(5), + PlaybackDirection = PlaybackDirection.Alternate, + Easing = easing + }; + + var transform = new TranslateTransform(0.0, 50.0); + var rect = new Rectangle { RenderTransform = transform }; + + var clock = new TestClock(); + + animation.RunAsync(rect, clock); + + clock.Step(TimeSpan.Zero); + Assert.Equal(10.0, transform.Y, 0.0001); + + for (var time = TimeSpan.FromSeconds(0.1); time < animation.Duration; time += TimeSpan.FromSeconds(0.1)) + { + clock.Step(time); + Assert.True(double.IsFinite(transform.Y)); + Assert.NotEqual(10.0, transform.Y); + Assert.NotEqual(20.0, transform.Y); + } + + clock.Step(animation.Duration); + Assert.Equal(20.0, transform.Y, 0.0001); + } + + [Theory] + [InlineData(nameof(BackEaseIn))] + [InlineData(nameof(BackEaseOut))] + [InlineData(nameof(BackEaseInOut))] + [InlineData(nameof(ElasticEaseIn))] + [InlineData(nameof(ElasticEaseOut))] + [InlineData(nameof(ElasticEaseInOut))] + public void KeySpline_Progress_Less_Than_Zero_Or_Greater_Than_One_Works_With_Single_KeyFrame(string easingType) + { + var easing = Easing.Parse(easingType); + + var animation = new Avalonia.Animation.Animation + { + Duration = TimeSpan.FromSeconds(1.0), + Children = + { + new KeyFrame + { + Cue = new Cue(1.0), + Setters = { new Setter(TranslateTransform.YProperty, 10.0) } + } + }, + IterationCount = new IterationCount(5), + PlaybackDirection = PlaybackDirection.Alternate, + Easing = easing + }; + + var transform = new TranslateTransform(0.0, 50.0); + var rect = new Rectangle { RenderTransform = transform }; + + var clock = new TestClock(); + + animation.RunAsync(rect, clock); + + clock.Step(TimeSpan.Zero); + Assert.Equal(50.0, transform.Y, 0.0001); + + for (var time = TimeSpan.FromSeconds(0.1); time < animation.Duration; time += TimeSpan.FromSeconds(0.1)) + { + clock.Step(time); + Assert.True(double.IsFinite(transform.Y)); + Assert.NotEqual(50.0, transform.Y); + Assert.NotEqual(10.0, transform.Y); + } + + clock.Step(animation.Duration); + Assert.Equal(10.0, transform.Y, 0.0001); + } } }
Translate animation flickers control visibility when using certain easings as of v11.0.6 ### Describe the bug We originally built a feature into our user prompt dialog overlay where if the user clicked into an area outside of the dialog, we would visually "shake" the dialog with a quick animation to indicate the operation wasn't allowed. This was implemented back when we referenced Avalonia v11.0.5 and worked great. We were about to implement a similar feature in another control in our latest codebase that now targets v11.0.7+ and found that the animation is causing the control to flicker visibility. After digging in, we found that `BackEaseIn`, `BackEaseInOut`, `ElasticEaseIn`, and `ElasticEaseInOut` all cause the issue starting in Avalonia v11.0.6 and it is easily reproduced. ### To Reproduce Add the following XAML to a project and check the `CheckBox` to trigger the animation. You will see the button flicker visibility at times the easing (if it is `BackEaseIn`, `BackEaseInOut`, `ElasticEaseIn`, or `ElasticEaseInOut`) drops below the bottom line in the charts here: https://docs.avaloniaui.net/docs/reference/animation-settings This all worked fine in v11.0.5, but some change in v11.0.6 broke it. The bug is present from v11.0.6 through the current master. This animation shows the issue in action: ![AnimationIssue](https://github.com/AvaloniaUI/Avalonia/assets/5760058/9e4dce06-5727-4f30-8458-9b89cc8a0d86) Whereas here in v11.0.5 is how it should look: ![AnimationWorking](https://github.com/AvaloniaUI/Avalonia/assets/5760058/32c77a2f-00cf-40b3-876a-26fe80c9e1eb) ``` <StackPanel> <Panel Width="300" Height="200" HorizontalAlignment="Left" Background="LightGray"> <Button x:Name="shakeButton" IsEnabled="False" Content="Shakes When Enabled" HorizontalAlignment="Center" VerticalAlignment="Center"> <Button.Theme> <ControlTheme TargetType="Button"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="Black" BorderThickness="1" Background="White" Padding="20"> <ContentPresenter Content="{TemplateBinding Content}" /> </Border> </ControlTemplate> </Setter> <Style Selector="^:disabled"> <Setter Property="TextElement.Foreground" Value="LightGray" /> </Style> <Style Selector="^:not(:disabled)"> <Setter Property="TextElement.Foreground" Value="Blue" /> <Style.Animations> <Animation FillMode="Both" Duration="0:0:1"> <Animation.Easing> <!-- The following easing have flicker issues, which is every easing that drops below the bottom line in the charts here: https://docs.avaloniaui.net/docs/reference/animation-settings <BackEaseIn/> <BackEaseInOut/> <ElasticEaseIn /> <ElasticEaseInOut /> --> <ElasticEaseInOut/> </Animation.Easing> <KeyFrame Cue="0%"> <Setter Property="TranslateTransform.Y" Value="0" /> </KeyFrame> <KeyFrame Cue="50%"> <Setter Property="TranslateTransform.Y" Value="-10" /> </KeyFrame> <KeyFrame Cue="100%"> <Setter Property="TranslateTransform.Y" Value="0" /> </KeyFrame> </Animation> </Style.Animations> </Style> </ControlTheme> </Button.Theme> </Button> </Panel> <TextBlock TextWrapping="Wrap">Check the box to enable the button and trigger an aimation. BackEaseIn, BackEaseInOut, ElasticEaseIn, and ElasticEaseInOut all cause issues.</TextBlock> <CheckBox IsChecked="{Binding #shakeButton.IsEnabled}" Content="Is enabled" /> </StackPanel> ``` ### Expected behavior The animation should move the button correctly even when the easing temporarily puts the animated control out of range of the normal values, and no visibility flickering should occur. This worked in v11.0.5. ### Avalonia version v11.0.6 and later ### OS Windows ### Additional context _No response_
null
2024-05-14T17:52:20Z
0.1
['Avalonia.Base.UnitTests.Animation.KeySplineTests.KeySpline_Progress_Less_Than_Zero_Or_Greater_Than_One_Works_With_Single_KeyFrame', 'Avalonia.Base.UnitTests.Animation.KeySplineTests.KeySpline_Progress_Less_Than_Zero_Or_Greater_Than_One_Works']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-15722
a60c59083d2e451f076afee020b2aefdb93d4d90
diff --git a/src/Avalonia.Base/Data/BindingNotification.cs b/src/Avalonia.Base/Data/BindingNotification.cs index 0c940a14610..a3a2e0c2b05 100644 --- a/src/Avalonia.Base/Data/BindingNotification.cs +++ b/src/Avalonia.Base/Data/BindingNotification.cs @@ -57,7 +57,6 @@ public class BindingNotification /// <param name="value">The binding value.</param> public BindingNotification(object? value) { - Debug.Assert(value is not BindingNotification); _value = value; } diff --git a/src/Avalonia.Base/Data/Core/ExpressionNodes/ExpressionNode.cs b/src/Avalonia.Base/Data/Core/ExpressionNodes/ExpressionNode.cs index e8e6633ab73..8b53190f869 100644 --- a/src/Avalonia.Base/Data/Core/ExpressionNodes/ExpressionNode.cs +++ b/src/Avalonia.Base/Data/Core/ExpressionNodes/ExpressionNode.cs @@ -187,13 +187,20 @@ protected void SetValue(object? valueOrNotification) else if (notification.ErrorType == BindingErrorType.DataValidationError) { if (notification.HasValue) - SetValue(notification.Value, notification.Error); + { + if (notification.Value is BindingNotification n) + SetValue(n); + else + SetValue(notification.Value, notification.Error); + } else + { SetDataValidationError(notification.Error!); + } } else { - SetValue(notification.Value, null); + SetValue(notification.Value); } } else
diff --git a/tests/Avalonia.Base.UnitTests/Data/Core/BindingExpressionTests.DataValidation.cs b/tests/Avalonia.Base.UnitTests/Data/Core/BindingExpressionTests.DataValidation.cs index bedf24bd6d7..8e1865f2092 100644 --- a/tests/Avalonia.Base.UnitTests/Data/Core/BindingExpressionTests.DataValidation.cs +++ b/tests/Avalonia.Base.UnitTests/Data/Core/BindingExpressionTests.DataValidation.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using Avalonia.Data; using Avalonia.UnitTests; using Xunit; @@ -271,6 +272,39 @@ public void Updates_Data_Validation_For_Null_Value_In_Property_Chain() GC.KeepAlive(data); } + [Fact] + public void Updates_Data_Validation_For_Required_DataAnnotation() + { + var data = new DataAnnotationsViewModel(); + var target = CreateTargetWithSource( + data, + o => o.RequiredString, + enableDataValidation: true); + + AssertBindingError( + target, + TargetClass.StringProperty, + new DataValidationException("String is required!"), + BindingErrorType.DataValidationError); + } + + [Fact] + public void Handles_Indei_And_DataAnnotations_On_Same_Class() + { + // Issue #15201 + var data = new IndeiDataAnnotationsViewModel(); + var target = CreateTargetWithSource( + data, + o => o.RequiredString, + enableDataValidation: true); + + AssertBindingError( + target, + TargetClass.StringProperty, + new DataValidationException("String is required!"), + BindingErrorType.DataValidationError); + } + public class ExceptionViewModel : NotifyingBase { private int _mustBePositive; @@ -341,6 +375,42 @@ public IndeiViewModel? Inner public override IEnumerable? GetErrors(string propertyName) => null; } + private class DataAnnotationsViewModel : NotifyingBase + { + private string? _requiredString; + + [Required(ErrorMessage = "String is required!")] + public string? RequiredString + { + get { return _requiredString; } + set { _requiredString = value; RaisePropertyChanged(); } + } + } + + private class IndeiDataAnnotationsViewModel : IndeiBase + { + private string? _requiredString; + + [Required(ErrorMessage = "String is required!")] + public string? RequiredString + { + get { return _requiredString; } + set { _requiredString = value; RaisePropertyChanged(); } + } + + public override bool HasErrors => RequiredString is null; + + public override IEnumerable? GetErrors(string propertyName) + { + if (propertyName == nameof(RequiredString) && RequiredString is null) + { + return new[] { "String is required!" }; + } + + return null; + } + } + private static void AssertNoError(TargetClass target, AvaloniaProperty property) { Assert.False(target.BindingNotifications.TryGetValue(property, out var notification));
11.1.0-beta1 stackoverflow on property set (SetProperty), works in 11.0.10 ### Describe the bug This code below is stack overflowing on 11.1.0-beta1. If I roll back to 11.0.10 the code works fine. ``` CSharp [Required(ErrorMessage = "Name is required!")] public string Name { get => _name; set => SetProperty(ref _name, value, true); } ``` ### To Reproduce Call ObservableValidator.SetProperty in 11.1.0-beta1 leads to stackoverflow. ``` CSharp [Required(ErrorMessage = "Name is required!")] ``` I think it's due to the required attribute but I'm not sure. ### Expected behavior The code should not stackoverflow? ### Avalonia version 11.1.0-beta1 ### OS Windows ### Additional context _No response_
Stacktrace (of stackoverflow) and SetProperty implementation are required to help here. Or minimal repro project. @BobbyCannon I have the same issue, check if your App.axaml.cs's `OnFrameworkInitializationCompleted()` has following code: ```csharp BindingPlugins.DataValidators.RemoveAt(0); ``` @maxkatz6 Maybe consider adding this note in the Release message @laolarou726 what exactly should be added to the release message? > @laolarou726 what exactly should be added to the release message? I mean this line of code. When I upgrading the Avalonia version for my older project. I also noticed this issue. After some investigation, I noticed this line of code has been added to the latest template project. So maybe add this notice some where in the document or Release message might be a good idea? minimal repro to paste into `src/Samples/Sandbox` ```cs public MainWindow() { InitializeComponent(); DataContext = new ViewModel(); } .... public partial class ViewModel : ObservableValidator { // [Required(ErrorMessage = "Name is required!")] [ObservableProperty] [NotifyDataErrorInfo] private string? _Name; } ``` and ```xml <TextBox Text="{Binding Name}" /> ``` -------- seems to stuck around here: ![image](https://github.com/AvaloniaUI/Avalonia/assets/47110241/ec21199b-5e7c-4c87-a073-2deabfa332bc) ... and here: ![image](https://github.com/AvaloniaUI/Avalonia/assets/47110241/1ae23425-95cb-4f38-8148-349ee81029db) I had commented that line of code then removed it. ![image](https://github.com/AvaloniaUI/Avalonia/assets/840590/d07e04bb-3eb8-45b8-b65b-10d2050edd23) I was concerned about two things... 1. Why 0 index, what it that changes in an upgrade? 2. What was being removed. This morning I wrote this... ``` CSharp // Removes {Avalonia.Data.Core.Plugins.DataAnnotationsValidationPlugin} var found = BindingPlugins.DataValidators.FirstOrDefault(x => x is DataAnnotationsValidationPlugin); if (found != null) { BindingPlugins.DataValidators.Remove(found); } ``` It won't break if the validator moves to a different location. Also is this still just a bug with the DataAnnotationsValidationPlugin? I noticed while debugging this value adds { Value: } around the previous value. @BobbyCannon https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins However, this is still a regression imo, so keep this ticket open for now.
2024-05-14T13:41:27Z
0.1
['Avalonia.Base.UnitTests.Data.Core.BindingExpressionTests+Reflection.Updates_Data_Validation_For_Required_DataAnnotation', 'Avalonia.Base.UnitTests.Data.Core.BindingExpressionTests+Compiled.Handles_Indei_And_DataAnnotations_On_Same_Class']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-15667
d1cdb29ba019f16f98dc44821bb51b24abc5d93c
diff --git a/api/Avalonia.nupkg.xml b/api/Avalonia.nupkg.xml index 6b79f6f33b0..13b9724778f 100644 --- a/api/Avalonia.nupkg.xml +++ b/api/Avalonia.nupkg.xml @@ -19,6 +19,12 @@ <Left>baseline/netstandard2.0/Avalonia.Base.dll</Left> <Right>target/netstandard2.0/Avalonia.Base.dll</Right> </Suppression> + <Suppression> + <DiagnosticId>CP0002</DiagnosticId> + <Target>M:Avalonia.Controls.Primitives.IPopupHost.ConfigurePosition(Avalonia.Visual,Avalonia.Controls.PlacementMode,Avalonia.Point,Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor,Avalonia.Controls.Primitives.PopupPositioning.PopupGravity,Avalonia.Controls.Primitives.PopupPositioning.PopupPositionerConstraintAdjustment,System.Nullable{Avalonia.Rect})</Target> + <Left>baseline/netstandard2.0/Avalonia.Controls.dll</Left> + <Right>target/netstandard2.0/Avalonia.Controls.dll</Right> + </Suppression> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:Avalonia.Controls.Screens.#ctor(Avalonia.Platform.IScreenImpl)</Target> @@ -43,6 +49,12 @@ <Left>baseline/netstandard2.0/Avalonia.Controls.dll</Left> <Right>target/netstandard2.0/Avalonia.Controls.dll</Right> </Suppression> + <Suppression> + <DiagnosticId>CP0006</DiagnosticId> + <Target>M:Avalonia.Controls.Primitives.IPopupHost.ConfigurePosition(Avalonia.Controls.Primitives.PopupPositioning.PopupPositionRequest)</Target> + <Left>baseline/netstandard2.0/Avalonia.Controls.dll</Left> + <Right>target/netstandard2.0/Avalonia.Controls.dll</Right> + </Suppression> <Suppression> <DiagnosticId>CP0009</DiagnosticId> <Target>T:Avalonia.Controls.Screens</Target> diff --git a/samples/ControlCatalog/Pages/FlyoutsPage.axaml b/samples/ControlCatalog/Pages/FlyoutsPage.axaml index c0521cd3ba5..64a005c987f 100644 --- a/samples/ControlCatalog/Pages/FlyoutsPage.axaml +++ b/samples/ControlCatalog/Pages/FlyoutsPage.axaml @@ -222,7 +222,15 @@ </Flyout> </Button.Flyout> </Button> - + <Button Content="Placement=Custom"> + <Button.Flyout> + <Flyout Placement="Custom" CustomPopupPlacementCallback="CustomPlacementCallback"> + <Panel Width="100" Height="100"> + <TextBlock Text="Flyout Content!" /> + </Panel> + </Flyout> + </Button.Flyout> + </Button> </UniformGrid> </Border> </StackPanel> @@ -267,7 +275,6 @@ </Flyout> </Button.Flyout> </Button> - </WrapPanel> </Border> </StackPanel> diff --git a/samples/ControlCatalog/Pages/FlyoutsPage.axaml.cs b/samples/ControlCatalog/Pages/FlyoutsPage.axaml.cs index 89441513856..5897eb2cde0 100644 --- a/samples/ControlCatalog/Pages/FlyoutsPage.axaml.cs +++ b/samples/ControlCatalog/Pages/FlyoutsPage.axaml.cs @@ -1,5 +1,8 @@ +using System; +using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; +using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Interactivity; namespace ControlCatalog.Pages @@ -71,5 +74,25 @@ private void SetXamlTexts() "Then attach the flyout where you want it:\n" + "<Button Content=\"Launch Flyout here\" Flyout=\"{StaticResource SharedFlyout}\" />"; } + + public void CustomPlacementCallback(CustomPopupPlacement placement) + { + var r = new Random().Next(); + placement.Anchor = (r % 4) switch + { + 1 => PopupAnchor.Top, + 2 => PopupAnchor.Left, + 3 => PopupAnchor.Right, + _ => PopupAnchor.Bottom, + }; + placement.Gravity = (r % 4) switch + { + 1 => PopupGravity.Top, + 2 => PopupGravity.Left, + 3 => PopupGravity.Right, + _ => PopupGravity.Bottom, + }; + placement.Offset = new Point(r % 20, r % 20); + } } } diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml b/samples/ControlCatalog/Pages/ToolTipPage.xaml index 8aaed903f36..8b76cccbc96 100644 --- a/samples/ControlCatalog/Pages/ToolTipPage.xaml +++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml @@ -5,31 +5,24 @@ Spacing="4"> <TextBlock Classes="h2">A control which pops up a hint when a control is hovered</TextBlock> - <Grid RowDefinitions="Auto,Auto,Auto,Auto" - ColumnDefinitions="Auto,Auto" - Margin="0,16,0,0" - HorizontalAlignment="Center"> + <UniformGrid Columns="2" + Margin="0,16,0,0" + HorizontalAlignment="Center"> <ToggleSwitch Margin="5" - HorizontalAlignment="Center" - IsChecked="{Binding Path=(ToolTip.ServiceEnabled), RelativeSource={RelativeSource AncestorType=UserControl}}" - Content="Enable ToolTip service" /> - <Border Grid.Column="0" - Grid.Row="1" - Background="{DynamicResource SystemAccentColor}" + HorizontalAlignment="Center" + IsChecked="{Binding Path=(ToolTip.ServiceEnabled), RelativeSource={RelativeSource AncestorType=UserControl}}" + Content="Enable ToolTip service" /> + <ToggleSwitch Margin="5" + IsChecked="{Binding ElementName=Border, Path=(ToolTip.IsOpen)}" + HorizontalAlignment="Center" + Content="ToolTip Open" /> + <Border Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" ToolTip.Tip="This is a ToolTip"> <TextBlock>Hover Here</TextBlock> </Border> - <ToggleSwitch Grid.Column="1" - Margin="5" - Grid.Row="0" - IsChecked="{Binding ElementName=Border, Path=(ToolTip.IsOpen)}" - HorizontalAlignment="Center" - Content="ToolTip Open" /> <Border Name="Border" - Grid.Column="1" - Grid.Row="1" Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" @@ -42,8 +35,15 @@ </ToolTip.Tip> <TextBlock>ToolTip bottom placement</TextBlock> </Border> - <Border Grid.Row="2" - Background="{DynamicResource SystemAccentColor}" + <Border Background="{DynamicResource SystemAccentColor}" + Margin="5" + Padding="50" + ToolTip.Placement="Custom" + ToolTip.CustomPopupPlacementCallback="CustomPlacementCallback" + ToolTip.Tip="Custom positioned tooltip"> + <TextBlock>ToolTip custom placement</TextBlock> + </Border> + <Border Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" ToolTip.Tip="Hello" @@ -67,8 +67,7 @@ <TextBlock>Moving offset</TextBlock> </Border> - <Button Grid.Row="2" Grid.Column="1" - IsEnabled="False" + <Button IsEnabled="False" ToolTip.ShowOnDisabled="True" ToolTip.Tip="This control is disabled" Margin="5" @@ -76,24 +75,20 @@ <TextBlock>ToolTip on a disabled control</TextBlock> </Button> - <Border Grid.Row="3" - Grid.Column="0" - Background="{DynamicResource SystemAccentColor}" + <Border Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" ToolTip.Tip="Outer tooltip"> <TextBlock Background="{StaticResource SystemAccentColorDark1}" Padding="10" ToolTip.Tip="Inner tooltip" VerticalAlignment="Center">Nested ToolTips</TextBlock> </Border> - - <Border Grid.Row="3" - Grid.Column="1" - Background="{DynamicResource SystemAccentColor}" + + <Border Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" ToolTip.ToolTipOpening="ToolTipOpening" ToolTip.Tip="Should never be visible"> <TextBlock VerticalAlignment="Center">ToolTip replaced on the fly</TextBlock> </Border> - </Grid> + </UniformGrid> </StackPanel> </UserControl> diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs b/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs index 0e8bf3a181d..7efdb99078c 100644 --- a/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs +++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs @@ -1,5 +1,8 @@ +using System; +using Avalonia; using Avalonia.Controls; using Avalonia.Interactivity; +using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Markup.Xaml; namespace ControlCatalog.Pages @@ -19,6 +22,27 @@ private void InitializeComponent() private void ToolTipOpening(object? sender, CancelRoutedEventArgs args) { ((Control)args.Source!).SetValue(ToolTip.TipProperty, "New tip set from ToolTipOpening."); - } + } + + public void CustomPlacementCallback(CustomPopupPlacement placement) + { + var r = new Random().Next(); + + placement.Anchor = (r % 4) switch + { + 1 => PopupAnchor.Top, + 2 => PopupAnchor.Left, + 3 => PopupAnchor.Right, + _ => PopupAnchor.Bottom, + }; + placement.Gravity = (r % 4) switch + { + 1 => PopupGravity.Top, + 2 => PopupGravity.Left, + 3 => PopupGravity.Right, + _ => PopupGravity.Bottom, + }; + placement.Offset = new Point(r % 20, r % 20); + } } } diff --git a/src/Avalonia.Controls/ContextMenu.cs b/src/Avalonia.Controls/ContextMenu.cs index cb64cc27e60..940528bf6f2 100644 --- a/src/Avalonia.Controls/ContextMenu.cs +++ b/src/Avalonia.Controls/ContextMenu.cs @@ -82,6 +82,10 @@ public class ContextMenu : MenuBase, ISetterValue, IPopupHostProvider public static readonly StyledProperty<Control?> PlacementTargetProperty = Popup.PlacementTargetProperty.AddOwner<ContextMenu>(); + /// <inheritdoc cref="Popup.CustomPopupPlacementCallbackProperty"/> + public static readonly StyledProperty<CustomPopupPlacementCallback?> CustomPopupPlacementCallbackProperty = + Popup.CustomPopupPlacementCallbackProperty.AddOwner<ContextMenu>(); + private Popup? _popup; private List<Control>? _attachedControls; private IInputElement? _previousFocus; @@ -185,6 +189,13 @@ public Control? PlacementTarget set => SetValue(PlacementTargetProperty, value); } + /// <inheritdoc cref="Popup.CustomPopupPlacementCallback"/> + public CustomPopupPlacementCallback? CustomPopupPlacementCallback + { + get => GetValue(CustomPopupPlacementCallbackProperty); + set => SetValue(CustomPopupPlacementCallbackProperty, value); + } + /// <summary> /// Occurs when the value of the /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" /> @@ -340,6 +351,7 @@ private void Open(Control control, Control placementTarget, PlacementMode placem _popup.PlacementConstraintAdjustment = PlacementConstraintAdjustment; _popup.PlacementGravity = PlacementGravity; _popup.PlacementRect = PlacementRect; + _popup.CustomPopupPlacementCallback = CustomPopupPlacementCallback; _popup.WindowManagerAddShadowHint = WindowManagerAddShadowHint; IsOpen = true; _popup.IsOpen = true; diff --git a/src/Avalonia.Controls/ContextRequestedEventArgs.cs b/src/Avalonia.Controls/ContextRequestedEventArgs.cs index ad5ffef267d..fa0d5f98557 100644 --- a/src/Avalonia.Controls/ContextRequestedEventArgs.cs +++ b/src/Avalonia.Controls/ContextRequestedEventArgs.cs @@ -26,6 +26,13 @@ public ContextRequestedEventArgs(PointerEventArgs pointerEventArgs) _pointerEventArgs = pointerEventArgs; } + /// <inheritdoc cref="ContextRequestedEventArgs()" /> + public ContextRequestedEventArgs(ContextRequestedEventArgs contextRequestedEventArgs) + : this() + { + _pointerEventArgs = contextRequestedEventArgs._pointerEventArgs; + } + /// <summary> /// Gets the x- and y-coordinates of the pointer position, optionally evaluated against a coordinate origin of a supplied <see cref="Control"/>. /// </summary> diff --git a/src/Avalonia.Controls/Flyouts/PopupFlyoutBase.cs b/src/Avalonia.Controls/Flyouts/PopupFlyoutBase.cs index 0c72d67154a..82a243cd727 100644 --- a/src/Avalonia.Controls/Flyouts/PopupFlyoutBase.cs +++ b/src/Avalonia.Controls/Flyouts/PopupFlyoutBase.cs @@ -30,11 +30,15 @@ public abstract class PopupFlyoutBase : FlyoutBase, IPopupHostProvider /// <inheritdoc cref="Popup.PlacementAnchorProperty"/> public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty = Popup.PlacementAnchorProperty.AddOwner<PopupFlyoutBase>(); - + /// <inheritdoc cref="Popup.PlacementAnchorProperty"/> public static readonly StyledProperty<PopupGravity> PlacementGravityProperty = Popup.PlacementGravityProperty.AddOwner<PopupFlyoutBase>(); + /// <inheritdoc cref="Popup.CustomPopupPlacementCallbackProperty"/> + public static readonly StyledProperty<CustomPopupPlacementCallback?> CustomPopupPlacementCallbackProperty = + Popup.CustomPopupPlacementCallbackProperty.AddOwner<PopupFlyoutBase>(); + /// <summary> /// Defines the <see cref="ShowMode"/> property /// </summary> @@ -112,6 +116,13 @@ public double VerticalOffset set => SetValue(VerticalOffsetProperty, value); } + /// <inheritdoc cref="Popup.CustomPopupPlacementCallback"/> + public CustomPopupPlacementCallback? CustomPopupPlacementCallback + { + get => GetValue(CustomPopupPlacementCallbackProperty); + set => SetValue(CustomPopupPlacementCallbackProperty, value); + } + /// <summary> /// Gets or sets the desired ShowMode /// </summary> @@ -445,6 +456,7 @@ private void PositionPopup(bool showAtPointer) Popup.HorizontalOffset = HorizontalOffset; Popup.PlacementAnchor = PlacementAnchor; Popup.PlacementGravity = PlacementGravity; + Popup.CustomPopupPlacementCallback = CustomPopupPlacementCallback; if (showAtPointer) { Popup.Placement = PlacementMode.Pointer; diff --git a/src/Avalonia.Controls/PlacementMode.cs b/src/Avalonia.Controls/PlacementMode.cs index 20e4e5470d5..93116d8f1a2 100644 --- a/src/Avalonia.Controls/PlacementMode.cs +++ b/src/Avalonia.Controls/PlacementMode.cs @@ -81,6 +81,11 @@ public enum PlacementMode /// <summary> /// Preferred location is to the right of the target element, with the bottom edge of popup aligned with bottom edge of the target element. /// </summary> - RightEdgeAlignedBottom + RightEdgeAlignedBottom, + + /// <summary> + /// A position and repositioning behavior that is defined by the <see cref="Popup.CustomPopupPlacementCallback"/> property. + /// </summary> + Custom } } diff --git a/src/Avalonia.Controls/Primitives/IPopupHost.cs b/src/Avalonia.Controls/Primitives/IPopupHost.cs index 0aad838b0f4..4cb259db5f7 100644 --- a/src/Avalonia.Controls/Primitives/IPopupHost.cs +++ b/src/Avalonia.Controls/Primitives/IPopupHost.cs @@ -1,6 +1,7 @@ using System; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives.PopupPositioning; +using Avalonia.Diagnostics; using Avalonia.Input; using Avalonia.Media; using Avalonia.Metadata; @@ -17,6 +18,7 @@ namespace Avalonia.Controls.Primitives /// on an <see cref="OverlayLayer"/>. /// </remarks> [NotClientImplementable] + [Unstable(ObsoletionMessages.MayBeRemovedInAvalonia12)] public interface IPopupHost : IDisposable, IFocusScope { /// <summary> @@ -79,20 +81,7 @@ public interface IPopupHost : IDisposable, IFocusScope /// Configures the position of the popup according to a target control and a set of /// placement parameters. /// </summary> - /// <param name="target">The placement target.</param> - /// <param name="placement">The placement mode.</param> - /// <param name="offset">The offset, in device-independent pixels.</param> - /// <param name="anchor">The anchor point.</param> - /// <param name="gravity">The popup gravity.</param> - /// <param name="constraintAdjustment">Defines how a popup position will be adjusted if the unadjusted position would result in the popup being partly constrained.</param> - /// <param name="rect"> - /// The anchor rect. If null, the bounds of <paramref name="target"/> will be used. - /// </param> - void ConfigurePosition(Visual target, PlacementMode placement, Point offset, - PopupAnchor anchor = PopupAnchor.None, - PopupGravity gravity = PopupGravity.None, - PopupPositionerConstraintAdjustment constraintAdjustment = PopupPositionerConstraintAdjustment.All, - Rect? rect = null); + void ConfigurePosition(PopupPositionRequest positionRequest); /// <summary> /// Sets the control to display in the popup. diff --git a/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs b/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs index 43bb9b2947f..3a602c15b7d 100644 --- a/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs +++ b/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using Avalonia.Controls.Primitives.PopupPositioning; +using Avalonia.Diagnostics; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Metadata; -using Avalonia.Threading; using Avalonia.VisualTree; namespace Avalonia.Controls.Primitives @@ -19,9 +19,10 @@ public class OverlayPopupHost : ContentControl, IPopupHost, IManagedPopupPositio private readonly OverlayLayer _overlayLayer; private readonly ManagedPopupPositioner _positioner; - private PopupPositionerParameters _positionerParameters; private Point _lastRequestedPosition; - private bool _shown; + private PopupPositionRequest? _popupPositionRequest; + private Size _popupSize; + private bool _shown, _needsUpdate; public OverlayPopupHost(OverlayLayer overlayLayer) { @@ -73,36 +74,42 @@ public void Hide() } /// <inheritdoc /> + [Unstable(ObsoletionMessages.MayBeRemovedInAvalonia12)] public void ConfigurePosition(Visual target, PlacementMode placement, Point offset, PopupAnchor anchor = PopupAnchor.None, PopupGravity gravity = PopupGravity.None, PopupPositionerConstraintAdjustment constraintAdjustment = PopupPositionerConstraintAdjustment.All, Rect? rect = null) { - _positionerParameters.ConfigurePosition((TopLevel)_overlayLayer.GetVisualRoot()!, target, placement, offset, anchor, - gravity, constraintAdjustment, rect, FlowDirection); + ((IPopupHost)this).ConfigurePosition(new PopupPositionRequest(target, placement, offset, anchor, gravity, + constraintAdjustment, rect, null)); + } + + /// <inheritdoc /> + void IPopupHost.ConfigurePosition(PopupPositionRequest positionRequest) + { + _popupPositionRequest = positionRequest; + _needsUpdate = true; UpdatePosition(); } /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { - if (_positionerParameters.Size != finalSize) + if (_popupSize != finalSize) { - _positionerParameters.Size = finalSize; + _popupSize = finalSize; + _needsUpdate = true; UpdatePosition(); } return base.ArrangeOverride(finalSize); } - private void UpdatePosition() { - // Don't bother the positioner with layout system artifacts - if (_positionerParameters.Size.Width == 0 || _positionerParameters.Size.Height == 0) - return; - if (_shown) + if (_needsUpdate && _popupPositionRequest is not null) { - _positioner.Update(_positionerParameters); + _needsUpdate = false; + _positioner.Update(TopLevel.GetTopLevel(_overlayLayer)!, _popupPositionRequest, _popupSize, FlowDirection); } } diff --git a/src/Avalonia.Controls/Primitives/Popup.cs b/src/Avalonia.Controls/Primitives/Popup.cs index 4c726e91839..28e2a51e069 100644 --- a/src/Avalonia.Controls/Primitives/Popup.cs +++ b/src/Avalonia.Controls/Primitives/Popup.cs @@ -22,6 +22,9 @@ namespace Avalonia.Controls.Primitives /// </summary> public class Popup : Control, IPopupHostProvider { + /// <summary> + /// Defines the <see cref="WindowManagerAddShadowHint"/> property. + /// </summary> public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty = AvaloniaProperty.Register<Popup, bool>(nameof(WindowManagerAddShadowHint), false); @@ -89,9 +92,21 @@ public class Popup : Control, IPopupHostProvider public static readonly StyledProperty<Control?> PlacementTargetProperty = AvaloniaProperty.Register<Popup, Control?>(nameof(PlacementTarget)); + /// <summary> + /// Defines the <see cref="CustomPopupPlacementCallback"/> property. + /// </summary> + public static readonly StyledProperty<CustomPopupPlacementCallback?> CustomPopupPlacementCallbackProperty = + AvaloniaProperty.Register<Popup, CustomPopupPlacementCallback?>(nameof(CustomPopupPlacementCallback)); + + /// <summary> + /// Defines the <see cref="OverlayDismissEventPassThrough"/> property. + /// </summary> public static readonly StyledProperty<bool> OverlayDismissEventPassThroughProperty = AvaloniaProperty.Register<Popup, bool>(nameof(OverlayDismissEventPassThrough)); + /// <summary> + /// Defines the <see cref="OverlayInputPassThroughElement"/> property. + /// </summary> public static readonly StyledProperty<IInputElement?> OverlayInputPassThroughElementProperty = AvaloniaProperty.Register<Popup, IInputElement?>(nameof(OverlayInputPassThroughElement)); @@ -287,6 +302,15 @@ public Control? PlacementTarget set => SetValue(PlacementTargetProperty, value); } + /// <summary> + /// Gets or sets a delegate handler method that positions the Popup control, when <see cref="Placement"/> is set to <see cref="PlacementMode.Custom"/>. + /// </summary> + public CustomPopupPlacementCallback? CustomPopupPlacementCallback + { + get => GetValue(CustomPopupPlacementCallbackProperty); + set => SetValue(CustomPopupPlacementCallbackProperty, value); + } + /// <summary> /// Gets or sets a value indicating whether the event that closes the popup is passed /// through to the parent window. @@ -603,14 +627,15 @@ internal void SetPopupParent(Control? newParent) private void UpdateHostPosition(IPopupHost popupHost, Control placementTarget) { - popupHost.ConfigurePosition( + popupHost.ConfigurePosition(new PopupPositionRequest( placementTarget, Placement, new Point(HorizontalOffset, VerticalOffset), PlacementAnchor, PlacementGravity, PlacementConstraintAdjustment, - PlacementRect ?? new Rect(default, placementTarget.Bounds.Size)); + PlacementRect ?? new Rect(default, placementTarget.Bounds.Size), + CustomPopupPlacementCallback)); } private void UpdateHostSizing(IPopupHost popupHost, TopLevel topLevel, Control placementTarget) @@ -651,14 +676,15 @@ private void HandlePositionChange() var placementTarget = PlacementTarget ?? this.FindLogicalAncestorOfType<Control>(); if (placementTarget == null) return; - _openState.PopupHost.ConfigurePosition( + _openState.PopupHost.ConfigurePosition(new PopupPositionRequest( placementTarget, Placement, new Point(HorizontalOffset, VerticalOffset), PlacementAnchor, PlacementGravity, PlacementConstraintAdjustment, - PlacementRect); + PlacementRect, + CustomPopupPlacementCallback)); } } diff --git a/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacement.cs b/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacement.cs new file mode 100644 index 00000000000..8be812b4eae --- /dev/null +++ b/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacement.cs @@ -0,0 +1,57 @@ +namespace Avalonia.Controls.Primitives.PopupPositioning; + +/// <summary> +/// Defines custom placement parameters for a <see cref="CustomPopupPlacementCallback"/> callback. +/// </summary> +public record CustomPopupPlacement +{ + private PopupGravity _gravity; + private PopupAnchor _anchor; + + internal CustomPopupPlacement(Size popupSize, Visual target) + { + PopupSize = popupSize; + Target = target; + } + + /// <summary> + /// The <see cref="Size"/> of the <see cref="Popup"/> control. + /// </summary> + public Size PopupSize { get; } + + /// <summary> + /// Placement target of the popup. + /// </summary> + public Visual Target { get; } + + /// <see cref="PopupPositionerParameters.AnchorRectangle"/> + public Rect AnchorRectangle { get; set; } + + /// <see cref="PopupPositionerParameters.Anchor"/> + public PopupAnchor Anchor + { + get => _anchor; + set + { + PopupPositioningEdgeHelper.ValidateEdge(value); + _anchor = value; + } + } + + /// <see cref="PopupPositionerParameters.Gravity"/> + public PopupGravity Gravity + { + get => _gravity; + set + { + PopupPositioningEdgeHelper.ValidateGravity(value); + _gravity = value; + } + } + + /// <see cref="PopupPositionerParameters.ConstraintAdjustment"/> + public PopupPositionerConstraintAdjustment ConstraintAdjustment { get; set; } + + /// <see cref="PopupPositionerParameters.Offset"/> + public Point Offset { get; set; } +} diff --git a/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacementCallback.cs b/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacementCallback.cs new file mode 100644 index 00000000000..dbe90d8d32e --- /dev/null +++ b/src/Avalonia.Controls/Primitives/PopupPositioning/CustomPopupPlacementCallback.cs @@ -0,0 +1,6 @@ +namespace Avalonia.Controls.Primitives.PopupPositioning; + +/// <summary> +/// Represents a method that provides custom positioning for a <see cref="Popup"/> control. +/// </summary> +public delegate void CustomPopupPlacementCallback(CustomPopupPlacement parameters); diff --git a/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs b/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs index 31c1e6054a4..a0b853f2dc8 100644 --- a/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs +++ b/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs @@ -45,6 +45,9 @@ DEALINGS IN THE SOFTWARE. */ using System; +using System.ComponentModel; +using System.Diagnostics; +using Avalonia.Diagnostics; using Avalonia.Input; using Avalonia.Metadata; using Avalonia.VisualTree; @@ -63,7 +66,7 @@ namespace Avalonia.Controls.Primitives.PopupPositioning /// requirement that a popup must intersect with or be at least partially adjacent to its parent /// surface. /// </remarks> - [Unstable] + [Unstable(ObsoletionMessages.MayBeRemovedInAvalonia12)] public record struct PopupPositionerParameters { private PopupGravity _gravity; @@ -443,19 +446,35 @@ public interface IPopupPositioner void Update(PopupPositionerParameters parameters); } - [Unstable] - static class PopupPositionerExtensions + internal static class PopupPositionerExtensions { - public static void ConfigurePosition(ref this PopupPositionerParameters positionerParameters, + public static void Update( + this IPopupPositioner positioner, TopLevel topLevel, - Visual target, PlacementMode placement, Point offset, - PopupAnchor anchor, PopupGravity gravity, - PopupPositionerConstraintAdjustment constraintAdjustment, Rect? rect, + PopupPositionRequest positionRequest, + Size popupSize, FlowDirection flowDirection) { - positionerParameters.Offset = offset; - positionerParameters.ConstraintAdjustment = constraintAdjustment; - if (placement == PlacementMode.Pointer) + if (popupSize == default) + { + return; + } + + var parameters = BuildParameters(topLevel, positionRequest, popupSize, flowDirection); + positioner.Update(parameters); + } + + private static PopupPositionerParameters BuildParameters( + TopLevel topLevel, + PopupPositionRequest positionRequest, + Size popupSize, + FlowDirection flowDirection) + { + PopupPositionerParameters positionerParameters = default; + positionerParameters.Offset = positionRequest.Offset; + positionerParameters.Size = popupSize; + positionerParameters.ConstraintAdjustment = positionRequest.ConstraintAdjustment; + if (positionRequest.Placement == PlacementMode.Pointer) { // We need a better way for tracking the last pointer position var position = topLevel.PointToClient(topLevel.LastPointerPosition ?? default); @@ -464,39 +483,45 @@ public static void ConfigurePosition(ref this PopupPositionerParameters position positionerParameters.Anchor = PopupAnchor.TopLeft; positionerParameters.Gravity = PopupGravity.BottomRight; } - else + else if (positionRequest.Placement == PlacementMode.Custom) { - if (target == null) - throw new InvalidOperationException("Placement mode is not Pointer and PlacementTarget is null"); - Matrix? matrix; - if (TryGetAdorner(target, out var adorned, out var adornerLayer)) - { - matrix = adorned!.TransformToVisual(topLevel) * target.TransformToVisual(adornerLayer!); - } - else - { - matrix = target.TransformToVisual(topLevel); - } + if (positionRequest.PlacementCallback is null) + throw new InvalidOperationException( + "CustomPopupPlacementCallback property must be set, when Placement=PlacementMode.Custom"); - if (matrix == null) + positionerParameters.AnchorRectangle = CalculateAnchorRect(topLevel, positionRequest); + + var customPlacementParameters = new CustomPopupPlacement( + popupSize, + positionRequest.Target) { - if (target.GetVisualRoot() == null) - throw new InvalidOperationException("Target control is not attached to the visual tree"); - throw new InvalidOperationException("Target control is not in the same tree as the popup parent"); - } + AnchorRectangle = positionerParameters.AnchorRectangle, + Anchor = positionerParameters.Anchor, + Gravity = positionerParameters.Gravity, + ConstraintAdjustment = positionerParameters.ConstraintAdjustment, + Offset = positionerParameters.Offset + }; - var bounds = new Rect(default, target.Bounds.Size); - var anchorRect = rect ?? bounds; - positionerParameters.AnchorRectangle = anchorRect.Intersect(bounds).TransformToAABB(matrix.Value); + positionRequest.PlacementCallback.Invoke(customPlacementParameters); - var parameters = placement switch + positionerParameters.AnchorRectangle = customPlacementParameters.AnchorRectangle; + positionerParameters.Anchor = customPlacementParameters.Anchor; + positionerParameters.Gravity = customPlacementParameters.Gravity; + positionerParameters.ConstraintAdjustment = customPlacementParameters.ConstraintAdjustment; + positionerParameters.Offset = customPlacementParameters.Offset; + } + else + { + positionerParameters.AnchorRectangle = CalculateAnchorRect(topLevel, positionRequest); + + var parameters = positionRequest.Placement switch { PlacementMode.Bottom => (PopupAnchor.Bottom, PopupGravity.Bottom), PlacementMode.Right => (PopupAnchor.Right, PopupGravity.Right), PlacementMode.Left => (PopupAnchor.Left, PopupGravity.Left), PlacementMode.Top => (PopupAnchor.Top, PopupGravity.Top), PlacementMode.Center => (PopupAnchor.None, PopupGravity.None), - PlacementMode.AnchorAndGravity => (anchor, gravity), + PlacementMode.AnchorAndGravity => (positionRequest.Anchor, positionRequest.Gravity), PlacementMode.TopEdgeAlignedRight => (PopupAnchor.TopRight, PopupGravity.TopLeft), PlacementMode.TopEdgeAlignedLeft => (PopupAnchor.TopLeft, PopupGravity.TopRight), PlacementMode.BottomEdgeAlignedLeft => (PopupAnchor.BottomLeft, PopupGravity.BottomRight), @@ -505,7 +530,7 @@ public static void ConfigurePosition(ref this PopupPositionerParameters position PlacementMode.LeftEdgeAlignedBottom => (PopupAnchor.BottomLeft, PopupGravity.TopLeft), PlacementMode.RightEdgeAlignedTop => (PopupAnchor.TopRight, PopupGravity.BottomRight), PlacementMode.RightEdgeAlignedBottom => (PopupAnchor.BottomRight, PopupGravity.TopRight), - _ => throw new ArgumentOutOfRangeException(nameof(placement), placement, + _ => throw new ArgumentOutOfRangeException(nameof(positionRequest.Placement), positionRequest.Placement, "Invalid value for Popup.PlacementMode") }; positionerParameters.Anchor = parameters.Item1; @@ -537,6 +562,35 @@ public static void ConfigurePosition(ref this PopupPositionerParameters position positionerParameters.Gravity |= PopupGravity.Right; } } + + return positionerParameters; + } + + private static Rect CalculateAnchorRect(TopLevel topLevel, PopupPositionRequest positionRequest) + { + var target = positionRequest.Target; + if (target == null) + throw new InvalidOperationException("Placement mode is not Pointer and PlacementTarget is null"); + Matrix? matrix; + if (TryGetAdorner(target, out var adorned, out var adornerLayer)) + { + matrix = adorned!.TransformToVisual(topLevel) * target.TransformToVisual(adornerLayer!); + } + else + { + matrix = target.TransformToVisual(topLevel); + } + + if (matrix == null) + { + if (target.GetVisualRoot() == null) + throw new InvalidOperationException("Target control is not attached to the visual tree"); + throw new InvalidOperationException("Target control is not in the same tree as the popup parent"); + } + + var bounds = new Rect(default, target.Bounds.Size); + var anchorRect = positionRequest.AnchorRect ?? bounds; + return anchorRect.Intersect(bounds).TransformToAABB(matrix.Value); } private static bool TryGetAdorner(Visual target, out Visual? adorned, out Visual? adornerLayer) diff --git a/src/Avalonia.Controls/Primitives/PopupPositioning/PopupPositionRequest.cs b/src/Avalonia.Controls/Primitives/PopupPositioning/PopupPositionRequest.cs new file mode 100644 index 00000000000..35e15e30570 --- /dev/null +++ b/src/Avalonia.Controls/Primitives/PopupPositioning/PopupPositionRequest.cs @@ -0,0 +1,35 @@ +using Avalonia.Diagnostics; +using Avalonia.Metadata; + +namespace Avalonia.Controls.Primitives.PopupPositioning; + +[PrivateApi] +[Unstable(ObsoletionMessages.MayBeRemovedInAvalonia12)] +public class PopupPositionRequest +{ + internal PopupPositionRequest(Visual target, PlacementMode placement) + { + Target = target; + Placement = placement; + } + + internal PopupPositionRequest(Visual target, PlacementMode placement, Point offset, PopupAnchor anchor, PopupGravity gravity, PopupPositionerConstraintAdjustment constraintAdjustment, Rect? anchorRect, CustomPopupPlacementCallback? placementCallback) + : this(target, placement) + { + Offset = offset; + Anchor = anchor; + Gravity = gravity; + ConstraintAdjustment = constraintAdjustment; + AnchorRect = anchorRect; + PlacementCallback = placementCallback; + } + + public Visual Target { get; } + public PlacementMode Placement {get;} + public Point Offset {get;} + public PopupAnchor Anchor {get;} + public PopupGravity Gravity {get;} + public PopupPositionerConstraintAdjustment ConstraintAdjustment {get;} + public Rect? AnchorRect {get;} + public CustomPopupPlacementCallback? PlacementCallback {get;} +} diff --git a/src/Avalonia.Controls/Primitives/PopupRoot.cs b/src/Avalonia.Controls/Primitives/PopupRoot.cs index 723bdca1b24..b2905b9176c 100644 --- a/src/Avalonia.Controls/Primitives/PopupRoot.cs +++ b/src/Avalonia.Controls/Primitives/PopupRoot.cs @@ -1,8 +1,10 @@ using System; using Avalonia.Automation.Peers; using Avalonia.Controls.Primitives.PopupPositioning; +using Avalonia.Diagnostics; using Avalonia.Interactivity; using Avalonia.Media; +using Avalonia.Metadata; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.VisualTree; @@ -26,7 +28,9 @@ public sealed class PopupRoot : WindowBase, IHostedVisualTreeRoot, IDisposable, public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty = Popup.WindowManagerAddShadowHintProperty.AddOwner<PopupRoot>(); - private PopupPositionerParameters _positionerParameters; + private PopupPositionRequest? _popupPositionRequest; + private Size _popupSize; + private bool _needsUpdate; /// <summary> /// Initializes static members of the <see cref="PopupRoot"/> class. @@ -124,20 +128,30 @@ public void Dispose() private void UpdatePosition() { - PlatformImpl?.PopupPositioner?.Update(_positionerParameters); + if (_needsUpdate && _popupPositionRequest is not null) + { + _needsUpdate = false; + PlatformImpl?.PopupPositioner? + .Update(ParentTopLevel, _popupPositionRequest, _popupSize, FlowDirection); + } } + [Unstable(ObsoletionMessages.MayBeRemovedInAvalonia12)] public void ConfigurePosition(Visual target, PlacementMode placement, Point offset, PopupAnchor anchor = PopupAnchor.None, PopupGravity gravity = PopupGravity.None, PopupPositionerConstraintAdjustment constraintAdjustment = PopupPositionerConstraintAdjustment.All, Rect? rect = null) { - _positionerParameters.ConfigurePosition(ParentTopLevel, target, - placement, offset, anchor, gravity, constraintAdjustment, rect, FlowDirection); + ((IPopupHost)this).ConfigurePosition(new PopupPositionRequest(target, placement, offset, anchor, gravity, + constraintAdjustment, rect, null)); + } - if (_positionerParameters.Size != default) - UpdatePosition(); + void IPopupHost.ConfigurePosition(PopupPositionRequest request) + { + _popupPositionRequest = request; + _needsUpdate = true; + UpdatePosition(); } public void SetChild(Control? control) => Content = control; @@ -184,10 +198,15 @@ protected override Size MeasureOverride(Size availableSize) return new Size(width, height); } - protected override sealed Size ArrangeSetBounds(Size size) + protected sealed override Size ArrangeSetBounds(Size size) { - _positionerParameters.Size = size; - UpdatePosition(); + if (_popupSize != size) + { + _popupSize = size; + _needsUpdate = true; + UpdatePosition(); + } + return ClientSize; } diff --git a/src/Avalonia.Controls/ToolTip.cs b/src/Avalonia.Controls/ToolTip.cs index 8bf0adedee5..fc8da13131a 100644 --- a/src/Avalonia.Controls/ToolTip.cs +++ b/src/Avalonia.Controls/ToolTip.cs @@ -4,6 +4,7 @@ using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; using Avalonia.Interactivity; +using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Reactive; using Avalonia.Styling; @@ -51,6 +52,10 @@ public class ToolTip : ContentControl, IPopupHostProvider public static readonly AttachedProperty<double> VerticalOffsetProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, double>("VerticalOffset", 20); + /// <inheritdoc cref="Popup.CustomPopupPlacementCallbackProperty"/> + public static readonly AttachedProperty<CustomPopupPlacementCallback?> CustomPopupPlacementCallbackProperty = + AvaloniaProperty.RegisterAttached<ToolTip, Control, CustomPopupPlacementCallback?>("CustomPopupPlacementCallback"); + /// <summary> /// Defines the ToolTip.ShowDelay property. /// </summary> @@ -327,6 +332,22 @@ public static void AddToolTipClosingHandler(Control element, EventHandler<Routed public static void RemoveToolTipClosingHandler(Control element, EventHandler<RoutedEventArgs> handler) => element.RemoveHandler(ToolTipClosingEvent, handler); + /// <summary> + /// Gets the value of the ToolTip.CustomPopupPlacementCallback attached property. + /// </summary> + public static CustomPopupPlacementCallback? GetCustomPopupPlacementCallback(Control element) + { + return element.GetValue(CustomPopupPlacementCallbackProperty); + } + + /// <summary> + /// Sets the value of the ToolTip.CustomPopupPlacementCallback attached property. + /// </summary> + public static void SetCustomPopupPlacementCallback(Control element, CustomPopupPlacementCallback? value) + { + element.SetValue(CustomPopupPlacementCallbackProperty, value); + } + private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; @@ -397,7 +418,8 @@ private void Open(Control control) { _popup.Bind(Popup.HorizontalOffsetProperty, control.GetBindingObservable(HorizontalOffsetProperty)), _popup.Bind(Popup.VerticalOffsetProperty, control.GetBindingObservable(VerticalOffsetProperty)), - _popup.Bind(Popup.PlacementProperty, control.GetBindingObservable(PlacementProperty)) + _popup.Bind(Popup.PlacementProperty, control.GetBindingObservable(PlacementProperty)), + _popup.Bind(Popup.CustomPopupPlacementCallbackProperty, control.GetBindingObservable(CustomPopupPlacementCallbackProperty)) }); _popup.PlacementTarget = control; @@ -415,14 +437,14 @@ private void Close() adornedControl.RaiseEvent(args); } - _subscriptions?.Dispose(); - if (_popup is not null) { _popup.IsOpen = false; _popup.SetPopupParent(null); _popup.PlacementTarget = null; } + + _subscriptions?.Dispose(); } private void OnPopupClosed(object? sender, EventArgs e)
diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs index fb88c983436..38bbc875c50 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/PopupRootTests.cs @@ -262,6 +262,7 @@ public void Should_Not_Have_Offset_On_Bounds_When_Content_Larger_Than_Max_Window var target = CreateTarget(window, popupImpl.Object); target.Content = child; + ((IPopupHost)target).ConfigurePosition(new PopupPositionRequest(window, PlacementMode.Top)); target.Show(); Assert.Equal(new Size(400, 1024), target.Bounds.Size); @@ -290,6 +291,7 @@ public void MinWidth_MinHeight_Should_Be_Respected() Height = 100, }; + ((IPopupHost)target).ConfigurePosition(new PopupPositionRequest(window, PlacementMode.Top)); target.Show(); Assert.Equal(new Rect(0, 0, 400, 800), target.Bounds); @@ -313,6 +315,7 @@ public void Setting_Width_Should_Resize_WindowImpl() target.Width = 400; target.Height = 800; + ((IPopupHost)target).ConfigurePosition(new PopupPositionRequest(window, PlacementMode.Top)); target.Show(); Assert.Equal(400, target.Width); diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs index e1ff48a3ccc..1cad1304af6 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs @@ -1206,6 +1206,50 @@ public void Popup_Attached_To_Adorner_Respects_Adorner_Position() } } + [Fact] + public void Custom_Placement_Callback_Is_Executed() + { + using (CreateServices()) + { + var callbackExecuted = 0; + var popupContent = new Border { Width = 100, Height = 100 }; + var popup = new Popup + { + Child = popupContent, + Placement = PlacementMode.Custom, + HorizontalOffset = 42, + VerticalOffset = 21 + }; + var popupParent = new Border { Child = popup }; + var root = PreparedWindow(popupParent); + + popup.CustomPopupPlacementCallback = (parameters) => + { + Assert.Equal(popupContent.Width, parameters.PopupSize.Width); + Assert.Equal(popupContent.Height, parameters.PopupSize.Height); + + Assert.Equal(root.Width, parameters.AnchorRectangle.Width); + Assert.Equal(root.Height, parameters.AnchorRectangle.Height); + + Assert.Equal(popup.HorizontalOffset, parameters.Offset.X); + Assert.Equal(popup.VerticalOffset, parameters.Offset.Y); + + callbackExecuted++; + + parameters.Anchor = PopupAnchor.Top; + parameters.Gravity = PopupGravity.Bottom; + }; + + root.LayoutManager.ExecuteInitialLayoutPass(); + popup.Open(); + root.LayoutManager.ExecuteLayoutPass(); + + // Ideally, callback should be executed only once for this test. + // But currently PlacementTargetLayoutUpdated triggers second update either way. + Assert.Equal(2, callbackExecuted); + } + } + private static PopupRoot CreateRoot(TopLevel popupParent, IPopupImpl impl = null) {
Add CustomPopupPlacementCallback support ### Is your feature request related to a problem? Please describe. WPF has a [CustomPopupPlacementCallback](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.custompopupplacementcallback?view=windowsdesktop-8.0) delegate that can be assigned to their [Popup](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.popup?view=windowsdesktop-8.0) and when `Popup.Placement == PlacementMode.Custom`, that delegate is used to supply dynamic options for placement via callback. The options are returned in an array of [CustomPopupPlacement](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.custompopupplacement?view=windowsdesktop-8.0) objects, and the one that appears first and allows the popup to fit best on screen is the one that is used. We have a requirement where an Avalonia `Control` that has a `ToolTip` needs to display that tip in a certain location relative to the target control. However, that relative location changes based on the current state of the target control and other controls around it at the time popup shows. Thus, we cannot use the simple `Placement` properties on `Popup` and need the use of a dynamic callback like in WPF to allow us to alter things on the fly. ### Describe the solution you'd like While we don't necessarily need the API to match WPF's `CustomPopupPlacementCallback` and `CustomPopupPlacement` exactly (they are slightly difficult to grasp when first learning them), we do need a callback function that can tell a popup like a `ToolTip` to display at some location relative to the target control. The Avalonia [Popup](https://github.com/AvaloniaUI/Avalonia/blob/master/src/Avalonia.Controls/Primitives/Popup.cs) already has some slight differences and enhancements over WPF popups, so we are happy to have a discussion on API implementation for this callback feature that would fit into the Avalonia model. ### Describe alternatives you've considered _No response_ ### Additional context _No response_
The API is designed to be Wayland-compatible and is designed against `xdg_positioner` object from `xdg-shell` protocol. Any placement API that requires access to global screen coordinates won't be Wayland-compatible. To position your popup relative to the top-left corner of a control use OffsetX/OffsetY properties with TopLeft anchor and BottomRight gravity. We can, however, introduce a callback that would allow to modify offset/anchor/gravity properties right before the popup is shown Just to clarify, the callback in WPF doesn't use screen coordinates. It is all coordinates relative to the target element. So a `(0,0)` placement value would mean upper left of the target control. The WPF callback allows us to look at things like target element size, popup size, and horizontal/vertical offsets, and then return target element-relative placement options. I would think that should be Wayland-compatible since it's not global screen coordinates. The WPF way would not make us alter the actual `HorizontalOffset` and `VerticalOffset` values since it expected the callback result's placements to specify a target element-relative location and axis. See the WPF [CustomPopupPlacement](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.custompopupplacement?view=windowsdesktop-8.0) for what the result there includes. Keep in mind that since it's using a `PlacementMode.Custom` setting for this, the `Placement` property is not even considered. --- I admittedly don't know the nuts and bolts of how Avalonia implemented popup positioning very well but when searching around, I happened to see a `PopupPositionerParameters` class, which looks like a promising possible result for a callback. If you guys are initializing a `PopupPositionerParameters` based on current props, what if we added a callback delegate property to `Popup` (or could be done via an event I suppose too) and if specified, it would pass in the `PopupPositionerParameters` you built but would allow us to tweak it further before it was actually used? The callback would need to have access to the target anchor element (to see it and its size), the popup (to see it and some of its properties). If we could alter the `PopupPositionerParameters` before it was used, that would allow us to dynamically change popup positioning based on the current state of the target element. And if the callback wasn't specified, or it did nothing in its logic, your current default positioning parameters would be used. Does that sound reasonable?
2024-05-09T13:46:13Z
0.1
['Avalonia.Controls.UnitTests.Primitives.PopupTestsWithPopupRoot.Popup_Attached_To_Adorner_Respects_Adorner_Position']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-15640
0d4fbe1880c201adb773c57c02ed5d7e81e7e653
diff --git a/src/Avalonia.Base/Data/Core/TargetTypeConverter.cs b/src/Avalonia.Base/Data/Core/TargetTypeConverter.cs index 2efc5b42bdc..57018bff55e 100644 --- a/src/Avalonia.Base/Data/Core/TargetTypeConverter.cs +++ b/src/Avalonia.Base/Data/Core/TargetTypeConverter.cs @@ -76,16 +76,32 @@ public override bool TryConvert(object? value, Type type, CultureInfo culture, o if (toTypeConverter.CanConvertFrom(from)) { - result = toTypeConverter.ConvertFrom(null, culture, value); - return true; + try + { + result = toTypeConverter.ConvertFrom(null, culture, value); + return true; + } + catch + { + result = null; + return false; + } } var fromTypeConverter = TypeDescriptor.GetConverter(from); if (fromTypeConverter.CanConvertTo(t)) { - result = fromTypeConverter.ConvertTo(null, culture, value, t); - return true; + try + { + result = fromTypeConverter.ConvertTo(null, culture, value, t); + return true; + } + catch + { + result = null; + return false; + } } // TODO: This requires reflection: we probably need to make compiled bindings emit @@ -95,8 +111,16 @@ public override bool TryConvert(object? value, Type type, CultureInfo culture, o t, OperatorType.Implicit | OperatorType.Explicit) is { } cast) { - result = cast.Invoke(null, new[] { value }); - return true; + try + { + result = cast.Invoke(null, new[] { value }); + return true; + } + catch + { + result = null; + return false; + } } #pragma warning restore IL2067 #pragma warning restore IL2026
diff --git a/tests/Avalonia.Controls.UnitTests/TextBoxTests_DataValidation.cs b/tests/Avalonia.Controls.UnitTests/TextBoxTests_DataValidation.cs index 295fc192d76..0eaa3092e98 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBoxTests_DataValidation.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBoxTests_DataValidation.cs @@ -6,8 +6,11 @@ using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; +using Avalonia.Data.Core; using Avalonia.Headless; using Avalonia.Markup.Data; +using Avalonia.Markup.Xaml.MarkupExtensions; +using Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings; using Avalonia.Platform; using Avalonia.UnitTests; using Moq; @@ -110,6 +113,40 @@ public void Setter_Exceptions_Should_Set_DataValidationErrors_HasErrors() } } + [Fact] + public void CompiledBindings_TypeConverter_Exceptions_Should_Set_DataValidationErrors_HasErrors() + { + var path = new CompiledBindingPathBuilder() + .Property( + new ClrPropertyInfo( + nameof(ExceptionTest.LessThan10), + target => ((ExceptionTest)target).LessThan10, + (target, value) => ((ExceptionTest)target).LessThan10 = (int)value, + typeof(int)), + PropertyInfoAccessorFactory.CreateInpcPropertyAccessor) + .Build(); + + using (UnitTestApplication.Start(Services)) + { + var target = new TextBox + { + DataContext = new ExceptionTest(), + [!TextBox.TextProperty] = new CompiledBindingExtension + { + Source = new ExceptionTest(), + Path = path, + Mode = BindingMode.TwoWay + }, + Template = CreateTemplate(), + }; + + target.ApplyTemplate(); + + target.Text = "a"; + Assert.True(DataValidationErrors.GetHasErrors(target)); + } + } + private static TestServices Services => TestServices.MockThreadingInterface.With( standardCursorFactory: Mock.Of<ICursorFactory>(), textShaperImpl: new HeadlessTextShaperStub(),
Regression: Exceptions thrown in TargetTypeConverter crash the app instead of going to the controls DataValidation ### Describe the bug Exceptions thrown in TargetTypeConverter crash the whole app, instead of being caught into control's Data Validation. ### To Reproduce ``` <TextBox Text="{CompiledBinding Value}" /> ``` where Value is an `int` - and type a letter. ``` Unhandled exception. System.ArgumentException: 0a is not a valid value for Int32. (Parameter 'value') ---> System.FormatException: The input string '0a' was not in a correct format. at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value) at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider) at System.ComponentModel.Int32Converter.FromString(String value, NumberFormatInfo formatInfo) at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) --- End of inner exception stack trace --- at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at Avalonia.Data.Core.TargetTypeConverter.DefaultConverter.TryConvert(Object value, Type type, CultureInfo culture, Object& result) at Avalonia.Data.Core.BindingExpression.WriteValueToSource(Object value) at Avalonia.Data.Core.BindingExpression.OnTargetPropertyChanged(Object sender, AvaloniaPropertyChangedEventArgs e) at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue) at Avalonia.PropertyStore.EffectiveValue`1.SetCurrentValueAndRaise(ValueStore owner, StyledProperty`1 property, T value) at Avalonia.PropertyStore.ValueStore.SetCurrentValue[T](StyledProperty`1 property, T value) at Avalonia.AvaloniaObject.SetCurrentValue[T](StyledProperty`1 property, T value) at Avalonia.Controls.TextBox.HandleTextInput(String input) at Avalonia.Controls.TextBox.OnTextInput(TextInputEventArgs e) at Avalonia.Input.InputElement.<>c.<.cctor>b__32_4(InputElement x, TextInputEventArgs e) at Avalonia.Reactive.LightweightObservableBase`1.PublishNext(T value) at Avalonia.Interactivity.RoutedEvent.InvokeRaised(Object sender, RoutedEventArgs e) at Avalonia.Interactivity.EventRoute.RaiseEventImpl(RoutedEventArgs e) at Avalonia.Interactivity.EventRoute.RaiseEvent(Interactive source, RoutedEventArgs e) at Avalonia.Interactivity.Interactive.RaiseEvent(RoutedEventArgs e) at Avalonia.Input.KeyboardDevice.ProcessRawEvent(RawInputEventArgs e) at Avalonia.Input.InputManager.ProcessInput(RawInputEventArgs e) at Avalonia.Controls.TopLevel.<>c.<HandleInput>b__141_0(Object state) at Avalonia.Threading.Dispatcher.Send(SendOrPostCallback action, Object arg, Nullable`1 priority) at Avalonia.Controls.TopLevel.HandleInput(RawInputEventArgs e) at Avalonia.Native.WindowBaseImpl.RawTextInputEvent(UInt64 timeStamp, String text) at Avalonia.Native.WindowBaseImpl.WindowBaseEvents.Avalonia.Native.Interop.IAvnWindowBaseEvents.RawTextInputEvent(UInt64 timeStamp, String text) at Avalonia.Native.Interop.Impl.__MicroComIAvnWindowBaseEventsVTable.RawTextInputEvent(Void* this, UInt64 timeStamp, Byte* text) --- End of stack trace from previous location --- at Avalonia.Native.DispatcherImpl.RunLoop(CancellationToken token) at Avalonia.Threading.DispatcherFrame.Run(IControlledDispatcherImpl impl) at Avalonia.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at Avalonia.Threading.Dispatcher.MainLoop(CancellationToken cancellationToken) at Avalonia.Controls.ApplicationLifetimes.ClassicDesktopStyleApplicationLifetime.Start(String[] args) at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime(AppBuilder builder, String[] args, Action`1 lifetimeBuilder) at AvaloniaBugs.Program.Main(String[] args) in /AvaloniaBugsAll/bug_type_converter/AvaloniaBugs/Program.cs:line 12 ``` or 1. `git clone https://github.com/BAndysc/avalonia-bugs-repro` 2. `git checkout bug_type_converter` 3. Run and type a letter ### Expected behavior No crash, like before binding refactor. ### Avalonia version 11.1-beta ### OS _No response_ ### Additional context _No response_
null
2024-05-07T09:11:37Z
0.1
['Avalonia.Controls.UnitTests.TextBoxTests_DataValidation.CompiledBindings_TypeConverter_Exceptions_Should_Set_DataValidationErrors_HasErrors']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-15423
d5ca06ff2432dcc4671a4ed795a5ce6a5cdadddc
diff --git a/src/Avalonia.ReactiveUI/ReactiveUserControl.cs b/src/Avalonia.ReactiveUI/ReactiveUserControl.cs index 94090f26141..76a4f29b161 100644 --- a/src/Avalonia.ReactiveUI/ReactiveUserControl.cs +++ b/src/Avalonia.ReactiveUI/ReactiveUserControl.cs @@ -48,14 +48,15 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang if (change.Property == DataContextProperty) { - if (Object.ReferenceEquals(change.OldValue, ViewModel)) + if (ReferenceEquals(change.OldValue, ViewModel) + && change.NewValue is null or TViewModel) { SetCurrentValue(ViewModelProperty, change.NewValue); } } else if (change.Property == ViewModelProperty) { - if (Object.ReferenceEquals(change.OldValue, DataContext)) + if (ReferenceEquals(change.OldValue, DataContext)) { SetCurrentValue(DataContextProperty, change.NewValue); } diff --git a/src/Avalonia.ReactiveUI/ReactiveWindow.cs b/src/Avalonia.ReactiveUI/ReactiveWindow.cs index 727c22f0167..4048ef1e257 100644 --- a/src/Avalonia.ReactiveUI/ReactiveWindow.cs +++ b/src/Avalonia.ReactiveUI/ReactiveWindow.cs @@ -48,14 +48,15 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang if (change.Property == DataContextProperty) { - if (Object.ReferenceEquals(change.OldValue, ViewModel)) + if (ReferenceEquals(change.OldValue, ViewModel) + && change.NewValue is null or TViewModel) { SetCurrentValue(ViewModelProperty, change.NewValue); } } else if (change.Property == ViewModelProperty) { - if (Object.ReferenceEquals(change.OldValue, DataContext)) + if (ReferenceEquals(change.OldValue, DataContext)) { SetCurrentValue(DataContextProperty, change.NewValue); }
diff --git a/tests/Avalonia.ReactiveUI.UnitTests/ReactiveUserControlTest.cs b/tests/Avalonia.ReactiveUI.UnitTests/ReactiveUserControlTest.cs index 4bf999bed01..67790789e31 100644 --- a/tests/Avalonia.ReactiveUI.UnitTests/ReactiveUserControlTest.cs +++ b/tests/Avalonia.ReactiveUI.UnitTests/ReactiveUserControlTest.cs @@ -134,6 +134,22 @@ public void Should_Inherit_DataContext() Assert.Same(vm2, view.ViewModel); } + // https://github.com/AvaloniaUI/Avalonia/issues/15060 + [Fact] + public void Should_Not_Inherit_DataContext_Of_Wrong_Type() + { + var view = new ExampleView(); + var root = new TestRoot(view); + + Assert.Null(view.DataContext); + Assert.Null(view.ViewModel); + + root.DataContext = this; + + Assert.Same(this, view.DataContext); + Assert.Null(view.ViewModel); + } + [Fact] public void Should_Not_Overlap_Change_Notifications() {
Using ReactiveUserControl in XAML crashes the application ### Describe the bug Using any control that inherits from `ReactiveUsercontrol<T>` in XAML or code behind immediately crashes the application if `DataContext` is set on a parent control and the data object cannot be cast to `T`. <details> <summary>Stack trace</summary> <pre> System.ArgumentException: Invalid value for Property 'ViewModel': 'AvaloniaRxTest.ViewModels.MainWindowViewModel' (AvaloniaRxTest.ViewModels.MainWindowViewModel) at Avalonia.StyledProperty`1.ShouldSetValue(AvaloniaObject target, Object value, TValue& converted) at Avalonia.StyledProperty`1.RouteSetCurrentValue(AvaloniaObject target, Object value) at Avalonia.AvaloniaObject.SetCurrentValue(AvaloniaProperty property, Object value) at Avalonia.ReactiveUI.ReactiveUserControl`1.OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) at Avalonia.AvaloniaObject.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change) at Avalonia.Animation.Animatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change) at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue) at Avalonia.PropertyStore.ValueStore.OnAncestorInheritedValueChanged[T](StyledProperty`1 property, T oldValue, T newValue) at Avalonia.PropertyStore.ValueStore.OnInheritedEffectiveValueChanged[T](StyledProperty`1 property, T oldValue, EffectiveValue`1 value) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(ValueStore owner, StyledProperty`1 property, T value) at Avalonia.PropertyStore.ValueStore.SetLocalValue[T](StyledProperty`1 property, T value) at Avalonia.PropertyStore.ValueStore.SetValue[T](StyledProperty`1 property, T value, BindingPriority priority) at Avalonia.AvaloniaObject.SetValue[T](StyledProperty`1 property, T value, BindingPriority priority) at Avalonia.StyledElement.set_DataContext(Object value) at AvaloniaRxTest.App.OnFrameworkInitializationCompleted() in C:\*\AvaloniaRxTest\App.axaml.cs:line 20 at Avalonia.AppBuilder.SetupUnsafe() at Avalonia.AppBuilder.Setup() at Avalonia.AppBuilder.SetupWithLifetime(IApplicationLifetime lifetime) at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime(AppBuilder builder, String[] args, Action`1 lifetimeBuilder) at AvaloniaRxTest.Program.Main(String[] args) in C:\*\AvaloniaRxTest\Program.cs:line 13 </pre> </details> ### To Reproduce 1. Start with Avalonia MVVM template: `dotnet new avalonia.mvvm` 2. Create a new view model and a `ReactiveUserControl` for it: ```cs public class ChildViewModel { } public class ChildView : ReactiveUserControl<ChildViewModel> { } ``` 3. Replace default `TextBlock` in _MainWindow.xaml_ with the new control: ```xml <!-- Other attributes are omitted for readability --> <Window xmlns:local="using:AvaloniaRxTest.Views"> <local:ChildView /> </Window> ``` 4. Update Avalonia packages to 11.1.0-beta1. 5. Debug the application and observe the crash. [AvaloniaRxTest.zip](https://github.com/AvaloniaUI/Avalonia/files/14672410/AvaloniaRxTest.zip) ### Expected behavior Application doesn't crash. ### Avalonia version 11.1.0-beta1 ### OS Windows ### Additional context Repro doesn't crash on Avalonia 11.0.10. Workaround for 11.1.0-beta1 is to "wrap" views that cause the crash in `ViewModelViewHost` but that implies a performance hit because view location is not free. #14477 seems to be where the bug was introduced but I can't say for sure because I can't get `git bisect` to work due to some funky issues with Git submodules.
Adding `&& typeof(TViewModel).IsAssignableFrom(change.NewValue)` here should fix it: https://github.com/AvaloniaUI/Avalonia/blob/bad2e8dbdcd3bd4ffd75a35fe94c20ff8ca2b880/src/Avalonia.ReactiveUI/ReactiveUserControl.cs#L51 The same fix should be applied to `ReactiveWindow`. It won't pass through converters, but I don't think that's needed here. why not just `change.NewValue is TViewModel` ? Because it can be `null`, but you're right, I think it can be `change.NewValue is null or TViewModel`, as the `ReferenceEquals` check ensures it's not a value type.
2024-04-18T01:19:23Z
0.1
['Avalonia.ReactiveUI.UnitTests.ReactiveUserControlTest.Should_Not_Inherit_DataContext_Of_Wrong_Type']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-14928
0b72cdb512187c8a4eded47e864e1194111e621f
diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml b/samples/ControlCatalog/Pages/ToolTipPage.xaml index 013c176bca5..fa40bc1a0fa 100644 --- a/samples/ControlCatalog/Pages/ToolTipPage.xaml +++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml @@ -5,10 +5,14 @@ Spacing="4"> <TextBlock Classes="h2">A control which pops up a hint when a control is hovered</TextBlock> - <Grid RowDefinitions="Auto,Auto,Auto" + <Grid RowDefinitions="Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,Auto" Margin="0,16,0,0" HorizontalAlignment="Center"> + <ToggleSwitch Margin="5" + HorizontalAlignment="Center" + IsChecked="{Binding Path=(ToolTip.ServiceEnabled), RelativeSource={RelativeSource AncestorType=UserControl}}" + Content="Enable ToolTip service" /> <Border Grid.Column="0" Grid.Row="1" Background="{DynamicResource SystemAccentColor}" @@ -21,6 +25,7 @@ Margin="5" Grid.Row="0" IsChecked="{Binding ElementName=Border, Path=(ToolTip.IsOpen)}" + HorizontalAlignment="Center" Content="ToolTip Open" /> <Border Name="Border" Grid.Column="1" @@ -38,7 +43,6 @@ <TextBlock>ToolTip bottom placement</TextBlock> </Border> <Border Grid.Row="2" - Grid.ColumnSpan="2" Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" @@ -62,6 +66,23 @@ </Border.Styles> <TextBlock>Moving offset</TextBlock> </Border> + + <Button Grid.Row="2" Grid.Column="1" + IsEnabled="False" + ToolTip.ShowOnDisabled="True" + ToolTip.Tip="This control is disabled" + Margin="5" + Padding="50"> + <TextBlock>ToolTip on a disabled control</TextBlock> + </Button> + + <Border Grid.Row="3" + Background="{DynamicResource SystemAccentColor}" + Margin="5" + Padding="50" + ToolTip.Tip="Outer tooltip"> + <TextBlock Background="{StaticResource SystemAccentColorDark1}" Padding="10" ToolTip.Tip="Inner tooltip" VerticalAlignment="Center">Nested ToolTips</TextBlock> + </Border> </Grid> </StackPanel> </UserControl> diff --git a/src/Avalonia.Base/Input/InputExtensions.cs b/src/Avalonia.Base/Input/InputExtensions.cs index 73dcef9e95a..a5107588c9e 100644 --- a/src/Avalonia.Base/Input/InputExtensions.cs +++ b/src/Avalonia.Base/Input/InputExtensions.cs @@ -13,36 +13,45 @@ namespace Avalonia.Input public static class InputExtensions { private static readonly Func<Visual, bool> s_hitTestDelegate = IsHitTestVisible; + private static readonly Func<Visual, bool> s_hitTestEnabledOnlyDelegate = IsHitTestVisible_EnabledOnly; /// <summary> /// Returns the active input elements at a point on an <see cref="IInputElement"/>. /// </summary> /// <param name="element">The element to test.</param> /// <param name="p">The point on <paramref name="element"/>.</param> + /// <param name="enabledElementsOnly">Whether to only return elements for which <see cref="IInputElement.IsEffectivelyEnabled"/> is true.</param> /// <returns> /// The active input elements found at the point, ordered topmost first. /// </returns> - public static IEnumerable<IInputElement> GetInputElementsAt(this IInputElement element, Point p) + public static IEnumerable<IInputElement> GetInputElementsAt(this IInputElement element, Point p, bool enabledElementsOnly = true) { element = element ?? throw new ArgumentNullException(nameof(element)); - return (element as Visual)?.GetVisualsAt(p, s_hitTestDelegate).Cast<IInputElement>() ?? + return (element as Visual)?.GetVisualsAt(p, enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate).Cast<IInputElement>() ?? Enumerable.Empty<IInputElement>(); } + + /// <inheritdoc cref="GetInputElementsAt(IInputElement, Point, bool)"/> + public static IEnumerable<IInputElement> GetInputElementsAt(this IInputElement element, Point p) => GetInputElementsAt(element, p, true); /// <summary> /// Returns the topmost active input element at a point on an <see cref="IInputElement"/>. /// </summary> /// <param name="element">The element to test.</param> /// <param name="p">The point on <paramref name="element"/>.</param> + /// <param name="enabledElementsOnly">Whether to only return elements for which <see cref="IInputElement.IsEffectivelyEnabled"/> is true.</param> /// <returns>The topmost <see cref="IInputElement"/> at the specified position.</returns> - public static IInputElement? InputHitTest(this IInputElement element, Point p) + public static IInputElement? InputHitTest(this IInputElement element, Point p, bool enabledElementsOnly = true) { element = element ?? throw new ArgumentNullException(nameof(element)); - return (element as Visual)?.GetVisualAt(p, s_hitTestDelegate) as IInputElement; + return (element as Visual)?.GetVisualAt(p, enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate) as IInputElement; } + /// <inheritdoc cref="InputHitTest(IInputElement, Point, bool)"/> + public static IInputElement? InputHitTest(this IInputElement element, Point p) => InputHitTest(element, p, true); + /// <summary> /// Returns the topmost active input element at a point on an <see cref="IInputElement"/>. /// </summary> @@ -52,26 +61,26 @@ public static IEnumerable<IInputElement> GetInputElementsAt(this IInputElement e /// A filter predicate. If the predicate returns false then the visual and all its /// children will be excluded from the results. /// </param> + /// <param name="enabledElementsOnly">Whether to only return elements for which <see cref="IInputElement.IsEffectivelyEnabled"/> is true.</param> /// <returns>The topmost <see cref="IInputElement"/> at the specified position.</returns> public static IInputElement? InputHitTest( this IInputElement element, Point p, - Func<Visual, bool> filter) + Func<Visual, bool> filter, + bool enabledElementsOnly = true) { element = element ?? throw new ArgumentNullException(nameof(element)); filter = filter ?? throw new ArgumentNullException(nameof(filter)); + var hitTestDelegate = enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate; - return (element as Visual)?.GetVisualAt(p, x => s_hitTestDelegate(x) && filter(x)) as IInputElement; + return (element as Visual)?.GetVisualAt(p, x => hitTestDelegate(x) && filter(x)) as IInputElement; } - private static bool IsHitTestVisible(Visual visual) - { - var element = visual as IInputElement; - return element != null && - visual.IsVisible && - element.IsHitTestVisible && - element.IsEffectivelyEnabled && - visual.IsAttachedToVisualTree; - } + /// <inheritdoc cref="InputHitTest(IInputElement, Point, Func{Visual, bool}, bool)"/> + public static IInputElement? InputHitTest(this IInputElement element, Point p, Func<Visual, bool> filter) => InputHitTest(element, p, filter, true); + + private static bool IsHitTestVisible(Visual visual) => visual is { IsVisible: true, IsAttachedToVisualTree: true } and IInputElement { IsHitTestVisible: true }; + + private static bool IsHitTestVisible_EnabledOnly(Visual visual) => IsHitTestVisible(visual) && visual is IInputElement { IsEffectivelyEnabled: true }; } } diff --git a/src/Avalonia.Base/Input/MouseDevice.cs b/src/Avalonia.Base/Input/MouseDevice.cs index 0cabf02566a..b97036c7ddf 100644 --- a/src/Avalonia.Base/Input/MouseDevice.cs +++ b/src/Avalonia.Base/Input/MouseDevice.cs @@ -75,9 +75,9 @@ private void ProcessRawEvent(RawPointerEventArgs e) case RawPointerEventType.XButton1Down: case RawPointerEventType.XButton2Down: if (ButtonCount(props) > 1) - e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult); + e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult.firstEnabledAncestor); else - e.Handled = MouseDown(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult); + e.Handled = MouseDown(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.LeftButtonUp: case RawPointerEventType.RightButtonUp: @@ -85,24 +85,24 @@ private void ProcessRawEvent(RawPointerEventArgs e) case RawPointerEventType.XButton1Up: case RawPointerEventType.XButton2Up: if (ButtonCount(props) != 0) - e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult); + e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult.firstEnabledAncestor); else - e.Handled = MouseUp(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult); + e.Handled = MouseUp(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Move: - e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult); + e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.IntermediatePoints, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Wheel: - e.Handled = MouseWheel(mouse, e.Timestamp, e.Root, e.Position, props, ((RawMouseWheelEventArgs)e).Delta, keyModifiers, e.InputHitTestResult); + e.Handled = MouseWheel(mouse, e.Timestamp, e.Root, e.Position, props, ((RawMouseWheelEventArgs)e).Delta, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Magnify: - e.Handled = GestureMagnify(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult); + e.Handled = GestureMagnify(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Rotate: - e.Handled = GestureRotate(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult); + e.Handled = GestureRotate(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Swipe: - e.Handled = GestureSwipe(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult); + e.Handled = GestureSwipe(mouse, e.Timestamp, e.Root, e.Position, props, ((RawPointerGestureEventArgs)e).Delta, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; } } diff --git a/src/Avalonia.Base/Input/PenDevice.cs b/src/Avalonia.Base/Input/PenDevice.cs index 7637de05acc..128a49e13b9 100644 --- a/src/Avalonia.Base/Input/PenDevice.cs +++ b/src/Avalonia.Base/Input/PenDevice.cs @@ -64,17 +64,17 @@ private void ProcessRawEvent(RawPointerEventArgs e) shouldReleasePointer = true; break; case RawPointerEventType.LeftButtonDown: - e.Handled = PenDown(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult); + e.Handled = PenDown(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.LeftButtonUp: if (_releasePointerOnPenUp) { shouldReleasePointer = true; } - e.Handled = PenUp(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult); + e.Handled = PenUp(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult.firstEnabledAncestor); break; case RawPointerEventType.Move: - e.Handled = PenMove(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult, e.IntermediatePoints); + e.Handled = PenMove(pointer, e.Timestamp, e.Root, e.Position, props, keyModifiers, e.InputHitTestResult.firstEnabledAncestor, e.IntermediatePoints); break; } } diff --git a/src/Avalonia.Base/Input/PointerOverPreProcessor.cs b/src/Avalonia.Base/Input/PointerOverPreProcessor.cs index 347ba35a411..d5a716ba602 100644 --- a/src/Avalonia.Base/Input/PointerOverPreProcessor.cs +++ b/src/Avalonia.Base/Input/PointerOverPreProcessor.cs @@ -67,7 +67,7 @@ public void OnNext(RawInputEventArgs value) else if (pointerDevice.TryGetPointer(args) is { } pointer && pointer.Type != PointerType.Touch) { - var element = pointer.Captured ?? args.InputHitTestResult; + var element = pointer.Captured ?? args.InputHitTestResult.firstEnabledAncestor; SetPointerOver(pointer, args.Root, element, args.Timestamp, args.Position, new PointerPointProperties(args.InputModifiers, args.Type.ToUpdateKind()), diff --git a/src/Avalonia.Base/Input/Raw/RawPointerEventArgs.cs b/src/Avalonia.Base/Input/Raw/RawPointerEventArgs.cs index 595f4c0c661..1a13d371126 100644 --- a/src/Avalonia.Base/Input/Raw/RawPointerEventArgs.cs +++ b/src/Avalonia.Base/Input/Raw/RawPointerEventArgs.cs @@ -123,7 +123,7 @@ public Point Position /// </summary> public Lazy<IReadOnlyList<RawPointerPoint>?>? IntermediatePoints { get; set; } - internal IInputElement? InputHitTestResult { get; set; } + internal (IInputElement? element, IInputElement? firstEnabledAncestor) InputHitTestResult { get; set; } } [PrivateApi] diff --git a/src/Avalonia.Base/Input/TouchDevice.cs b/src/Avalonia.Base/Input/TouchDevice.cs index 04c444f441a..026af11b058 100644 --- a/src/Avalonia.Base/Input/TouchDevice.cs +++ b/src/Avalonia.Base/Input/TouchDevice.cs @@ -44,14 +44,14 @@ public void ProcessRawEvent(RawInputEventArgs ev) { if (args.Type == RawPointerEventType.TouchEnd) return; - var hit = args.InputHitTestResult; + var hit = args.InputHitTestResult.firstEnabledAncestor; _pointers[args.RawPointerId] = pointer = new Pointer(Pointer.GetNextFreeId(), PointerType.Touch, _pointers.Count == 0); pointer.Capture(hit); } - var target = pointer.Captured ?? args.InputHitTestResult ?? args.Root; + var target = pointer.Captured ?? args.InputHitTestResult.firstEnabledAncestor ?? args.Root; var gestureTarget = pointer.CapturedGestureRecognizer?.Target; var updateKind = args.Type.ToUpdateKind(); var keyModifier = args.InputModifiers.ToKeyModifiers(); diff --git a/src/Avalonia.Base/Rendering/IRenderer.cs b/src/Avalonia.Base/Rendering/IRenderer.cs index 227ff538971..bd5aff8e6be 100644 --- a/src/Avalonia.Base/Rendering/IRenderer.cs +++ b/src/Avalonia.Base/Rendering/IRenderer.cs @@ -87,7 +87,7 @@ public interface IHitTester /// children will be excluded from the results. /// </param> /// <returns>The visuals at the specified point, topmost first.</returns> - IEnumerable<Visual> HitTest(Point p, Visual root, Func<Visual, bool> filter); + IEnumerable<Visual> HitTest(Point p, Visual root, Func<Visual, bool>? filter); /// <summary> /// Hit tests a location to find first visual at the specified point. @@ -99,6 +99,6 @@ public interface IHitTester /// children will be excluded from the results. /// </param> /// <returns>The visual at the specified point, topmost first.</returns> - Visual? HitTestFirst(Point p, Visual root, Func<Visual, bool> filter); + Visual? HitTestFirst(Point p, Visual root, Func<Visual, bool>? filter); } } diff --git a/src/Avalonia.Controls/Application.cs b/src/Avalonia.Controls/Application.cs index 6b8ddc15eaa..e48711efdb4 100644 --- a/src/Avalonia.Controls/Application.cs +++ b/src/Avalonia.Controls/Application.cs @@ -268,6 +268,7 @@ public virtual void RegisterServices() .Bind<IThemeVariantHost>().ToConstant(this) .Bind<IFocusManager>().ToConstant(focusManager) .Bind<IInputManager>().ToConstant(InputManager) + .Bind< IToolTipService>().ToConstant(new ToolTipService(InputManager)) .Bind<IKeyboardNavigationHandler>().ToTransient<KeyboardNavigationHandler>() .Bind<IDragDropDevice>().ToConstant(DragDropDevice.Instance); diff --git a/src/Avalonia.Controls/IToolTipService.cs b/src/Avalonia.Controls/IToolTipService.cs new file mode 100644 index 00000000000..31884348502 --- /dev/null +++ b/src/Avalonia.Controls/IToolTipService.cs @@ -0,0 +1,9 @@ +using Avalonia.Metadata; + +namespace Avalonia.Controls; + +[Unstable, PrivateApi] +internal interface IToolTipService +{ + void Update(Visual? candidateToolTipHost); +} diff --git a/src/Avalonia.Controls/ToolTip.cs b/src/Avalonia.Controls/ToolTip.cs index 8e0ca62131d..85362258eb3 100644 --- a/src/Avalonia.Controls/ToolTip.cs +++ b/src/Avalonia.Controls/ToolTip.cs @@ -55,6 +55,18 @@ public class ToolTip : ContentControl, IPopupHostProvider public static readonly AttachedProperty<int> ShowDelayProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, int>("ShowDelay", 400); + /// <summary> + /// Defines the ToolTip.ShowOnDisabled property. + /// </summary> + public static readonly AttachedProperty<bool> ShowOnDisabledProperty = + AvaloniaProperty.RegisterAttached<ToolTip, Control, bool>("ShowOnDisabled", defaultValue: false, inherits: true); + + /// <summary> + /// Defines the ToolTip.ServiceEnabled property. + /// </summary> + public static readonly AttachedProperty<bool> ServiceEnabledProperty = + AvaloniaProperty.RegisterAttached<ToolTip, Control, bool>("ServiceEnabled", defaultValue: true, inherits: true); + /// <summary> /// Stores the current <see cref="ToolTip"/> instance in the control. /// </summary> @@ -69,8 +81,6 @@ public class ToolTip : ContentControl, IPopupHostProvider /// </summary> static ToolTip() { - TipProperty.Changed.Subscribe(ToolTipService.Instance.TipChanged); - IsOpenProperty.Changed.Subscribe(ToolTipService.Instance.TipOpenChanged); IsOpenProperty.Changed.Subscribe(IsOpenChanged); HorizontalOffsetProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); @@ -213,6 +223,36 @@ public static void SetShowDelay(Control element, int value) element.SetValue(ShowDelayProperty, value); } + /// <summary> + /// Gets whether a control will display a tooltip even if it disabled. + /// </summary> + /// <param name="element">The control to get the property from.</param> + public static bool GetShowOnDisabled(Control element) => + element.GetValue(ShowOnDisabledProperty); + + /// <summary> + /// Sets whether a control will display a tooltip even if it disabled. + /// </summary> + /// <param name="element">The control to get the property from.</param> + /// <param name="value">Whether the control is to display a tooltip even if it disabled.</param> + public static void SetShowOnDisabled(Control element, bool value) => + element.SetValue(ShowOnDisabledProperty, value); + + /// <summary> + /// Gets whether showing and hiding of a control's tooltip will be automatically controlled by Avalonia. + /// </summary> + /// <param name="element">The control to get the property from.</param> + public static bool GetServiceEnabled(Control element) => + element.GetValue(ServiceEnabledProperty); + + /// <summary> + /// Sets whether showing and hiding of a control's tooltip will be automatically controlled by Avalonia. + /// </summary> + /// <param name="element">The control to get the property from.</param> + /// <param name="value">Whether the control is to display a tooltip even if it disabled.</param> + public static void SetServiceEnabled(Control element, bool value) => + element.SetValue(ServiceEnabledProperty, value); + private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; diff --git a/src/Avalonia.Controls/ToolTipService.cs b/src/Avalonia.Controls/ToolTipService.cs index 9e75026d791..77e314e52dd 100644 --- a/src/Avalonia.Controls/ToolTipService.cs +++ b/src/Avalonia.Controls/ToolTipService.cs @@ -1,6 +1,7 @@ using System; using Avalonia.Input; -using Avalonia.Interactivity; +using Avalonia.Input.Raw; +using Avalonia.Reactive; using Avalonia.Threading; namespace Avalonia.Controls @@ -8,44 +9,95 @@ namespace Avalonia.Controls /// <summary> /// Handles <see cref="ToolTip"/> interaction with controls. /// </summary> - internal sealed class ToolTipService + internal sealed class ToolTipService : IToolTipService, IDisposable { - public static ToolTipService Instance { get; } = new ToolTipService(); + private readonly IDisposable _subscriptions; + private Control? _tipControl; private DispatcherTimer? _timer; - private ToolTipService() { } + public ToolTipService(IInputManager inputManager) + { + _subscriptions = new CompositeDisposable( + inputManager.Process.Subscribe(InputManager_OnProcess), + ToolTip.ServiceEnabledProperty.Changed.Subscribe(ServiceEnabledChanged), + ToolTip.TipProperty.Changed.Subscribe(TipChanged), + ToolTip.IsOpenProperty.Changed.Subscribe(TipOpenChanged)); + } - /// <summary> - /// called when the <see cref="ToolTip.TipProperty"/> property changes on a control. - /// </summary> - /// <param name="e">The event args.</param> - internal void TipChanged(AvaloniaPropertyChangedEventArgs e) + public void Dispose() => _subscriptions.Dispose(); + + private void InputManager_OnProcess(RawInputEventArgs e) { - var control = (Control)e.Sender; + if (e is RawPointerEventArgs pointerEvent) + { + switch (pointerEvent.Type) + { + case RawPointerEventType.Move: + Update(pointerEvent.InputHitTestResult.element as Visual); + break; + case RawPointerEventType.LeftButtonDown: + case RawPointerEventType.RightButtonDown: + case RawPointerEventType.MiddleButtonDown: + case RawPointerEventType.XButton1Down: + case RawPointerEventType.XButton2Down: + StopTimer(); + _tipControl?.ClearValue(ToolTip.IsOpenProperty); + break; + } + } + } - if (e.OldValue != null) + public void Update(Visual? candidateToolTipHost) + { + while (candidateToolTipHost != null) { - control.PointerEntered -= ControlPointerEntered; - control.PointerExited -= ControlPointerExited; - control.RemoveHandler(InputElement.PointerPressedEvent, ControlPointerPressed); + if (candidateToolTipHost is Control control) + { + if (!ToolTip.GetServiceEnabled(control)) + return; + + if (ToolTip.GetTip(control) != null && (control.IsEffectivelyEnabled || ToolTip.GetShowOnDisabled(control))) + break; + } + + candidateToolTipHost = candidateToolTipHost?.VisualParent; } - if (e.NewValue != null) + var newControl = candidateToolTipHost as Control; + + if (newControl == _tipControl) { - control.PointerEntered += ControlPointerEntered; - control.PointerExited += ControlPointerExited; - control.AddHandler(InputElement.PointerPressedEvent, ControlPointerPressed, - RoutingStrategies.Bubble | RoutingStrategies.Tunnel | RoutingStrategies.Direct, true); + return; } + OnTipControlChanged(_tipControl, newControl); + _tipControl = newControl; + } + + private void ServiceEnabledChanged(AvaloniaPropertyChangedEventArgs<bool> args) + { + if (args.Sender == _tipControl && !ToolTip.GetServiceEnabled(_tipControl)) + { + StopTimer(); + } + } + + /// <summary> + /// called when the <see cref="ToolTip.TipProperty"/> property changes on a control. + /// </summary> + /// <param name="e">The event args.</param> + private void TipChanged(AvaloniaPropertyChangedEventArgs e) + { + var control = (Control)e.Sender; + if (ToolTip.GetIsOpen(control) && e.NewValue != e.OldValue && !(e.NewValue is ToolTip)) { if (e.NewValue is null) { Close(control); } - else + else { if (control.GetValue(ToolTip.ToolTipProperty) is { } tip) { @@ -55,7 +107,7 @@ internal void TipChanged(AvaloniaPropertyChangedEventArgs e) } } - internal void TipOpenChanged(AvaloniaPropertyChangedEventArgs e) + private void TipOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; @@ -64,13 +116,13 @@ internal void TipOpenChanged(AvaloniaPropertyChangedEventArgs e) control.DetachedFromVisualTree += ControlDetaching; control.EffectiveViewportChanged += ControlEffectiveViewportChanged; } - else if(e.OldValue is true && e.NewValue is false) + else if (e.OldValue is true && e.NewValue is false) { control.DetachedFromVisualTree -= ControlDetaching; control.EffectiveViewportChanged -= ControlEffectiveViewportChanged; } } - + private void ControlDetaching(object? sender, VisualTreeAttachmentEventArgs e) { var control = (Control)sender!; @@ -79,49 +131,31 @@ private void ControlDetaching(object? sender, VisualTreeAttachmentEventArgs e) Close(control); } - /// <summary> - /// Called when the pointer enters a control with an attached tooltip. - /// </summary> - /// <param name="sender">The event sender.</param> - /// <param name="e">The event args.</param> - private void ControlPointerEntered(object? sender, PointerEventArgs e) + private void OnTipControlChanged(Control? oldValue, Control? newValue) { StopTimer(); - var control = (Control)sender!; - var showDelay = ToolTip.GetShowDelay(control); - if (showDelay == 0) + if (oldValue != null) { - Open(control); + // If the control is showing a tooltip and the pointer is over the tooltip, don't close it. + if (oldValue.GetValue(ToolTip.ToolTipProperty) is not { IsPointerOver: true }) + Close(oldValue); } - else + + if (newValue != null) { - StartShowTimer(showDelay, control); + var showDelay = ToolTip.GetShowDelay(newValue); + if (showDelay == 0) + { + Open(newValue); + } + else + { + StartShowTimer(showDelay, newValue); + } } } - /// <summary> - /// Called when the pointer leaves a control with an attached tooltip. - /// </summary> - /// <param name="sender">The event sender.</param> - /// <param name="e">The event args.</param> - private void ControlPointerExited(object? sender, PointerEventArgs e) - { - var control = (Control)sender!; - - // If the control is showing a tooltip and the pointer is over the tooltip, don't close it. - if (control.GetValue(ToolTip.ToolTipProperty) is { } tooltip && tooltip.IsPointerOver) - return; - - Close(control); - } - - private void ControlPointerPressed(object? sender, PointerPressedEventArgs e) - { - StopTimer(); - (sender as AvaloniaObject)?.ClearValue(ToolTip.IsOpenProperty); - } - private void ControlEffectiveViewportChanged(object? sender, Layout.EffectiveViewportChangedEventArgs e) { var control = (Control)sender!; @@ -140,11 +174,9 @@ private void ToolTipClosed(object? sender, EventArgs e) private void ToolTipPointerExited(object? sender, PointerEventArgs e) { - // The pointer has exited the tooltip. Close the tooltip unless the pointer is over the + // The pointer has exited the tooltip. Close the tooltip unless the current tooltip source is still the // adorned control. - if (sender is ToolTip toolTip && - toolTip.AdornedControl is { } control && - !control.IsPointerOver) + if (sender is ToolTip { AdornedControl: { } control } && control != _tipControl) { Close(control); } @@ -152,7 +184,7 @@ toolTip.AdornedControl is { } control && private void StartShowTimer(int showDelay, Control control) { - _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(showDelay) }; + _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(showDelay), Tag = (this, control) }; _timer.Tick += (o, e) => Open(control); _timer.Start(); } @@ -175,8 +207,6 @@ private void Open(Control control) private void Close(Control control) { - StopTimer(); - ToolTip.SetIsOpen(control, false); } diff --git a/src/Avalonia.Controls/TopLevel.cs b/src/Avalonia.Controls/TopLevel.cs index 70e531a7897..7fcbd544e9e 100644 --- a/src/Avalonia.Controls/TopLevel.cs +++ b/src/Avalonia.Controls/TopLevel.cs @@ -122,6 +122,7 @@ private static readonly WeakEvent<IResourceHost, ResourcesChangedEventArgs> ); private readonly IInputManager? _inputManager; + private readonly IToolTipService? _tooltipService; private readonly IAccessKeyHandler? _accessKeyHandler; private readonly IKeyboardNavigationHandler? _keyboardNavigationHandler; private readonly IGlobalStyles? _globalStyles; @@ -182,6 +183,8 @@ static TopLevel() newInputElement.PropertyChanged += topLevel.PointerOverElementOnPropertyChanged; } }); + + ToolTip.ServiceEnabledProperty.Changed.Subscribe(OnToolTipServiceEnabledChanged); } /// <summary> @@ -211,6 +214,7 @@ public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver? dependencyResol _accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver); _inputManager = TryGetService<IInputManager>(dependencyResolver); + _tooltipService = TryGetService<IToolTipService>(dependencyResolver); _keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver); _globalStyles = TryGetService<IGlobalStyles>(dependencyResolver); _applicationThemeHost = TryGetService<IThemeVariantHost>(dependencyResolver); @@ -833,7 +837,9 @@ private void HandleInput(RawInputEventArgs e) var (topLevel, e) = (ValueTuple<TopLevel, RawInputEventArgs>)state!; if (e is RawPointerEventArgs pointerArgs) { - pointerArgs.InputHitTestResult = topLevel.InputHitTest(pointerArgs.Position); + var hitTestElement = topLevel.InputHitTest(pointerArgs.Position, enabledElementsOnly: false); + + pointerArgs.InputHitTestResult = (hitTestElement, FirstEnabledAncestor(hitTestElement)); } topLevel._inputManager?.ProcessInput(e); @@ -847,6 +853,17 @@ private void HandleInput(RawInputEventArgs e) } } + private static IInputElement? FirstEnabledAncestor(IInputElement? hitTestElement) + { + var candidate = hitTestElement; + while (candidate?.IsEffectivelyEnabled == false) + { + candidate = (candidate as Visual)?.Parent as IInputElement; + } + + return candidate; + } + private void PointerOverElementOnPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (e.Property == CursorProperty && sender is InputElement inputElement) @@ -863,6 +880,30 @@ private void GlobalActualThemeVariantChanged(object? sender, EventArgs e) private void SceneInvalidated(object? sender, SceneInvalidatedEventArgs e) { _pointerOverPreProcessor?.SceneInvalidated(e.DirtyRect); + UpdateToolTip(e.DirtyRect); + } + + private static void OnToolTipServiceEnabledChanged(AvaloniaPropertyChangedEventArgs<bool> args) + { + if (args.GetNewValue<bool>() + && args.Priority != BindingPriority.Inherited + && args.Sender is Visual visual + && GetTopLevel(visual) is { } topLevel) + { + topLevel.UpdateToolTip(visual.Bounds.Translate((Vector)visual.TranslatePoint(default, topLevel)!)); + } + } + + private void UpdateToolTip(Rect dirtyRect) + { + if (_tooltipService != null && _pointerOverPreProcessor?.LastPosition is { } lastPos) + { + var clientPoint = this.PointToClient(lastPos); + if (dirtyRect.Contains(clientPoint)) + { + _tooltipService.Update(HitTester.HitTestFirst(clientPoint, this, null)); + } + } } void PlatformImpl_LostFocus()
diff --git a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs index 98a131752a4..ddfc2b7b722 100644 --- a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs @@ -1,45 +1,26 @@ using System; -using System.Reactive.Disposables; -using Avalonia.Markup.Xaml; -using Avalonia.Platform; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Avalonia.Data; +using Avalonia.Input; +using Avalonia.Input.Raw; +using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.UnitTests; -using Avalonia.Utilities; -using Avalonia.VisualTree; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { - public class TolTipTests + public class ToolTipTests { - private MouseTestHelper _mouseHelper = new MouseTestHelper(); + private static readonly MouseDevice s_mouseDevice = new(new Pointer(0, PointerType.Mouse, true)); - [Fact] - public void Should_Not_Open_On_Detached_Control() - { - //issue #3188 - var control = new Decorator() - { - [ToolTip.TipProperty] = "Tip", - [ToolTip.ShowDelayProperty] = 0 - }; - - Assert.False(control.IsAttachedToVisualTree); - - //here in issue #3188 exception is raised - _mouseHelper.Enter(control); - - Assert.False(ToolTip.GetIsOpen(control)); - } - [Fact] public void Should_Close_When_Control_Detaches() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var panel = new Panel(); var target = new Decorator() @@ -50,15 +31,7 @@ public void Should_Close_When_Control_Detaches() panel.Children.Add(target); - window.Content = panel; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); - - Assert.True(target.IsAttachedToVisualTree); - - _mouseHelper.Enter(target); + SetupWindowAndActivateToolTip(panel, target); Assert.True(ToolTip.GetIsOpen(target)); @@ -71,27 +44,22 @@ public void Should_Close_When_Control_Detaches() [Fact] public void Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var xaml = @" -<Window xmlns='https://github.com/avaloniaui' - xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> - <Panel x:Name='PART_panel'> - <Decorator x:Name='PART_target' ToolTip.Tip='{Binding Tip}' ToolTip.ShowDelay='0' /> - </Panel> -</Window>"; - var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); - - window.DataContext = new ToolTipViewModel(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); + var target = new Decorator + { + [!ToolTip.TipProperty] = new Binding("Tip"), + [ToolTip.ShowDelayProperty] = 0, + }; - var target = window.Find<Decorator>("PART_target"); - var panel = window.Find<Panel>("PART_panel"); - - Assert.True(target.IsAttachedToVisualTree); + var panel = new Panel(); + panel.Children.Add(target); + + var mouseEnter = SetupWindowAndGetMouseEnterAction(panel); - _mouseHelper.Enter(target); + panel.DataContext = new ToolTipViewModel(); + + mouseEnter(target); Assert.True(ToolTip.GetIsOpen(target)); @@ -104,25 +72,15 @@ public void Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree() [Fact] public void Should_Open_On_Pointer_Enter() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 0 }; - window.Content = target; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); - - Assert.True(target.IsAttachedToVisualTree); - - _mouseHelper.Enter(target); + SetupWindowAndActivateToolTip(target); Assert.True(ToolTip.GetIsOpen(target)); } @@ -131,28 +89,19 @@ public void Should_Open_On_Pointer_Enter() [Fact] public void Content_Should_Update_When_Tip_Property_Changes_And_Already_Open() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 0 }; - window.Content = target; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); - - _mouseHelper.Enter(target); + SetupWindowAndActivateToolTip(target); Assert.True(ToolTip.GetIsOpen(target)); Assert.Equal("Tip", target.GetValue(ToolTip.ToolTipProperty).Content); - ToolTip.SetTip(target, "Tip1"); Assert.Equal("Tip1", target.GetValue(ToolTip.ToolTipProperty).Content); } @@ -161,25 +110,15 @@ public void Content_Should_Update_When_Tip_Property_Changes_And_Already_Open() [Fact] public void Should_Open_On_Pointer_Enter_With_Delay() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 1 }; - window.Content = target; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); - - Assert.True(target.IsAttachedToVisualTree); - - _mouseHelper.Enter(target); + SetupWindowAndActivateToolTip(target); var timer = Assert.Single(Dispatcher.SnapshotTimersForUnitTests()); Assert.Equal(TimeSpan.FromMilliseconds(1), timer.Interval); @@ -268,23 +207,15 @@ public void Clearing_IsOpen_Should_Remove_Open_Class() [Fact] public void Should_Close_On_Null_Tip() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 0 }; - window.Content = target; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); - - _mouseHelper.Enter(target); + SetupWindowAndActivateToolTip(target); Assert.True(ToolTip.GetIsOpen(target)); @@ -297,28 +228,23 @@ public void Should_Close_On_Null_Tip() [Fact] public void Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 0 }; - window.Content = target; + var mouseEnter = SetupWindowAndGetMouseEnterAction(target); - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); + mouseEnter(target); - _mouseHelper.Enter(target); Assert.True(ToolTip.GetIsOpen(target)); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); - _mouseHelper.Enter(tooltip); - _mouseHelper.Leave(target); + + mouseEnter(tooltip); Assert.True(ToolTip.GetIsOpen(target)); } @@ -327,33 +253,25 @@ public void Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip() [Fact] public void Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Control() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", [ToolTip.ShowDelayProperty] = 0 }; - window.Content = target; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); + var mouseEnter = SetupWindowAndGetMouseEnterAction(target); - _mouseHelper.Enter(target); + mouseEnter(target); Assert.True(ToolTip.GetIsOpen(target)); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); - _mouseHelper.Enter(tooltip); - _mouseHelper.Leave(target); + mouseEnter(tooltip); Assert.True(ToolTip.GetIsOpen(target)); - _mouseHelper.Enter(target); - _mouseHelper.Leave(tooltip); + mouseEnter(target); Assert.True(ToolTip.GetIsOpen(target)); } @@ -362,10 +280,8 @@ public void Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Cont [Fact] public void Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control() { - using (UnitTestApplication.Start(TestServices.StyledWindow)) + using (UnitTestApplication.Start(TestServices.FocusableWindow)) { - var window = new Window(); - var target = new Decorator() { [ToolTip.TipProperty] = "Tip", @@ -379,27 +295,74 @@ public void Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control() Children = { target, other } }; - window.Content = panel; - - window.ApplyStyling(); - window.ApplyTemplate(); - window.Presenter.ApplyTemplate(); + var mouseEnter = SetupWindowAndGetMouseEnterAction(panel); - _mouseHelper.Enter(target); + mouseEnter(target); Assert.True(ToolTip.GetIsOpen(target)); var tooltip = Assert.IsType<ToolTip>(target.GetValue(ToolTip.ToolTipProperty)); - _mouseHelper.Enter(tooltip); - _mouseHelper.Leave(target); + mouseEnter(tooltip); Assert.True(ToolTip.GetIsOpen(target)); - _mouseHelper.Enter(other); - _mouseHelper.Leave(tooltip); + mouseEnter(other); Assert.False(ToolTip.GetIsOpen(target)); } } + + private Action<Control> SetupWindowAndGetMouseEnterAction(Control windowContent, [CallerMemberName] string testName = null) + { + var windowImpl = MockWindowingPlatform.CreateWindowMock(); + var hitTesterMock = new Mock<IHitTester>(); + + var window = new Window(windowImpl.Object) + { + HitTesterOverride = hitTesterMock.Object, + Content = windowContent, + Title = testName, + }; + + window.ApplyStyling(); + window.ApplyTemplate(); + window.Presenter.ApplyTemplate(); + window.Show(); + + Assert.True(windowContent.IsAttachedToVisualTree); + Assert.True(windowContent.IsMeasureValid); + Assert.True(windowContent.IsVisible); + + var controlIds = new Dictionary<Control, int>(); + + return control => + { + Point point; + + if (control == null) + { + point = default; + } + else + { + if (!controlIds.TryGetValue(control, out int id)) + { + id = controlIds[control] = controlIds.Count; + } + point = new Point(id, int.MaxValue); + } + + hitTesterMock.Setup(m => m.HitTestFirst(point, window, It.IsAny<Func<Visual, bool>>())) + .Returns(control); + + windowImpl.Object.Input(new RawPointerEventArgs(s_mouseDevice, (ulong)DateTime.Now.Ticks, window, + RawPointerEventType.Move, point, RawInputModifiers.None)); + + Assert.True(control == null || control.IsPointerOver); + }; + } + + private void SetupWindowAndActivateToolTip(Control windowContent, Control targetOverride = null, [CallerMemberName] string testName = null) => + SetupWindowAndGetMouseEnterAction(windowContent, testName)(targetOverride ?? windowContent); } internal class ToolTipViewModel diff --git a/tests/Avalonia.UnitTests/UnitTestApplication.cs b/tests/Avalonia.UnitTests/UnitTestApplication.cs index 18ccff75f0b..18b1bb64611 100644 --- a/tests/Avalonia.UnitTests/UnitTestApplication.cs +++ b/tests/Avalonia.UnitTests/UnitTestApplication.cs @@ -53,6 +53,8 @@ public static IDisposable Start(TestServices services = null) Dispatcher.UIThread.RunJobs(); } + ((ToolTipService)AvaloniaLocator.Current.GetService<IToolTipService>())?.Dispose(); + scope.Dispose(); Dispatcher.ResetForUnitTests(); SynchronizationContext.SetSynchronizationContext(oldContext); @@ -67,6 +69,7 @@ public override void RegisterServices() .Bind<IGlobalClock>().ToConstant(Services.GlobalClock) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) + .Bind<IToolTipService>().ToConstant(Services.InputManager == null ? null : new ToolTipService(Services.InputManager)) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToFunc(Services.KeyboardNavigation ?? (() => null))
Display ToolTip on Control with IsEnabled=False Right now it seems impossible to display a ToolTip properly if the control it's attached to isn't enabled. WPF has [ToolTipService.ShowOnDisabled](https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.tooltipservice.showondisabled?view=netcore-3.1) cibuild0006898
A little more complicated than it might seem because we rely on `PointerEnter` to show tooltips and that event isn't fired when a control is disabled. WPF hooks into the [global `InputManager`](https://github.com/dotnet/wpf/blob/4a3c96a6c6548c4d37ccdcbb44712ef3c147b58f/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/PopupControlService.cs#L35) to bypass this, we'd need to do something similar. This feature isn't available in UWP it seems. mmm, I think it's possible make a PseudoGlobalInputManager, getting the last window/control parent and getting its Pointer Events (I don't know if that is good for the performance/scalability). Are there any workarounds for this? I'm trying to show a tooltip for a disabled ListBoxItem. did anyone find a workaround for this? @jpgarza93 Here's an attached property workaround. It checks if an attached control is under the pointer from its `TopLevel` and if its disabled it'll show its tooltip. When none are under the pointer it'll clear any that were manually shown: ``` using Avalonia; using Avalonia.Controls; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.VisualTree; using System.Linq; using System.Reactive.Linq; namespace Example { public static class ShowDisabledTooltipExtension { #region Constructors static ShowDisabledTooltipExtension() { ShowOnDisabledProperty.Changed.AddClassHandler<Control>((x, y) => HandleShowOnDisabledChanged(x, y)); } #endregion #region Properties #region ShowOnDisabled AvaloniaProperty public static bool GetShowOnDisabled(AvaloniaObject obj) { return obj.GetValue(ShowOnDisabledProperty); } public static void SetShowOnDisabled(AvaloniaObject obj, bool value) { obj.SetValue(ShowOnDisabledProperty, value); } public static readonly AttachedProperty<bool> ShowOnDisabledProperty = AvaloniaProperty.RegisterAttached<object, Control, bool>( "ShowOnDisabled", false, false); private static void HandleShowOnDisabledChanged(Control control, AvaloniaPropertyChangedEventArgs e) { if (e.NewValue is bool isEnabledVal && isEnabledVal) { control.DetachedFromVisualTree += AttachedControl_DetachedFromVisualOrExtension; control.AttachedToVisualTree += AttachedControl_AttachedToVisualTree; if (control.IsInitialized) { // enabled after visual attached AttachedControl_AttachedToVisualTree(control, null); } } else { AttachedControl_DetachedFromVisualOrExtension(control, null); } } private static void AttachedControl_AttachedToVisualTree(object sender, VisualTreeAttachmentEventArgs e) { if (sender is not Control control) { return; } var tl = TopLevel.GetTopLevel(control); // NOTE pointermove needed to be tunneled for me but you may not need to... tl.AddHandler(TopLevel.PointerMovedEvent, TopLevel_PointerMoved, RoutingStrategies.Tunnel); } private static void AttachedControl_DetachedFromVisualOrExtension(object s, VisualTreeAttachmentEventArgs e) { if (s is not Control control) { return; } control.DetachedFromVisualTree -= AttachedControl_DetachedFromVisualOrExtension; control.AttachedToVisualTree -= AttachedControl_AttachedToVisualTree; if (TopLevel.GetTopLevel(control) is not TopLevel tl) { return; } tl.RemoveHandler(TopLevel.PointerMovedEvent, TopLevel_PointerMoved); } private static void TopLevel_PointerMoved(object sender, global::Avalonia.Input.PointerEventArgs e) { if (sender is not Control tl) { return; } var attached_controls = tl.GetVisualDescendants().Where(x => GetShowOnDisabled(x)).Cast<Control>(); // find disabled children under pointer w/ this extension enabled var disabled_child_under_pointer = attached_controls .FirstOrDefault(x => x.Bounds.Contains(e.GetPosition(x.Parent as Visual)) && x.IsEffectivelyVisible && !x.IsEnabled); if (disabled_child_under_pointer != null) { // manually show tooltip ToolTip.SetIsOpen(disabled_child_under_pointer, true); } var disabled_tooltips_to_hide = attached_controls .Where(x => ToolTip.GetIsOpen(x) && x != disabled_child_under_pointer && !x.IsEnabled); foreach (var dcst in disabled_tooltips_to_hide) { ToolTip.SetIsOpen(dcst, false); } } #endregion #endregion } } ``` To use just set `ShowOnDisabled` to `true` on the control with the tooltip. Example: ``` <Button local:ShowDisabledTooltipExtension.ShowOnDisabled="True" IsEnabled="False" Content="Test Button" ToolTip.Tip="Disabled tooltip" /> ``` > @jpgarza93 Here's an attached property workaround. It checks if an attached control is under the pointer from its `TopLevel` and if its disabled it'll show its tooltip. When none are under the pointer it'll clear any that were manually shown > Thank you for this @tkefauver!!! In my case, I had to change the two `!x.IsEnabled` lines to `!x.IsEffectivelyEnabled`. This is because I'm using the tooltip to show a user-facing explanation why the control is disabled (i.e. "you can't click this unless you've done this other thing first"), which comes from a bound custom command type, and when the control is disabled because a bound `ICommand`'s `CanExecute()` returned false, the control's `IsEnabled` stays true, but its `IsEffectivelyEnabled` becomes false. In case anyone wants to know how to do a command like that, here's the code: RelayCommandWithReason.cs: ``` csharp public interface IReportReasonCantExecute { string ReasonCantExecute { set; } } public class RelayCommandWithReason : IRelayCommand /* from CommunityToolkit.MVVM */, IReportReasonCantExecute, INotifyPropertyChanged, INotifyPropertyChanging { #region INotifyPropertyChange interfaces public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangingEventHandler? PropertyChanging; #endregion #region IRelayCommand interface public event EventHandler? CanExecuteChanged; public void NotifyCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } public void Execute(object? parameter) { _execute?.Invoke(parameter); } public bool CanExecute(object? parameter) { if (_canExecuteWithReason != null) { bool canExecute = _canExecuteWithReason(parameter, this); if (canExecute) { ReasonCantExecute = null; } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ReasonCantExecute))); return canExecute; } return true; } #endregion public delegate bool CanExecuteWithReason(object? parameter, IReportReasonCantExecute reporter); private string? _reasonCantExecute; public string? ReasonCantExecute { get => _reasonCantExecute; set { if (_reasonCantExecute != value) { PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(nameof(ReasonCantExecute))); _reasonCantExecute = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ReasonCantExecute))); } } } private readonly Action<object?>? _execute; private readonly CanExecuteWithReason? _canExecuteWithReason; public RelayCommandWithReason(Action<object?> execute, CanExecuteWithReason canExecuteWithReason) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecuteWithReason = canExecuteWithReason; } } ``` in the view model: ``` csharp public ICommand DoTheThingCommand => new RelayCommandWithReason(this.DoTheThing, this.CanDoTheThing); internal bool CanDoTheThing(object? parameter, IReportReasonCantExecute reporter) { if (CommonProcessObject.SomethingIUsed) { reporter.ReasonCantExecute = "You can't do the thing yet."; return false; } return true; } public void DoTheThing(object? parameter) { // do the thing } ``` in the view: ``` xaml <Button Content="Do the thing" Command="{Binding DoTheThingCommand}" local:ShowDisabledTooltipExtension.ShowOnDisabled="true" ToolTip.Tip="{Binding $self.((local:RelayCommandWithReason)Command).ReasonCantExecute}" CommandParameter="{Binding CommonProcessObject.SomethingIUsed}" /> ``` result: ![image](https://github.com/AvaloniaUI/Avalonia/assets/2152220/8a447f76-a6c1-40e1-b08e-2375997128d7) (The only thing to keep in mind is that because `SomethingIUsed` was used in the condition, I had to pass it in as the `CommandParameter`, even though I didn't actually need to use it as `parameter` as it's already directly accessible to that viewmodel... but otherwise, CanExecute won't get re-evaluated when `SomethingIUsed` changes. That'd be true of a regular CanExecute without reason too though; with the toolkit RelayCommand the expectation is to adorn the property with `[NotifyCanExecuteChangedFor(nameof(DoTheThingCommand))]`, but that couples the property to the command and this property is in a child property of an ObservableObject in a base class many views use, so not an option 😅)
2024-03-12T12:45:39Z
0.1
[]
['Avalonia.Controls.UnitTests.ToolTipTests.Should_Close_When_Control_Detaches', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Close_When_Tip_Is_Opened_And_Detached_From_Visual_Tree', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Open_On_Pointer_Enter', 'Avalonia.Controls.UnitTests.ToolTipTests.Content_Should_Update_When_Tip_Property_Changes_And_Already_Open', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Open_On_Pointer_Enter_With_Delay', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Close_On_Null_Tip', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Not_Close_When_Pointer_Is_Moved_Over_ToolTip', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Not_Close_When_Pointer_Is_Moved_From_ToolTip_To_Original_Control', 'Avalonia.Controls.UnitTests.ToolTipTests.Should_Close_When_Pointer_Is_Moved_From_ToolTip_To_Another_Control']
AvaloniaUI/Avalonia
avaloniaui__avalonia-14913
86bfc26aceeb3000f47e3a67c39daa78deb0acda
diff --git a/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs b/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs index 04f6b1d8a12..aa62eaaf065 100644 --- a/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs +++ b/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs @@ -285,8 +285,12 @@ public bool BringDescendantIntoView(Visual target, Rect targetRect) return false; } + var oldOffset = Offset; SetCurrentValue(OffsetProperty, offset); - return true; + + // It's possible that the Offset coercion has changed the offset back to its previous value, + // this is common for floating point rounding errors. + return !Offset.NearlyEquals(oldOffset); } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
diff --git a/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs b/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs index 274bee15284..e70ab520439 100644 --- a/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs @@ -439,6 +439,56 @@ public void Nested_Presenters_Should_Scroll_Outer_When_Content_Exceeds_Viewport( Assert.Equal(new Vector(0, 0), innerPresenter.Offset); } + [Fact] + public void Nested_Presenters_Should_Scroll_Outer_When_Viewports_Are_Close() + { + ScrollContentPresenter innerPresenter; + Border border; + + var outerPresenter = new ScrollContentPresenter + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Width = 100, + Height = 170.0568181818182, + UseLayoutRounding = false, + Content = innerPresenter = new ScrollContentPresenter + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Width = 100, + Height = 493.2613636363636, + UseLayoutRounding = false, + Content = new StackPanel + { + Children = + { + new Border + { + Height = 455.31818181818187, + UseLayoutRounding = false + }, + (border = new Border { + Width = 100, + Height = 37.94318181818182, + UseLayoutRounding = false + }) + } + } + } + }; + + innerPresenter.UpdateChild(); + outerPresenter.UpdateChild(); + outerPresenter.Measure(new Size(100, 170.0568181818182)); + outerPresenter.Arrange(new Rect(0, 0, 100, 170.0568181818182)); + + border.BringIntoView(); + + Assert.Equal(new Vector(0, 323.20454545454544), outerPresenter.Offset); + Assert.Equal(new Vector(0, 0), innerPresenter.Offset); + } + private class TestControl : Control { public Size AvailableSize { get; private set; }
Rendering artifacts in ListView ## Describe the bug I am experiencing strange rendering artefacts when using a `ListView`. ## To Reproduce Steps to reproduce the behavior: See attached minimal example. [ListViewAutoScrollBug.zip](https://github.com/AvaloniaUI/Avalonia/files/13349670/ListViewAutoScrollBug.zip) A clear and concise description of what you expected to happen. ## Screenshots https://github.com/AvaloniaUI/Avalonia/assets/125025268/56b2cfc4-e568-4f26-bc02-63c9ad0ed28f ## Environment <!-- (please complete the following information): --> - OS: Windows 11 - Avalonia-Version: 11.0.5 ## Additional context I want to render a hierarchical tree in a ListView. Every change of the tree triggers a redraw of the ListView so that the content of the ListView is recreated every time a node is expanded or collapsed. For illustration purposes in this demo every expand of a node creates 20 new children while the last of them shall be selected and become visible. (`AutoScrollToSelectedItem`) This works most of the time. But sometimes the ListView "overdraws" the item with some old content that does not disappear anymore. In these cases the autoscroll does not work either.
Seems same as [#12744](https://github.com/AvaloniaUI/Avalonia/issues/12744). consider using TreeDataGrid > consider using TreeDataGrid I can‘t say for sure but I think I had basically the same issue with TreeDataGrid. That‘s was one of two reasons to go with this approach. I can also confirm TreeDataGrid has virtualization issue. Btw seems like you are using semi avalonia❤️ y, the underlaying issue is applying to all virtualized controls. So if anyone finds the root cause, a PR is more than welcome. Maybe @grokys has some ideas but he is more than busy rn. I think this is indeed a duplicate, so closing it in favor of the original issue. If someone disagrees, let me know. I don't know if this is helpful but I noticed that it is reproducable that exacly the same node seems to be affected every time you run the app. (Just expand the last node until the issue appears) And the it seems like a "broken" node is added additionally to the other nodes before the actual new nodes are added. This broken node also appears in the logical tree. ![grafik](https://github.com/AvaloniaUI/Avalonia/assets/125025268/834618d4-d2f2-4ded-93d1-6d2fccfde2bd) The issue seems to occur only when `AutoScrollToSelectedItem` is true. At least in my example it only occurs when the last item gets selected by code. In my tests the issue disappeared when `UseLayoutRounding` is set to `false` on `ListBox`. Should be fixed by #13765 if you'd like to test. I have tested the attached example with 11.0.6 and the issue is still present. @CodeDevAM can you also check nightly? It has fixes that 11.0.6 doesn't have No difference with 11.1.999-cibuild0043367-beta Reopening for now. /cc @grokys The issue is still present with 11.0.9. Unfortunately this is a big blocker for my app. Maybe this helps finding the root cause: I have provided an _Reset View_ button the the user for the situation when the issue occurs in my app. So the user can manually recreate the ListView Control. Then issue does not appear for the newly created control. But it may appear again after some modifications to the list. My current investigation results: - Occurance depands on the size of Controls. A slightly different size results in different bahaviour. https://github.com/AvaloniaUI/Avalonia/assets/125025268/b6cc4178-ad80-49ff-b7a0-1a5b3120ab02 https://github.com/AvaloniaUI/Avalonia/assets/125025268/7e4e594d-66fe-470d-9277-da793c012b8e - `ScrollIntoView()` from `VirtualizingStackPanel` seems to add Items that are not initialized correctly. Not all `VisualChildren` are cleared corretly afterwards. This results in overlaying Controls. - Different settings for `UseLayoutRounding` have an impact on the behaviour but the issue **does not** disappear. I don't have a minimal reproduction scenario yet but `TreeDataGrid` seems to have the same or a very similar issue. (Version 11.0.2) Since I don't have a solution for `AutoScrollToSelectedItem` with a `TreeDataGrid` yet the issue also occurs independently of this feature. ![grafik](https://github.com/AvaloniaUI/Avalonia/assets/125025268/61cc9b54-5bc5-4eb4-a3b8-5a280bf23f15) @CodeDevAM I'd suggest you put your sample into `src/samples/Sandbox` and try to debug the virtulization logic in source directly, given you spend some time on that issue anyways. Maybe you find the right place to clean up recycle items. That's exactly what I was doing. I spent many hours to figure out the root cause of this issue. (at least for a `ListBox`) Unfortunatly it's a very complicated piece of code and I was not able to figure it out so far. The problem that I have is that changing the underlying collection of a `ListBox` causes a run through a hierarchy of Controls multiple times in different modes that changes the behaviour of the relevant functions slightly. In the end it is very hard to follow. Long story short: I think it needs an expert that is more familiar with the inner details of a `ListBox`. This check could be problematic because it is prone to floating point rounding errors. https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L406 I noticed that the Bound checks behave differently in a good case and a bad case. Like a Bottom of `798.8636363636365` is not considered to be within the bounds `798.8636363636364`. @CodeDevAM if you give a kind of "epsilon" to the contains method, would that solve your issue? `Bounds.Contains(rect, 0.0001)` where Contains needs a new overload accepting that epsilon. A check with a certain tolerance would be a good idea. Unfortunately it does not solve the issue. With my analysis I figured out so far that `_viewport` of the `VirtualizingStackPanel` is calculated differently in a good case and a bad case at https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L422 As a result the `anchorIndex` is is not calculated correctly. https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L465 Another idea would be to use Inflate on the Bounds and friends 🤔 I can reproduce the issue consistently when the item to select has a width larger than the `ListBox` (by resizing the window enough). This causes the inner `ScrollViewer` (the `ListBox`'s one) to incorrectly handle the `RequestBringIntoView` for the item, preventing the outer one (inside `MainWindow)` from scrolling to the correct position. This in turn prevents the focused item from being part of the realized item list, duplicating it. Here's a PR to fix that: #14900 @CodeDevAM can you please confirm that this fixes your issue? Several of your videos don't seem to have the item larger than the viewport, so maybe there's still something else going on. That fix can be tested on 11.2.999-cibuild0046020-beta builds, just in case. > @CodeDevAM can you please confirm that this fixes your issue? Several of your videos don't seem to have the item larger than the viewport, so maybe there's still something else going on. Unfortunately there is no improvement with 11.2.999-cibuild0046020-beta. But when I go to official 11.0.10 the issue disappears in my minimal example app. Good case with 11.2.999-cibuild0046020-beta: https://github.com/AvaloniaUI/Avalonia/assets/125025268/344451a1-7db1-4f0d-a510-6e4e65221e82 Bad case with 11.2.999-cibuild0046020-beta: https://github.com/AvaloniaUI/Avalonia/assets/125025268/690948ca-991d-4749-a982-9612512a356f minimal example app with 11.2.999-cibuild0046020-beta: [ListViewAutoScrollBug.zip](https://github.com/AvaloniaUI/Avalonia/files/14555511/ListViewAutoScrollBug.zip) Good case with 11.0.10: https://github.com/AvaloniaUI/Avalonia/assets/125025268/167b5f02-aade-4178-955f-1ce0727c5608 "Bad" case that went well with 11.0.10 https://github.com/AvaloniaUI/Avalonia/assets/125025268/4eafb866-e1aa-4680-a39b-e655b3daccfb minimal example app with 11.0.10: [ListViewAutoScrollBug.zip](https://github.com/AvaloniaUI/Avalonia/files/14555568/ListViewAutoScrollBug.zip) I recommend not to close this issue yet unless it's clear whats the root cause of this issue. Note: I have minimized the example app to a simple list where adding 13 elements to the list causes the issue but adding 12 elements to the list does not. That's at least how it behaves on my machine.
2024-03-11T10:44:01Z
0.1
['Avalonia.Controls.UnitTests.Presenters.ScrollContentPresenterTests.Nested_Presenters_Should_Scroll_Outer_When_Viewports_Are_Close']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-14900
27c49a8b2200e00efb744b7132c2774edf2ea366
diff --git a/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs b/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs index 4a54c1b35c8..04f6b1d8a12 100644 --- a/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs +++ b/src/Avalonia.Controls/Presenters/ScrollContentPresenter.cs @@ -259,38 +259,34 @@ public bool BringDescendantIntoView(Visual target, Rect targetRect) var rect = targetRect.TransformToAABB(transform.Value); var offset = Offset; - var result = false; if (rect.Bottom > offset.Y + Viewport.Height) { offset = offset.WithY((rect.Bottom - Viewport.Height) + Child.Margin.Top); - result = true; } if (rect.Y < offset.Y) { offset = offset.WithY(rect.Y); - result = true; } if (rect.Right > offset.X + Viewport.Width) { offset = offset.WithX((rect.Right - Viewport.Width) + Child.Margin.Left); - result = true; } if (rect.X < offset.X) { offset = offset.WithX(rect.X); - result = true; } - if (result) + if (Offset.NearlyEquals(offset)) { - SetCurrentValue(OffsetProperty, offset); + return false; } - return result; + SetCurrentValue(OffsetProperty, offset); + return true; } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) diff --git a/src/Avalonia.Controls/VirtualizingStackPanel.cs b/src/Avalonia.Controls/VirtualizingStackPanel.cs index f702f09e8ae..65410021a89 100644 --- a/src/Avalonia.Controls/VirtualizingStackPanel.cs +++ b/src/Avalonia.Controls/VirtualizingStackPanel.cs @@ -453,8 +453,6 @@ private MeasureViewport CalculateMeasureViewport(IReadOnlyList<object?> items) { Debug.Assert(_realizedElements is not null); - // If the control has not yet been laid out then the effective viewport won't have been set. - // Try to work it out from an ancestor control. var viewport = _viewport; // Get the viewport in the orientation direction.
diff --git a/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs b/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs index 30628b1af85..274bee15284 100644 --- a/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Presenters/ScrollContentPresenterTests.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Reactive.Linq; using Avalonia.Controls.Presenters; -using Avalonia.Controls.Primitives; using Avalonia.Layout; using Avalonia.UnitTests; using Xunit; @@ -366,7 +365,7 @@ public void BringDescendantIntoView_Should_Update_Offset() target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); - target.BringDescendantIntoView(target.Child, new Rect(200, 200, 0, 0)); + target.BringDescendantIntoView(target.Child!, new Rect(200, 200, 0, 0)); Assert.Equal(new Vector(100, 100), target.Offset); } @@ -400,6 +399,46 @@ public void BringDescendantIntoView_Should_Handle_Child_Margin() Assert.Equal(new Vector(150, 150), target.Offset); } + [Fact] + public void Nested_Presenters_Should_Scroll_Outer_When_Content_Exceeds_Viewport() + { + ScrollContentPresenter innerPresenter; + Border border; + + var outerPresenter = new ScrollContentPresenter + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Width = 100, + Height = 100, + Content = innerPresenter = new ScrollContentPresenter + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Width = 100, + Height = 200, + Content = border = new Border + { + Width = 200, // larger than viewport + Height = 25, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + Margin = new Thickness(0, 120, 0, 0) + } + } + }; + + innerPresenter.UpdateChild(); + outerPresenter.UpdateChild(); + outerPresenter.Measure(new Size(100, 100)); + outerPresenter.Arrange(new Rect(0, 0, 100, 100)); + + border.BringIntoView(); + + Assert.Equal(new Vector(0, 45), outerPresenter.Offset); + Assert.Equal(new Vector(0, 0), innerPresenter.Offset); + } + private class TestControl : Control { public Size AvailableSize { get; private set; }
Rendering artifacts in ListView ## Describe the bug I am experiencing strange rendering artefacts when using a `ListView`. ## To Reproduce Steps to reproduce the behavior: See attached minimal example. [ListViewAutoScrollBug.zip](https://github.com/AvaloniaUI/Avalonia/files/13349670/ListViewAutoScrollBug.zip) A clear and concise description of what you expected to happen. ## Screenshots https://github.com/AvaloniaUI/Avalonia/assets/125025268/56b2cfc4-e568-4f26-bc02-63c9ad0ed28f ## Environment <!-- (please complete the following information): --> - OS: Windows 11 - Avalonia-Version: 11.0.5 ## Additional context I want to render a hierarchical tree in a ListView. Every change of the tree triggers a redraw of the ListView so that the content of the ListView is recreated every time a node is expanded or collapsed. For illustration purposes in this demo every expand of a node creates 20 new children while the last of them shall be selected and become visible. (`AutoScrollToSelectedItem`) This works most of the time. But sometimes the ListView "overdraws" the item with some old content that does not disappear anymore. In these cases the autoscroll does not work either.
Seems same as [#12744](https://github.com/AvaloniaUI/Avalonia/issues/12744). consider using TreeDataGrid > consider using TreeDataGrid I can‘t say for sure but I think I had basically the same issue with TreeDataGrid. That‘s was one of two reasons to go with this approach. I can also confirm TreeDataGrid has virtualization issue. Btw seems like you are using semi avalonia❤️ y, the underlaying issue is applying to all virtualized controls. So if anyone finds the root cause, a PR is more than welcome. Maybe @grokys has some ideas but he is more than busy rn. I think this is indeed a duplicate, so closing it in favor of the original issue. If someone disagrees, let me know. I don't know if this is helpful but I noticed that it is reproducable that exacly the same node seems to be affected every time you run the app. (Just expand the last node until the issue appears) And the it seems like a "broken" node is added additionally to the other nodes before the actual new nodes are added. This broken node also appears in the logical tree. ![grafik](https://github.com/AvaloniaUI/Avalonia/assets/125025268/834618d4-d2f2-4ded-93d1-6d2fccfde2bd) The issue seems to occur only when `AutoScrollToSelectedItem` is true. At least in my example it only occurs when the last item gets selected by code. In my tests the issue disappeared when `UseLayoutRounding` is set to `false` on `ListBox`. Should be fixed by #13765 if you'd like to test. I have tested the attached example with 11.0.6 and the issue is still present. @CodeDevAM can you also check nightly? It has fixes that 11.0.6 doesn't have No difference with 11.1.999-cibuild0043367-beta Reopening for now. /cc @grokys The issue is still present with 11.0.9. Unfortunately this is a big blocker for my app. Maybe this helps finding the root cause: I have provided an _Reset View_ button the the user for the situation when the issue occurs in my app. So the user can manually recreate the ListView Control. Then issue does not appear for the newly created control. But it may appear again after some modifications to the list. My current investigation results: - Occurance depands on the size of Controls. A slightly different size results in different bahaviour. https://github.com/AvaloniaUI/Avalonia/assets/125025268/b6cc4178-ad80-49ff-b7a0-1a5b3120ab02 https://github.com/AvaloniaUI/Avalonia/assets/125025268/7e4e594d-66fe-470d-9277-da793c012b8e - `ScrollIntoView()` from `VirtualizingStackPanel` seems to add Items that are not initialized correctly. Not all `VisualChildren` are cleared corretly afterwards. This results in overlaying Controls. - Different settings for `UseLayoutRounding` have an impact on the behaviour but the issue **does not** disappear. I don't have a minimal reproduction scenario yet but `TreeDataGrid` seems to have the same or a very similar issue. (Version 11.0.2) Since I don't have a solution for `AutoScrollToSelectedItem` with a `TreeDataGrid` yet the issue also occurs independently of this feature. ![grafik](https://github.com/AvaloniaUI/Avalonia/assets/125025268/61cc9b54-5bc5-4eb4-a3b8-5a280bf23f15) @CodeDevAM I'd suggest you put your sample into `src/samples/Sandbox` and try to debug the virtulization logic in source directly, given you spend some time on that issue anyways. Maybe you find the right place to clean up recycle items. That's exactly what I was doing. I spent many hours to figure out the root cause of this issue. (at least for a `ListBox`) Unfortunatly it's a very complicated piece of code and I was not able to figure it out so far. The problem that I have is that changing the underlying collection of a `ListBox` causes a run through a hierarchy of Controls multiple times in different modes that changes the behaviour of the relevant functions slightly. In the end it is very hard to follow. Long story short: I think it needs an expert that is more familiar with the inner details of a `ListBox`. This check could be problematic because it is prone to floating point rounding errors. https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L406 I noticed that the Bound checks behave differently in a good case and a bad case. Like a Bottom of `798.8636363636365` is not considered to be within the bounds `798.8636363636364`. @CodeDevAM if you give a kind of "epsilon" to the contains method, would that solve your issue? `Bounds.Contains(rect, 0.0001)` where Contains needs a new overload accepting that epsilon. A check with a certain tolerance would be a good idea. Unfortunately it does not solve the issue. With my analysis I figured out so far that `_viewport` of the `VirtualizingStackPanel` is calculated differently in a good case and a bad case at https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L422 As a result the `anchorIndex` is is not calculated correctly. https://github.com/AvaloniaUI/Avalonia/blob/11f5203ab24515a4094d7140d0d757d5016e2007/src/Avalonia.Controls/VirtualizingStackPanel.cs#L465 Another idea would be to use Inflate on the Bounds and friends 🤔
2024-03-10T01:14:05Z
0.1
['Avalonia.Controls.UnitTests.Presenters.ScrollContentPresenterTests.Nested_Presenters_Should_Scroll_Outer_When_Content_Exceeds_Viewport']
['Avalonia.Controls.UnitTests.Presenters.ScrollContentPresenterTests.BringDescendantIntoView_Should_Update_Offset', 'Avalonia.Controls.UnitTests.Presenters.ScrollContentPresenterTests.BringDescendantIntoView_Should_Handle_Child_Margin']
AvaloniaUI/Avalonia
avaloniaui__avalonia-14838
3e51397884a6a2b9f7bb474668bdf28e22e136d8
diff --git a/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs b/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs index 5a4a56b7469..179ba009c02 100644 --- a/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs +++ b/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs @@ -257,8 +257,10 @@ private static State ParseTypeCast(ref CharacterReader r, List<INode> nodes) } result = ParseBeforeMember(ref r, nodes); + if (result == State.AttachedProperty) + result = ParseAttachedProperty(ref r, nodes); - if(r.Peek == '[') + if (r.Peek == '[') { result = ParseIndexer(ref r, nodes); }
diff --git a/tests/Avalonia.Markup.UnitTests/Parsers/ExpressionObserverBuilderTests_AttachedProperty.cs b/tests/Avalonia.Markup.UnitTests/Parsers/ExpressionObserverBuilderTests_AttachedProperty.cs index 4c9333c42b3..cc2dc35f0bf 100644 --- a/tests/Avalonia.Markup.UnitTests/Parsers/ExpressionObserverBuilderTests_AttachedProperty.cs +++ b/tests/Avalonia.Markup.UnitTests/Parsers/ExpressionObserverBuilderTests_AttachedProperty.cs @@ -65,6 +65,22 @@ public async Task Should_Get_Chained_Attached_Property_Value() Assert.Null(((IAvaloniaObjectDebug)data).GetPropertyChangedSubscribers()); } + [Fact] + public async Task Should_Get_Chained_Attached_Property_Value_With_TypeCast() + { + var expected = new Class1(); + + var data = new Class1(); + data.SetValue(Owner.SomethingProperty, new Class1() { Next = expected }); + + var target = Build(data, "((Class1)(Owner.Something)).Next", typeResolver: (ns, name) => name == "Class1" ? typeof(Class1) : _typeResolver(ns, name)); + var result = await target.Take(1); + + Assert.Equal(expected, result); + + Assert.Null(((IAvaloniaObjectDebug)data).GetPropertyChangedSubscribers()); + } + [Fact] public void Should_Track_Simple_Attached_Value() { @@ -159,6 +175,11 @@ private static class Owner "Foo", typeof(Owner), defaultValue: "foo"); + + public static readonly AttachedProperty<AvaloniaObject> SomethingProperty = + AvaloniaProperty.RegisterAttached<Class1, AvaloniaObject>( + "Something", + typeof(Owner)); } private class Class1 : AvaloniaObject
Parsing binding expression with type cast of attached property fails ## Describe the bug I'm attempting to bind to a property of the adorned element in a template set to the adorner property. To do this with compiled bindings a type cast is required but that fails to parse. ## To Reproduce ```xml <TextBox> <TextBox.Styles> <Style Selector="TextBox"> <Setter Property="(AdornerLayer.Adorner)"> <Template> <TextBlock Margin="10 20 0 0" Foreground="Red" Text="{Binding $self.((TextBox)(AdornerLayer.AdornedElement)).Text}"/> </Template> </Setter> </Style> </TextBox.Styles> </TextBox> ``` This fails to compile. ``` Avalonia error AVLN:0004: Internal compiler error while transforming node XamlX.Ast.XamlAstObjectNode: Avalonia error AVLN:0004: Avalonia.Data.Core.ExpressionParseException: Expected ')'. Avalonia error AVLN:0004: at Avalonia.Markup.Parsers.BindingExpressionGrammar.ParseTypeCast(CharacterReader& r, List`1 nodes) in /_/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs:line 249 Avalonia error AVLN:0004: at Avalonia.Markup.Parsers.BindingExpressionGrammar.Parse(CharacterReader& r) in /_/src/Markup/Avalonia.Markup/Markup/Parsers/BindingExpressionGrammar.cs:line 50 Avalonia error AVLN:0004: at Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers.AvaloniaXamlIlBindingPathParser.Transform(AstTransformationContext context, IXamlAstNode node) in /_/src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/AvaloniaXamlIlBindingPathParser.cs:line 28 Avalonia error AVLN:0004: at XamlX.Transform.AstTransformationContext.Visitor.Visit(IXamlAstNode node) in /_/src/Markup/Avalonia.Markup.Xaml.Loader/xamlil.github/src/XamlX/Transform/AstTransformationContext.cs:line 58 Line 20, position 60. ``` With a ReflectionBinding it fails at runtime. ``` Avalonia.Data.Core.ExpressionParseException HResult=0x80131500 Message=Expected ')'. Source=Avalonia.Markup StackTrace: at Avalonia.Markup.Parsers.BindingExpressionGrammar.ParseTypeCast(CharacterReader& r, List`1 nodes) at Avalonia.Markup.Parsers.BindingExpressionGrammar.Parse(CharacterReader& r) at Avalonia.Markup.Parsers.ExpressionParser.Parse(CharacterReader& r) at Avalonia.Markup.Parsers.ExpressionObserverBuilder.Parse(String expression, Boolean enableValidation, Func`3 typeResolver, INameScope nameScope) at Avalonia.Data.Binding.CreateExpressionObserver(AvaloniaObject target, AvaloniaProperty targetProperty, Object anchor, Boolean enableDataValidation) at Avalonia.Data.BindingBase.Initiate(AvaloniaObject target, AvaloniaProperty targetProperty, Object anchor, Boolean enableDataValidation) at Avalonia.AvaloniaObjectExtensions.Bind(AvaloniaObject target, AvaloniaProperty property, IBinding binding, Object anchor) at AvaloniaApplication3.MainWindow.XamlClosure_2.Build(IServiceProvider ) in MainWindow.axaml:line 20 at Avalonia.Markup.Xaml.XamlIl.Runtime.XamlIlRuntimeHelpers.<>c__DisplayClass1_0`1.<DeferredTransformationFactoryV2>b__0(IServiceProvider sp) at Avalonia.Markup.Xaml.Templates.TemplateContent.Load(Object templateContent) at Avalonia.Markup.Xaml.Templates.Template.Build() at Avalonia.Markup.Xaml.Templates.Template.Avalonia.Styling.ITemplate.Build() at Avalonia.Styling.PropertySetterTemplateInstance.GetValue() at Avalonia.PropertyStore.EffectiveValue`1.GetValue(IValueEntry entry) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaise(ValueStore owner, IValueEntry value, BindingPriority priority) at Avalonia.PropertyStore.ValueStore.ReevaluateEffectiveValues(IValueEntry changedValueEntry) at Avalonia.PropertyStore.ValueStore.EndStyling() at Avalonia.StyledElement.ApplyStyling() at Avalonia.StyledElement.EndInit() at AvaloniaApplication3.MainWindow.!XamlIlPopulate(IServiceProvider , MainWindow ) in MainWindow.axaml:line 14 at AvaloniaApplication3.MainWindow.!XamlIlPopulateTrampoline(MainWindow ) at AvaloniaApplication3.MainWindow.InitializeComponent(Boolean loadXaml, Boolean attachDevTools) in Avalonia.Generators\Avalonia.Generators.NameGenerator.AvaloniaNameSourceGenerator\AvaloniaApplication3.MainWindow.g.cs:line 23 at AvaloniaApplication3.MainWindow..ctor() in MainWindow.axaml.cs:line 14 at AvaloniaApplication3.App.OnFrameworkInitializationCompleted() in App.axaml.cs:line 18 at Avalonia.AppBuilder.SetupUnsafe() at Avalonia.AppBuilder.Setup() at Avalonia.AppBuilder.SetupWithLifetime(IApplicationLifetime lifetime) at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime(AppBuilder builder, String[] args, ShutdownMode shutdownMode) at AvaloniaApplication3.Program.Main(String[] args) in Program.cs:line 12 ``` With ReflectionBinding you don't need the type cast so if you instead do `{ReflectionBinding $self.(AdornerLayer.AdornedElement).Text}` it works. ## Expected behavior No error and successful binding the same as when using the ReflectionBinding without type cast. ## Environment: - OS: Windows - Avalonia-Version: 11.0.5 ## Additional context It looks like BindingExpressionGrammar.ParseTypeCast expects ParseBeforeMember to parse the identifier but for attached properties it doesn't but instead returns State.AttachedProperty. If I add parsing of an attached property after the call to ParseBeforeMember it looks like it works but I'm not well versed in the code base enough to know if that would be enough. ```csharp if (parseMemberBeforeAddCast) { if (!ParseCloseBrace(ref r)) { throw new ExpressionParseException(r.Position, "Expected ')'."); } result = ParseBeforeMember(ref r, nodes); // With this parsing a type cast of an attached property seems to work if (result == State.AttachedProperty) result = ParseAttachedProperty(ref r, nodes); if(r.Peek == '[') { result = ParseIndexer(ref r, nodes); } } ``` ```csharp [Fact] public async Task Should_Get_Chained_Attached_Property_Value_With_TypeCast() { var expected = new Class1(); var data = new Class1(); data.SetValue(Owner.SomethingProperty, new Class1() { Next = expected }); var target = ExpressionObserverBuilder.Build(data, "((Class1)(Owner.Something)).Next", typeResolver: (ns, name) => name == "Class1" ? typeof(Class1) : _typeResolver(ns, name)); var result = await target.Take(1); Assert.Equal(expected, result); Assert.Null(((IAvaloniaObjectDebug)data).GetPropertyChangedSubscribers()); } private static class Owner { public static readonly AttachedProperty<string> FooProperty = AvaloniaProperty.RegisterAttached<Class1, string>( "Foo", typeof(Owner), defaultValue: "foo"); public static readonly AttachedProperty<AvaloniaObject> SomethingProperty = AvaloniaProperty.RegisterAttached<Class1, AvaloniaObject>( "Something", typeof(Owner)); } ```
@appel1 great findings and I like that you also directly added a unit test. If you want to, you may try to make a PR out of it. This may help: - https://github.com/AvaloniaUI/Avalonia/wiki/Debugging-the-XAML-compiler - https://github.com/AvaloniaUI/Avalonia/blob/master/Documentation/build.md
2024-03-06T07:23:05Z
0.1
['Avalonia.Markup.UnitTests.Parsers.ExpressionObserverBuilderTests_AttachedProperty.Should_Get_Chained_Attached_Property_Value_With_TypeCast']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-14439
499e09efc9288d2dc6b9b674c9fedd3d6e5243ec
diff --git a/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs b/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs index 4029782772b..c0ea14037cd 100644 --- a/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs +++ b/src/Avalonia.Controls/Primitives/PopupPositioning/IPopupPositioner.cs @@ -468,7 +468,16 @@ public static void ConfigurePosition(ref this PopupPositionerParameters position { if (target == null) throw new InvalidOperationException("Placement mode is not Pointer and PlacementTarget is null"); - var matrix = target.TransformToVisual(topLevel); + Matrix? matrix; + if (TryGetAdorner(target, out var adorned, out var adornerLayer)) + { + matrix = adorned!.TransformToVisual(topLevel) * target.TransformToVisual(adornerLayer!); + } + else + { + matrix = target.TransformToVisual(topLevel); + } + if (matrix == null) { if (target.GetVisualRoot() == null) @@ -529,6 +538,25 @@ public static void ConfigurePosition(ref this PopupPositionerParameters position } } } + + private static bool TryGetAdorner(Visual target, out Visual? adorned, out Visual? adornerLayer) + { + var element = target; + while (element != null) + { + if (AdornerLayer.GetAdornedElement(element) is { } adornedElement) + { + adorned = adornedElement; + adornerLayer = AdornerLayer.GetAdornerLayer(adorned); + return true; + } + element = element.VisualParent; + } + + adorned = null; + adornerLayer = null; + return false; + } } }
diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs index 5a0c60dff68..8398da59a5c 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs @@ -1143,6 +1143,53 @@ public void GetPosition_On_Control_In_Popup_Called_From_Parent_Should_Return_Val } } + [Fact] + public void Popup_Attached_To_Adorner_Respects_Adorner_Position() + { + using (CreateServices()) + { + var popupTarget = new Border() { Height = 30, Background = Brushes.Red, [DockPanel.DockProperty] = Dock.Top }; + var popupContent = new Border() { Height = 30, Width = 50, Background = Brushes.Yellow }; + var popup = new Popup + { + Child = popupContent, + Placement = PlacementMode.AnchorAndGravity, + PlacementTarget = popupTarget, + PlacementAnchor = PopupAnchor.BottomRight, + PlacementGravity = PopupGravity.BottomRight + }; + var adorner = new DockPanel() { Children = { popupTarget, popup }, + HorizontalAlignment = HorizontalAlignment.Left, + Width = 40, + Margin = new Thickness(50, 5, 0, 0) }; + + var adorned = new Border() { + Width = 100, + Height = 100, + Background = Brushes.Blue, + [Canvas.LeftProperty] = 20, + [Canvas.TopProperty] = 40 + }; + var windowContent = new Canvas(); + windowContent.Children.Add(adorned); + + var root = PreparedWindow(windowContent); + + var adornerLayer = AdornerLayer.GetAdornerLayer(adorned); + adornerLayer.Children.Add(adorner); + AdornerLayer.SetAdornedElement(adorner, adorned); + + root.LayoutManager.ExecuteInitialLayoutPass(); + popup.Open(); + Dispatcher.UIThread.RunJobs(DispatcherPriority.AfterRender); + + // X: Adorned Canvas.Left + Adorner Margin Left + Adorner Width + // Y: Adorned Canvas.Top + Adorner Margin Top + Adorner Height + Assert.Equal(new PixelPoint(110, 75), popupContent.PointToScreen(new Point(0, 0))); + } + } + + private static PopupRoot CreateRoot(TopLevel popupParent, IPopupImpl impl = null) { impl ??= popupParent.PlatformImpl.CreatePopup();
Popup with a placement target pops up in a wrong position with compositor in adorner layer **Describe the bug** Popups are displayed in a wrong position, with compositor enabled, with Placement Target specified (pointer position works) when the parent control is an adorner layer. **To Reproduce** Open a popup (i.e. combobox), which belongs to a control that is placed on an adorner layer, with a placement target, with the compositor enabled. or 1. Clone https://github.com/BAndysc/Avalonia_Compositor_Adorner_Popup_Bug 2. Run (by default the compositor is disabled) 3. See the correct result: (both popups displayed below the controls) ![image](https://user-images.githubusercontent.com/5689666/210281832-cf808a05-8cf7-48ea-87ca-b95f7a002fa6.png) 4. Change `UseCompositor` to `true` and run 5. See the popup is displayed in a wrong place ![image](https://user-images.githubusercontent.com/5689666/210281880-88871c65-eb94-444e-8975-f7bc11193b14.png) **Desktop:** - OS: macOS - Version 11.0.999-cibuild0028025-beta **Additional context:** The example might be a bit cursed, but I think it is a common practice to place a combobox in an adorner layer, and the list will be opened in a wrong place as well (as this uses the same popups underneath)
I've checked this again in latest stable Avalonia 11.0.0, but sadly it is still bugged. Sorry for the ping, but let me ping @kekekeks as I believe if anybody might have an idea where the problem is, that's Nikita. I've debugged the code and I was able to find the offending line: in Avalonia 0.10 the bounds here were taken directly from TransformedBounds property: https://github.com/AvaloniaUI/Avalonia/blob/7739bd9ca3a20a8cb2b10c4ee2ca31337b227f4e/src/Avalonia.Controls/Primitives/AdornerLayer.cs#L183-L187 since this property has been removed, new Adorner code constructs TransformedBounds manually, but as you can see the `transform` Matrix is always set to Identity, which is the problem. https://github.com/AvaloniaUI/Avalonia/blob/2ecfbb978337ef7937821717c01421cdf60cd504/src/Avalonia.Controls/Primitives/AdornerLayer.cs#L321-L325 Later in the code, this invalid TransformedBounds is assigned to RenderTransform, which is used to determine the popup location: https://github.com/AvaloniaUI/Avalonia/blob/2ecfbb978337ef7937821717c01421cdf60cd504/src/Avalonia.Controls/Primitives/AdornerLayer.cs#L228 ### Partial fix: changing ``` info.Bounds = new TransformedBounds(new Rect(adorned.Bounds.Size), new Rect(adorned.Bounds.Size), Matrix.Identity); ``` to ``` info.Bounds = adorned.GetTransformedBounds(); ``` fixes the problem, but as you can probably guess at this point, this is not the only problem here. With the compositor change, observing for `TransformedBounds` changes was changed to observing for `Bounds` changes. This means if the control moves "indirectly" (i.e. its parents move), then this event will not be fired and the Bounds will not be correctly updated. Since I am not sure how to solve this issue correctly, let me ping @kekekeks since you are the main compositor engine author.
2024-02-01T13:01:51Z
0.1
['Avalonia.Controls.UnitTests.Primitives.PopupTests.Popup_Attached_To_Adorner_Respects_Adorner_Position']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-14048
0bde86b4577fbf2580dbffc3892de2e06e74b95d
diff --git a/samples/ControlCatalog/Pages/BorderPage.xaml b/samples/ControlCatalog/Pages/BorderPage.xaml index 7ec7e81e805..4c2384d6869 100644 --- a/samples/ControlCatalog/Pages/BorderPage.xaml +++ b/samples/ControlCatalog/Pages/BorderPage.xaml @@ -5,6 +5,9 @@ d:DesignWidth="400" x:Class="ControlCatalog.Pages.BorderPage"> <StackPanel Orientation="Vertical" Spacing="4"> + <StackPanel.Resources> + <SolidColorBrush x:Key="SemiTransparentSystemAccentBrush" Color="{DynamicResource SystemAccentColor}" Opacity="0.4" /> + </StackPanel.Resources> <TextBlock Classes="h2">A control which decorates a child with a border and background</TextBlock> <StackPanel Orientation="Vertical" @@ -15,10 +18,25 @@ <TextBlock>Border</TextBlock> </Border> <Border Background="{DynamicResource SystemAccentColorDark1}" - BorderBrush="{DynamicResource SystemAccentColor}" - BorderThickness="4" - Padding="16"> - <TextBlock>Border and Background</TextBlock> + BorderBrush="{DynamicResource SemiTransparentSystemAccentBrush}" + BackgroundSizing="CenterBorder" + BorderThickness="8" + Padding="12"> + <TextBlock>Background And CenterBorder</TextBlock> + </Border> + <Border Background="{DynamicResource SystemAccentColorDark1}" + BorderBrush="{DynamicResource SemiTransparentSystemAccentBrush}" + BackgroundSizing="InnerBorderEdge" + BorderThickness="8" + Padding="12"> + <TextBlock>Background And InnerBorder</TextBlock> + </Border> + <Border Background="{DynamicResource SystemAccentColorDark1}" + BorderBrush="{DynamicResource SemiTransparentSystemAccentBrush}" + BackgroundSizing="OuterBorderEdge" + BorderThickness="8" + Padding="12"> + <TextBlock>Background And OuterBorderEdge</TextBlock> </Border> <Border BorderBrush="{DynamicResource SystemAccentColor}" BorderThickness="4" diff --git a/src/Avalonia.Base/Media/BackgroundSizing.cs b/src/Avalonia.Base/Media/BackgroundSizing.cs new file mode 100644 index 00000000000..bd079ce731c --- /dev/null +++ b/src/Avalonia.Base/Media/BackgroundSizing.cs @@ -0,0 +1,38 @@ +namespace Avalonia.Media +{ + /// <summary> + /// Defines how a background is drawn relative to its border. + /// </summary> + public enum BackgroundSizing + { + /// <summary> + /// The background is drawn up to the inside edge of the border. + /// </summary> + /// <remarks> + /// The background will never be drawn under the border itself and will not be visible + /// underneath the border regardless of border transparency. + /// </remarks> + InnerBorderEdge = 0, + + /// <summary> + /// The background is drawn completely to the outside edge of the border. + /// </summary> + /// <remarks> + /// The background will be visible underneath the border if the border has transparency. + /// </remarks> + OuterBorderEdge = 1, + + /// <summary> + /// The background is drawn to the midpoint (center) of the border. + /// </summary> + /// <remarks> + /// The background will be visible underneath half of the border if the border has transparency. + /// For this reason it is not recommended to use <see cref="CenterBorder"/> if transparency is involved. + /// <br/><br/> + /// This value does not exist in other XAML frameworks and only exists in Avalonia for backwards compatibility + /// with legacy code. Before <see cref="BackgroundSizing"/> was added, Avalonia would always render using this + /// value (Skia's default). + /// </remarks> + CenterBorder = 2, + } +} diff --git a/src/Avalonia.Base/Media/GeometryBuilder.cs b/src/Avalonia.Base/Media/GeometryBuilder.cs new file mode 100644 index 00000000000..074c48d8eeb --- /dev/null +++ b/src/Avalonia.Base/Media/GeometryBuilder.cs @@ -0,0 +1,608 @@ +// Portions of this source file are adapted from the Windows Presentation Foundation (WPF) project. +// (https://github.com/dotnet/wpf) +// +// Licensed to The Avalonia Project under the MIT License, courtesy of The .NET Foundation. +// +// Portions of this source file are adapted from the WinUI project. +// (https://github.com/microsoft/microsoft-ui-xaml/tree/winui3/main) +// +// Licensed to The Avalonia Project under the MIT License. + +// Ignore Spelling: keypoints + +using System; +using Avalonia.Utilities; + +namespace Avalonia.Media +{ + /// <summary> + /// Contains internal helpers used to build and draw various geometries. + /// </summary> + internal class GeometryBuilder + { + private const double PiOver2 = 1.57079633; // 90 deg to rad + private const double Epsilon = 0.00000153; // Same as LayoutHelper.LayoutEpsilon + + /// <summary> + /// Draws a new rounded rectangle within the given geometry context. + /// Warning: The caller must manage and dispose the <see cref="StreamGeometryContext"/> externally. + /// </summary> + /// <remarks> + /// WinUI: https://github.com/microsoft/microsoft-ui-xaml/blob/93742a178db8f625ba9299f62c21f656e0b195ad/dxaml/xcp/core/core/elements/geometry.cpp#L1072-L1079 + /// </remarks> + /// <param name="context">The geometry context to draw into.</param> + /// <param name="keypoints">The rounded rectangle keypoints defining the rectangle to draw.</param> + public static void DrawRoundedCornersRectangle( + StreamGeometryContext context, + ref RoundedRectKeypoints keypoints) + { + double radiusX; + double radiusY; + + context.BeginFigure(keypoints.TopLeft, isFilled: true); + + // Top + context.LineTo(keypoints.TopRight); + + // TopRight corner + radiusX = keypoints.RightTop.X - keypoints.TopRight.X; + radiusY = keypoints.TopRight.Y - keypoints.RightTop.Y; + radiusX = radiusX > 0 ? radiusX : -radiusX; + radiusY = radiusY > 0 ? radiusY : -radiusY; + + context.ArcTo( + keypoints.RightTop, + new Size(radiusX, radiusY), + rotationAngle: 0.0, + isLargeArc: false, + SweepDirection.Clockwise); + + // Right + context.LineTo(keypoints.RightBottom); + + // BottomRight corner + radiusX = keypoints.RightBottom.X - keypoints.BottomRight.X; + radiusY = keypoints.BottomRight.Y - keypoints.RightBottom.Y; + radiusX = radiusX > 0 ? radiusX : -radiusX; + radiusY = radiusY > 0 ? radiusY : -radiusY; + + if (radiusX != 0 || radiusY != 0) + { + context.ArcTo( + keypoints.BottomRight, + new Size(radiusX, radiusY), + rotationAngle: 0.0, + isLargeArc: false, + SweepDirection.Clockwise); + } + + // Bottom + context.LineTo(keypoints.BottomLeft); + + // BottomLeft corner + radiusX = keypoints.BottomLeft.X - keypoints.LeftBottom.X; + radiusY = keypoints.BottomLeft.Y - keypoints.LeftBottom.Y; + radiusX = radiusX > 0 ? radiusX : -radiusX; + radiusY = radiusY > 0 ? radiusY : -radiusY; + + if (radiusX != 0 || radiusY != 0) + { + context.ArcTo( + keypoints.LeftBottom, + new Size(radiusX, radiusY), + rotationAngle: 0.0, + isLargeArc: false, + SweepDirection.Clockwise); + } + + // Left + context.LineTo(keypoints.LeftTop); + + // TopLeft corner + radiusX = keypoints.TopLeft.X - keypoints.LeftTop.X; + radiusY = keypoints.TopLeft.Y - keypoints.LeftTop.Y; + radiusX = radiusX > 0 ? radiusX : -radiusX; + radiusY = radiusY > 0 ? radiusY : -radiusY; + + if (radiusX != 0 || radiusY != 0) + { + context.ArcTo( + keypoints.TopLeft, + new Size(radiusX, radiusY), + rotationAngle: 0.0, + isLargeArc: false, + SweepDirection.Clockwise); + } + + context.EndFigure(isClosed: true); + } + + /// <summary> + /// Draws a new rounded rectangle within the given geometry context. + /// Warning: The caller must manage and dispose the <see cref="StreamGeometryContext"/> externally. + /// </summary> + /// <param name="context">The geometry context to draw into.</param> + /// <param name="rect">The existing rectangle dimensions without corner radii.</param> + /// <param name="radiusX">The radius on the X-axis used to round the corners of the rectangle.</param> + /// <param name="radiusY">The radius on the Y-axis used to round the corners of the rectangle.</param> + public static void DrawRoundedCornersRectangle( + StreamGeometryContext context, + Rect rect, + double radiusX, + double radiusY) + { + var arcSize = new Size(radiusX, radiusY); + + // The rectangle is constructed as follows: + // + // (origin) + // Corner 4 Corner 1 + // Top/Left Line 1 Top/Right + // \_ __________ _/ + // | | + // Line 4 | | Line 2 + // _ |__________| _ + // / Line 3 \ + // Corner 3 Corner 2 + // Bottom/Left Bottom/Right + // + // - Lines 1,3 follow the deflated rectangle bounds minus RadiusX + // - Lines 2,4 follow the deflated rectangle bounds minus RadiusY + // - All corners are constructed using elliptical arcs + + context.BeginFigure(new Point(rect.Left + radiusX, rect.Top), isFilled: true); + + // Line 1 + Corner 1 + context.LineTo(new Point(rect.Right - radiusX, rect.Top)); + context.ArcTo( + new Point(rect.Right, rect.Top + radiusY), + arcSize, + rotationAngle: PiOver2, + isLargeArc: false, + SweepDirection.Clockwise); + + // Line 2 + Corner 2 + context.LineTo(new Point(rect.Right, rect.Bottom - radiusY)); + context.ArcTo( + new Point(rect.Right - radiusX, rect.Bottom), + arcSize, + rotationAngle: PiOver2, + isLargeArc: false, + SweepDirection.Clockwise); + + // Line 3 + Corner 3 + context.LineTo(new Point(rect.Left + radiusX, rect.Bottom)); + context.ArcTo( + new Point(rect.Left, rect.Bottom - radiusY), + arcSize, + rotationAngle: PiOver2, + isLargeArc: false, + SweepDirection.Clockwise); + + // Line 4 + Corner 4 + context.LineTo(new Point(rect.Left, rect.Top + radiusY)); + context.ArcTo( + new Point(rect.Left + radiusX, rect.Top), + arcSize, + rotationAngle: PiOver2, + isLargeArc: false, + SweepDirection.Clockwise); + + context.EndFigure(isClosed: true); + } + + /// <summary> + /// Calculates the keypoints of a rounded rectangle based on the algorithm in WinUI. + /// These keypoints may then be drawn or transformed into other types. + /// </summary> + /// <param name="outerBounds">The outer bounds of the rounded rectangle. + /// This should be the overall bounds and size of the shape/control without any + /// corner radii or border thickness adjustments.</param> + /// <param name="borderThickness">The unadjusted border thickness of the rounded rectangle.</param> + /// <param name="cornerRadius">The unadjusted corner radii of the rounded rectangle. + /// The corner radius is defined to be the middle of the border stroke (center of the border).</param> + /// <param name="sizing">The sizing mode used to calculate the final rounded rectangle size.</param> + /// <returns>New rounded rectangle keypoints.</returns> + public static RoundedRectKeypoints CalculateRoundedCornersRectangleWinUI( + Rect outerBounds, + Thickness borderThickness, + CornerRadius cornerRadius, + BackgroundSizing sizing) + { + // This was initially derived from WinUI: + // - CGeometryBuilder::CalculateRoundedCornersRectangle + // https://github.com/microsoft/microsoft-ui-xaml/blob/93742a178db8f625ba9299f62c21f656e0b195ad/dxaml/xcp/core/core/elements/geometry.cpp#L862-L869 + // + // It has been modified to accept a BackgroundSizing parameter directly as well + // as to support BackgroundSizing.CenterBorder. + // + // Keep in mind: + // > In Xaml, the corner radius is defined to be the middle of the stroke + // > (i.e. half the border thickness extends to either side). + + bool fOuter; + Rect boundRect = outerBounds; + + if (sizing == BackgroundSizing.InnerBorderEdge) + { + boundRect = outerBounds.Deflate(borderThickness); + fOuter = false; + } + else if (sizing == BackgroundSizing.OuterBorderEdge) + { + fOuter = true; + } + else // CenterBorder + { + // This is a trick to support a 3rd state (CenterBorder) using the same WinUI-based algorithm. + // The WinUI algorithm only supports the fOuter = True|False parameter. + boundRect = outerBounds.Deflate(borderThickness * 0.5); + fOuter = false; + } + + // Start of WinUI converted code + // WinUI's Point struct fields can be modified directly, Avalonia's Point is read-only. + // Therefore, we will use doubles for calculation so multiple Point structs aren't + // required during calculations -- everything can be done with these double variables. + double fLeftTop; + double fLeftBottom; + double fTopLeft; + double fTopRight; + double fRightTop; + double fRightBottom; + double fBottomLeft; + double fBottomRight; + + double left; + double right; + double top; + double bottom; + + // If the caller wants to take the border into account + // initialize the borders variables + if (borderThickness != default) + { + left = 0.5 * borderThickness.Left; + right = 0.5 * borderThickness.Right; + top = 0.5 * borderThickness.Top; + bottom = 0.5 * borderThickness.Bottom; + } + else + { + left = 0.0; + right = 0.0; + top = 0.0; + bottom = 0.0; + } + + // The following if/else block initializes the variables + // of which the points of the path will be created + // In case of outer, add the border - if any. + // Otherwise (inner rectangle) subtract the border - if any + if (fOuter) + { + if (MathUtilities.AreClose(cornerRadius.TopLeft, 0.0, Epsilon)) + { + fLeftTop = 0.0; + fTopLeft = 0.0; + } + else + { + fLeftTop = cornerRadius.TopLeft + left; + fTopLeft = cornerRadius.TopLeft + top; + } + + if (MathUtilities.AreClose(cornerRadius.TopRight, 0.0, Epsilon)) + { + fTopRight = 0.0; + fRightTop = 0.0; + } + else + { + fTopRight = cornerRadius.TopRight + top; + fRightTop = cornerRadius.TopRight + right; + } + + if (MathUtilities.AreClose(cornerRadius.BottomRight, 0.0, Epsilon)) + { + fRightBottom = 0.0; + fBottomRight = 0.0; + } + else + { + fRightBottom = cornerRadius.BottomRight + right; + fBottomRight = cornerRadius.BottomRight + bottom; + } + + if (MathUtilities.AreClose(cornerRadius.BottomLeft, 0.0, Epsilon)) + { + fBottomLeft = 0.0; + fLeftBottom = 0.0; + } + else + { + fBottomLeft = cornerRadius.BottomLeft + bottom; + fLeftBottom = cornerRadius.BottomLeft + left; + } + } + else + { + fLeftTop = Math.Max(0.0, cornerRadius.TopLeft - left); + fTopLeft = Math.Max(0.0, cornerRadius.TopLeft - top); + fTopRight = Math.Max(0.0, cornerRadius.TopRight - top); + fRightTop = Math.Max(0.0, cornerRadius.TopRight - right); + fRightBottom = Math.Max(0.0, cornerRadius.BottomRight - right); + fBottomRight = Math.Max(0.0, cornerRadius.BottomRight - bottom); + fBottomLeft = Math.Max(0.0, cornerRadius.BottomLeft - bottom); + fLeftBottom = Math.Max(0.0, cornerRadius.BottomLeft - left); + } + + double topLeftX = fLeftTop; + double topLeftY = 0; + + double topRightX = boundRect.Width - fRightTop; + double topRightY = 0; + + double rightTopX = boundRect.Width; + double rightTopY = fTopRight; + + double rightBottomX = boundRect.Width; + double rightBottomY = boundRect.Height - fBottomRight; + + double bottomRightX = boundRect.Width - fRightBottom; + double bottomRightY = boundRect.Height; + + double bottomLeftX = fLeftBottom; + double bottomLeftY = boundRect.Height; + + double leftBottomX = 0; + double leftBottomY = boundRect.Height - fBottomLeft; + + double leftTopX = 0; + double leftTopY = fTopLeft; + + // check keypoints for overlap and resolve by partitioning radii according to + // the percentage of each one. + + // top edge + if (topLeftX > topRightX) + { + double v = (fLeftTop) / (fLeftTop + fRightTop) * boundRect.Width; + topLeftX = v; + topRightX = v; + } + // right edge + if (rightTopY > rightBottomY) + { + double v = (fTopRight) / (fTopRight + fBottomRight) * boundRect.Height; + rightTopY = v; + rightBottomY = v; + } + // bottom edge + if (bottomRightX < bottomLeftX) + { + double v = (fLeftBottom) / (fLeftBottom + fRightBottom) * boundRect.Width; + bottomRightX = v; + bottomLeftX = v; + } + // left edge + if (leftBottomY < leftTopY) + { + double v = (fTopLeft) / (fTopLeft + fBottomLeft) * boundRect.Height; + leftBottomY = v; + leftTopY = v; + } + + // The above code does all calculations without taking into consideration X/Y absolute position. + // In WinUI, this is compensated for in DrawRoundedCornersRectangle(); however, we do this here directly + // when the final keypoints are being created. + var keypoints = new RoundedRectKeypoints(); + keypoints.TopLeft = new Point( + boundRect.X + topLeftX, + boundRect.Y + topLeftY); + keypoints.TopRight = new Point( + boundRect.X + topRightX, + boundRect.Y + topRightY); + + keypoints.RightTop = new Point( + boundRect.X + rightTopX, + boundRect.Y + rightTopY); + keypoints.RightBottom = new Point( + boundRect.X + rightBottomX, + boundRect.Y + rightBottomY); + + keypoints.BottomRight = new Point( + boundRect.X + bottomRightX, + boundRect.Y + bottomRightY); + keypoints.BottomLeft = new Point( + boundRect.X + bottomLeftX, + boundRect.Y + bottomLeftY); + + keypoints.LeftBottom = new Point( + boundRect.X + leftBottomX, + boundRect.Y + leftBottomY); + keypoints.LeftTop = new Point( + boundRect.X + leftTopX, + boundRect.Y + leftTopY); + + return keypoints; + } + + /// <summary> + /// Represents the keypoints of a rounded rectangle. + /// These keypoints can be shared between methods and turned into geometry. + /// </summary> + /// <remarks> + /// A rounded rectangle is the base geometric shape used when drawing borders. + /// It is a superset of a simple rectangle (which has corner radii set to zero). + /// These keypoints can be combined together to produce geometries for both background + /// and border elements. + /// </remarks> + internal struct RoundedRectKeypoints + { + // The following keypoints are defined for a rounded rectangle: + // + // TopLeft TopRight + // *--------------------------------* + // (start) / \ + // LeftTop * * RightTop + // | | + // | | + // LeftBottom * * RightBottom + // \ / + // *--------------------------------* + // BottomLeft BottomRight + // + // Or, for a simple rectangle without corner radii: + // + // TopLeft = LeftTop TopRight = RightTop + // (start) *------------------------------------* + // | | + // | | + // *------------------------------------* + // BottomLeft = LeftBottom BottomRight = RightBottom + + /// <summary> + /// Initializes a new instance of the <see cref="RoundedRectKeypoints"/> struct. + /// </summary> + public RoundedRectKeypoints() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RoundedRectKeypoints"/> struct. + /// </summary> + /// <param name="roundedRect">An existing <see cref="RoundedRect"/> to initialize keypoints with.</param> + public RoundedRectKeypoints(RoundedRect roundedRect) + { + LeftTop = new Point( + roundedRect.Rect.TopLeft.X, + roundedRect.Rect.TopLeft.Y + roundedRect.RadiiTopLeft.Y); + TopLeft = new Point( + roundedRect.Rect.TopLeft.X + roundedRect.RadiiTopLeft.X, + roundedRect.Rect.TopLeft.Y); + TopRight = new Point( + roundedRect.Rect.TopRight.X - roundedRect.RadiiTopRight.X, + roundedRect.Rect.TopRight.Y); + RightTop = new Point( + roundedRect.Rect.TopRight.X, + roundedRect.Rect.TopRight.Y + roundedRect.RadiiTopRight.Y); + RightBottom = new Point( + roundedRect.Rect.BottomRight.X, + roundedRect.Rect.BottomRight.Y - roundedRect.RadiiBottomRight.Y); + BottomRight = new Point( + roundedRect.Rect.BottomRight.X - roundedRect.RadiiBottomRight.X, + roundedRect.Rect.BottomRight.Y); + BottomLeft = new Point( + roundedRect.Rect.BottomLeft.X + roundedRect.RadiiBottomLeft.X, + roundedRect.Rect.BottomLeft.Y); + LeftBottom = new Point( + roundedRect.Rect.BottomLeft.X, + roundedRect.Rect.BottomRight.Y - roundedRect.RadiiBottomLeft.Y); + } + + /// <summary> + /// Gets the topmost point in the left line segment of the rectangle. + /// </summary> + public Point LeftTop { get; set; } + + /// <summary> + /// Gets the leftmost point in the top line segment of the rectangle. + /// </summary> + public Point TopLeft { get; set; } + + /// <summary> + /// Gets the rightmost point in the top line segment of the rectangle. + /// </summary> + public Point TopRight { get; set; } + + /// <summary> + /// Gets the topmost point in the right line segment of the rectangle. + /// </summary> + public Point RightTop { get; set; } + + /// <summary> + /// Gets the bottommost point in the right line segment of the rectangle. + /// </summary> + public Point RightBottom { get; set; } + + /// <summary> + /// Gets the rightmost point in the bottom line segment of the rectangle. + /// </summary> + public Point BottomRight { get; set; } + + /// <summary> + /// Gets the leftmost point in the bottom line segment of the rectangle. + /// </summary> + public Point BottomLeft { get; set; } + + /// <summary> + /// Gets the bottommost point in the left line segment of the rectangle. + /// </summary> + public Point LeftBottom { get; set; } + + /// <summary> + /// Gets a value indicating whether the rounded rectangle is actually rounded on + /// any corner. If false the key points represent a simple rectangle. + /// </summary> + public bool IsRounded + { + get + { + return (TopLeft != LeftTop || + TopRight != RightTop || + BottomLeft != LeftBottom || + BottomRight != RightBottom); + } + } + + /// <summary> + /// Converts the keypoints into a simple rectangle (with no corners). + /// This is equivalent to the outer rectangle with zero corner radii. + /// </summary> + /// <remarks> + /// Warning: This will force the keypoints into a simple rectangle without + /// any rounded corners. Use <see cref="IsRounded"/> to determine if corner + /// information is otherwise available. + /// </remarks> + /// <returns>A new rectangle representing the keypoints.</returns> + public Rect ToRect() + { + return new Rect( + topLeft: new Point( + x: LeftTop.X, + y: TopLeft.Y), + bottomRight: new Point( + x: RightBottom.X, + y: BottomRight.Y)); + } + + /// <summary> + /// Converts the keypoints into a rounded rectangle with elliptical corner radii. + /// </summary> + /// <remarks> + /// Elliptical corner radius (represented by <see cref="Vector"/>) is more powerful + /// than circular corner radius (represented by a <see cref="CornerRadius"/>). + /// Elliptical is a superset of circular. + /// </remarks> + /// <returns>A new rounded rectangle representing the keypoints.</returns> + public RoundedRect ToRoundedRect() + { + return new RoundedRect( + ToRect(), + radiiTopLeft: new Vector( + x: TopLeft.X - LeftTop.X, + y: LeftTop.Y - TopLeft.Y), + radiiTopRight: new Vector( + x: RightTop.X - TopRight.X, + y: RightTop.Y - TopRight.Y), + radiiBottomRight: new Vector( + x: RightBottom.X - BottomRight.X, + y: BottomRight.Y - RightBottom.Y), + radiiBottomLeft: new Vector( + x: BottomLeft.X - LeftBottom.X, + y: BottomLeft.Y - LeftBottom.Y)); + } + } + } +} diff --git a/src/Avalonia.Base/Media/RectangleGeometry.cs b/src/Avalonia.Base/Media/RectangleGeometry.cs index 01771242a7c..e97a240fc4d 100644 --- a/src/Avalonia.Base/Media/RectangleGeometry.cs +++ b/src/Avalonia.Base/Media/RectangleGeometry.cs @@ -1,4 +1,3 @@ -using System; using Avalonia.Platform; namespace Avalonia.Media @@ -8,6 +7,18 @@ namespace Avalonia.Media /// </summary> public class RectangleGeometry : Geometry { + /// <summary> + /// Defines the <see cref="RadiusX"/> property. + /// </summary> + public static readonly StyledProperty<double> RadiusXProperty = + AvaloniaProperty.Register<RectangleGeometry, double>(nameof(RadiusX)); + + /// <summary> + /// Defines the <see cref="RadiusY"/> property. + /// </summary> + public static readonly StyledProperty<double> RadiusYProperty = + AvaloniaProperty.Register<RectangleGeometry, double>(nameof(RadiusY)); + /// <summary> /// Defines the <see cref="Rect"/> property. /// </summary> @@ -16,7 +27,10 @@ public class RectangleGeometry : Geometry static RectangleGeometry() { - AffectsGeometry(RectProperty); + AffectsGeometry( + RadiusXProperty, + RadiusYProperty, + RectProperty); } /// <summary> @@ -35,6 +49,47 @@ public RectangleGeometry(Rect rect) Rect = rect; } + /// <summary> + /// Initializes a new instance of the <see cref="RectangleGeometry"/> class. + /// </summary> + /// <param name="rect">The rectangle bounds.</param> + /// <param name="radiusX">The radius on the X-axis used to round the corners of the rectangle.</param> + /// <param name="radiusY">The radius on the Y-axis used to round the corners of the rectangle.</param> + public RectangleGeometry(Rect rect, double radiusX, double radiusY) + { + Rect = rect; + RadiusX = radiusX; + RadiusY = radiusY; + } + + /// <summary> + /// Gets or sets the radius on the X-axis used to round the corners of the rectangle. + /// Corner radii are represented by an ellipse so this is the X-axis width of the ellipse. + /// </summary> + /// <remarks> + /// In order for this property to be used, <see cref="Rect"/> must not be set + /// (equal to the default <see cref="Avalonia.Rect"/> value). + /// </remarks> + public double RadiusX + { + get => GetValue(RadiusXProperty); + set => SetValue(RadiusXProperty, value); + } + + /// <summary> + /// Gets or sets the radius on the Y-axis used to round the corners of the rectangle. + /// Corner radii are represented by an ellipse so this is the Y-axis height of the ellipse. + /// </summary> + /// <remarks> + /// In order for this property to be used, <see cref="Rect"/> must not be set + /// (equal to the default <see cref="Avalonia.Rect"/> value). + /// </remarks> + public double RadiusY + { + get => GetValue(RadiusYProperty); + set => SetValue(RadiusYProperty, value); + } + /// <summary> /// Gets or sets the bounds of the rectangle. /// </summary> @@ -49,9 +104,25 @@ public Rect Rect private protected sealed override IGeometryImpl? CreateDefiningGeometry() { + double radiusX = RadiusX; + double radiusY = RadiusY; var factory = AvaloniaLocator.Current.GetRequiredService<IPlatformRenderInterface>(); - return factory.CreateRectangleGeometry(Rect); + if (radiusX == 0 && radiusY == 0) + { + // Optimization when there are no corner radii + return factory.CreateRectangleGeometry(Rect); + } + else + { + var geometry = factory.CreateStreamGeometry(); + using (var ctx = new StreamGeometryContext(geometry.Open())) + { + GeometryBuilder.DrawRoundedCornersRectangle(ctx, Rect, radiusX, radiusY); + } + + return geometry; + } } } } diff --git a/src/Avalonia.Base/RoundedRect.cs b/src/Avalonia.Base/RoundedRect.cs index 0b23a8c0caf..c39dbd1b1f2 100644 --- a/src/Avalonia.Base/RoundedRect.cs +++ b/src/Avalonia.Base/RoundedRect.cs @@ -36,8 +36,13 @@ public override int GetHashCode() public Vector RadiiTopRight { get; } public Vector RadiiBottomLeft { get; } public Vector RadiiBottomRight { get; } - - public RoundedRect(Rect rect, Vector radiiTopLeft, Vector radiiTopRight, Vector radiiBottomRight, Vector radiiBottomLeft) + + public RoundedRect( + Rect rect, + Vector radiiTopLeft, + Vector radiiTopRight, + Vector radiiBottomRight, + Vector radiiBottomLeft) { Rect = rect; RadiiTopLeft = radiiTopLeft; @@ -46,7 +51,11 @@ public RoundedRect(Rect rect, Vector radiiTopLeft, Vector radiiTopRight, Vector RadiiBottomLeft = radiiBottomLeft; } - public RoundedRect(Rect rect, double radiusTopLeft, double radiusTopRight, double radiusBottomRight, + public RoundedRect( + Rect rect, + double radiusTopLeft, + double radiusTopRight, + double radiusBottomRight, double radiusBottomLeft) : this(rect, new Vector(radiusTopLeft, radiusTopLeft), @@ -55,34 +64,28 @@ public RoundedRect(Rect rect, double radiusTopLeft, double radiusTopRight, doubl new Vector(radiusBottomLeft, radiusBottomLeft) ) { - } public RoundedRect(Rect rect, Vector radii) : this(rect, radii, radii, radii, radii) { - } public RoundedRect(Rect rect, double radiusX, double radiusY) : this(rect, new Vector(radiusX, radiusY)) { - } public RoundedRect(Rect rect, double radius) : this(rect, radius, radius) { - } public RoundedRect(Rect rect) : this(rect, 0) { - } public RoundedRect(in Rect bounds, in CornerRadius radius) : this(bounds, radius.TopLeft, radius.TopRight, radius.BottomRight, radius.BottomLeft) { - } public static implicit operator RoundedRect(Rect r) => new RoundedRect(r); @@ -99,7 +102,7 @@ public RoundedRect Inflate(double dx, double dy) { return Deflate(-dx, -dy); } - + public unsafe RoundedRect Deflate(double dx, double dy) { if (!IsRounded) @@ -143,7 +146,7 @@ public unsafe RoundedRect Deflate(double dx, double dy) return new RoundedRect(new Rect(left, top, right - left, bottom - top), radii[0], radii[1], radii[2], radii[3]); } - + /// <summary> /// This method should be used internally to check for the rect emptiness /// Once we add support for WPF-like empty rects, there will be an actual implementation diff --git a/src/Avalonia.Controls/Border.cs b/src/Avalonia.Controls/Border.cs index e7373a813e4..4eb0274ec72 100644 --- a/src/Avalonia.Controls/Border.cs +++ b/src/Avalonia.Controls/Border.cs @@ -23,6 +23,14 @@ public partial class Border : Decorator, IVisualWithRoundRectClip public static readonly StyledProperty<IBrush?> BackgroundProperty = AvaloniaProperty.Register<Border, IBrush?>(nameof(Background)); + /// <summary> + /// Defines the <see cref="BackgroundSizing"/> property. + /// </summary> + public static readonly StyledProperty<BackgroundSizing> BackgroundSizingProperty = + AvaloniaProperty.Register<Border, BackgroundSizing>( + nameof(BackgroundSizing), + BackgroundSizing.CenterBorder); + /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> @@ -59,6 +67,7 @@ static Border() { AffectsRender<Border>( BackgroundProperty, + BackgroundSizingProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty, @@ -91,6 +100,15 @@ public IBrush? Background set => SetValue(BackgroundProperty, value); } + /// <summary> + /// Gets or sets how the background is drawn relative to the border. + /// </summary> + public BackgroundSizing BackgroundSizing + { + get => GetValue(BackgroundSizingProperty); + set => SetValue(BackgroundSizingProperty, value); + } + /// <summary> /// Gets or sets a brush with which to paint the border. /// </summary> @@ -168,6 +186,7 @@ public sealed override void Render(DrawingContext context) Bounds.Size, LayoutThickness, CornerRadius, + BackgroundSizing, Background, BorderBrush, BoxShadow); diff --git a/src/Avalonia.Controls/ContentControl.cs b/src/Avalonia.Controls/ContentControl.cs index 4d32658e0dc..cf3f1c845a6 100644 --- a/src/Avalonia.Controls/ContentControl.cs +++ b/src/Avalonia.Controls/ContentControl.cs @@ -47,6 +47,7 @@ static ContentControl() { Name = "PART_ContentPresenter", [~BackgroundProperty] = new TemplateBinding(BackgroundProperty), + [~BackgroundSizingProperty] = new TemplateBinding(BackgroundSizingProperty), [~BorderBrushProperty] = new TemplateBinding(BorderBrushProperty), [~BorderThicknessProperty] = new TemplateBinding(BorderThicknessProperty), [~CornerRadiusProperty] = new TemplateBinding(CornerRadiusProperty), diff --git a/src/Avalonia.Controls/Presenters/ContentPresenter.cs b/src/Avalonia.Controls/Presenters/ContentPresenter.cs index 02a8fb7d2c1..76a882df129 100644 --- a/src/Avalonia.Controls/Presenters/ContentPresenter.cs +++ b/src/Avalonia.Controls/Presenters/ContentPresenter.cs @@ -25,6 +25,12 @@ public class ContentPresenter : Control public static readonly StyledProperty<IBrush?> BackgroundProperty = Border.BackgroundProperty.AddOwner<ContentPresenter>(); + /// <summary> + /// Defines the <see cref="BackgroundSizing"/> property. + /// </summary> + public static readonly StyledProperty<BackgroundSizing> BackgroundSizingProperty = + Border.BackgroundSizingProperty.AddOwner<ContentPresenter>(); + /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> @@ -171,10 +177,12 @@ static ContentPresenter() { AffectsRender<ContentPresenter>( BackgroundProperty, + BackgroundSizingProperty, BorderBrushProperty, BorderThicknessProperty, - CornerRadiusProperty, - BoxShadowProperty); + BoxShadowProperty, + CornerRadiusProperty); + AffectsArrange<ContentPresenter>(HorizontalContentAlignmentProperty, VerticalContentAlignmentProperty); AffectsMeasure<ContentPresenter>(BorderThicknessProperty, PaddingProperty); } @@ -184,45 +192,42 @@ public ContentPresenter() UpdatePseudoClasses(); } - /// <summary> - /// Gets or sets a brush with which to paint the background. - /// </summary> + /// <inheritdoc cref="Border.Background"/> public IBrush? Background { get => GetValue(BackgroundProperty); set => SetValue(BackgroundProperty, value); } - /// <summary> - /// Gets or sets a brush with which to paint the border. - /// </summary> + /// <inheritdoc cref="Border.BackgroundSizing"/> + public BackgroundSizing BackgroundSizing + { + get => GetValue(BackgroundSizingProperty); + set => SetValue(BackgroundSizingProperty, value); + } + + /// <inheritdoc cref="Border.BorderBrush"/> public IBrush? BorderBrush { get => GetValue(BorderBrushProperty); set => SetValue(BorderBrushProperty, value); } - /// <summary> - /// Gets or sets the thickness of the border. - /// </summary> + /// <inheritdoc cref="Border.BorderThickness"/> public Thickness BorderThickness { get => GetValue(BorderThicknessProperty); set => SetValue(BorderThicknessProperty, value); } - /// <summary> - /// Gets or sets the radius of the border rounded corners. - /// </summary> + /// <inheritdoc cref="Border.CornerRadius"/> public CornerRadius CornerRadius { get => GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } - /// <summary> - /// Gets or sets the box shadow effect parameters - /// </summary> + /// <inheritdoc cref="Border.BoxShadow"/> public BoxShadows BoxShadow { get => GetValue(BoxShadowProperty); @@ -541,7 +546,14 @@ private void VerifyScale() /// <inheritdoc/> public sealed override void Render(DrawingContext context) { - _borderRenderer.Render(context, Bounds.Size, LayoutThickness, CornerRadius, Background, BorderBrush, + _borderRenderer.Render( + context, + Bounds.Size, + LayoutThickness, + CornerRadius, + BackgroundSizing, + Background, + BorderBrush, BoxShadow); } diff --git a/src/Avalonia.Controls/Primitives/TemplatedControl.cs b/src/Avalonia.Controls/Primitives/TemplatedControl.cs index c232fdcc12d..1fef3821592 100644 --- a/src/Avalonia.Controls/Primitives/TemplatedControl.cs +++ b/src/Avalonia.Controls/Primitives/TemplatedControl.cs @@ -22,6 +22,12 @@ public class TemplatedControl : Control public static readonly StyledProperty<IBrush?> BackgroundProperty = Border.BackgroundProperty.AddOwner<TemplatedControl>(); + /// <summary> + /// Defines the <see cref="BackgroundSizing"/> property. + /// </summary> + public static readonly StyledProperty<BackgroundSizing> BackgroundSizingProperty = + Border.BackgroundSizingProperty.AddOwner<TemplatedControl>(); + /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> @@ -131,6 +137,15 @@ public IBrush? Background set => SetValue(BackgroundProperty, value); } + /// <summary> + /// Gets or sets how the control's background is drawn relative to the control's border. + /// </summary> + public BackgroundSizing BackgroundSizing + { + get => GetValue(BackgroundSizingProperty); + set => SetValue(BackgroundSizingProperty, value); + } + /// <summary> /// Gets or sets the brush used to draw the control's border. /// </summary> diff --git a/src/Avalonia.Controls/Shapes/Rectangle.cs b/src/Avalonia.Controls/Shapes/Rectangle.cs index d60180bab4b..cfccf0d588b 100644 --- a/src/Avalonia.Controls/Shapes/Rectangle.cs +++ b/src/Avalonia.Controls/Shapes/Rectangle.cs @@ -7,8 +7,6 @@ namespace Avalonia.Controls.Shapes /// </summary> public class Rectangle : Shape { - private const double PiOver2 = 1.57079633; // 90 deg to rad - /// <summary> /// Defines the <see cref="RadiusX"/> property. /// </summary> @@ -30,20 +28,14 @@ static Rectangle() StrokeThicknessProperty); } - /// <summary> - /// Gets or sets the radius on the X-axis used to round the corners of the rectangle. - /// Corner radii are represented by an ellipse so this is the X-axis width of the ellipse. - /// </summary> + /// <inheritdoc cref="RectangleGeometry.RadiusX"/> public double RadiusX { get => GetValue(RadiusXProperty); set => SetValue(RadiusXProperty, value); } - /// <summary> - /// Gets or sets the radius on the Y-axis used to round the corners of the rectangle. - /// Corner radii are represented by an ellipse so this is the Y-axis height of the ellipse. - /// </summary> + /// <inheritdoc cref="RectangleGeometry.RadiusY"/> public double RadiusY { get => GetValue(RadiusYProperty); @@ -53,85 +45,9 @@ public double RadiusY /// <inheritdoc/> protected override Geometry CreateDefiningGeometry() { - // TODO: If RectangleGeometry ever supports RadiusX/Y like in WPF, - // this code can be removed/combined with that implementation - - double x = RadiusX; - double y = RadiusY; - - if (x == 0 && y == 0) - { - // Optimization when there are no corner radii - var rect = new Rect(Bounds.Size).Deflate(StrokeThickness / 2); - return new RectangleGeometry(rect); - } - else - { - var rect = new Rect(Bounds.Size).Deflate(StrokeThickness / 2); - var geometry = new StreamGeometry(); - var arcSize = new Size(x, y); - - using (StreamGeometryContext context = geometry.Open()) - { - // The rectangle is constructed as follows: - // - // (origin) - // Corner 4 Corner 1 - // Top/Left Line 1 Top/Right - // \_ __________ _/ - // | | - // Line 4 | | Line 2 - // _ |__________| _ - // / Line 3 \ - // Corner 3 Corner 2 - // Bottom/Left Bottom/Right - // - // - Lines 1,3 follow the deflated rectangle bounds minus RadiusX - // - Lines 2,4 follow the deflated rectangle bounds minus RadiusY - // - All corners are constructed using elliptical arcs - - // Line 1 + Corner 1 - context.BeginFigure(new Point(rect.Left + x, rect.Top), true); - context.LineTo(new Point(rect.Right - x, rect.Top)); - context.ArcTo( - new Point(rect.Right, rect.Top + y), - arcSize, - rotationAngle: PiOver2, - isLargeArc: false, - SweepDirection.Clockwise); - - // Line 2 + Corner 2 - context.LineTo(new Point(rect.Right, rect.Bottom - y)); - context.ArcTo( - new Point(rect.Right - x, rect.Bottom), - arcSize, - rotationAngle: PiOver2, - isLargeArc: false, - SweepDirection.Clockwise); - - // Line 3 + Corner 3 - context.LineTo(new Point(rect.Left + x, rect.Bottom)); - context.ArcTo( - new Point(rect.Left, rect.Bottom - y), - arcSize, - rotationAngle: PiOver2, - isLargeArc: false, - SweepDirection.Clockwise); - - // Line 4 + Corner 4 - context.LineTo(new Point(rect.Left, rect.Top + y)); - context.ArcTo( - new Point(rect.Left + x, rect.Top), - arcSize, - rotationAngle: PiOver2, - isLargeArc: false, - SweepDirection.Clockwise); - - context.EndFigure(true); - } + var rect = new Rect(Bounds.Size).Deflate(StrokeThickness / 2); - return geometry; - } + return new RectangleGeometry(rect, RadiusX, RadiusY); } /// <inheritdoc/> diff --git a/src/Avalonia.Controls/Utils/BorderRenderHelper.cs b/src/Avalonia.Controls/Utils/BorderRenderHelper.cs index 4df4fd738a0..f86ddb0d2dc 100644 --- a/src/Avalonia.Controls/Utils/BorderRenderHelper.cs +++ b/src/Avalonia.Controls/Utils/BorderRenderHelper.cs @@ -1,35 +1,38 @@ -using System; -using Avalonia.Collections; -using Avalonia.Media; -using Avalonia.Media.Immutable; +using Avalonia.Media; using Avalonia.Platform; using Avalonia.Utilities; namespace Avalonia.Controls.Utils { + /// <summary> + /// Contains helper methods for rendering a <see cref="Border"/>'s background and border to a given context. + /// </summary> internal class BorderRenderHelper { private bool _useComplexRendering; private bool? _backendSupportsIndividualCorners; - private StreamGeometry? _backgroundGeometryCache; - private StreamGeometry? _borderGeometryCache; + private Geometry? _backgroundGeometryCache; + private Geometry? _borderGeometryCache; private Size _size; private Thickness _borderThickness; private CornerRadius _cornerRadius; + private BackgroundSizing _backgroundSizing; private bool _initialized; private IPen? _cachedPen; - - void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius) + private void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius, BackgroundSizing backgroundSizing) { _backendSupportsIndividualCorners ??= AvaloniaLocator.Current.GetRequiredService<IPlatformRenderInterface>() .SupportsIndividualRoundRects; _size = finalSize; _borderThickness = borderThickness; _cornerRadius = cornerRadius; + _backgroundSizing = backgroundSizing; _initialized = true; - if (borderThickness.IsUniform && (cornerRadius.IsUniform || _backendSupportsIndividualCorners == true)) + if (borderThickness.IsUniform && + (cornerRadius.IsUniform || _backendSupportsIndividualCorners == true) && + backgroundSizing == BackgroundSizing.CenterBorder) { _backgroundGeometryCache = null; _borderGeometryCache = null; @@ -41,17 +44,19 @@ void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius var boundRect = new Rect(finalSize); var innerRect = boundRect.Deflate(borderThickness); - BorderGeometryKeypoints? backgroundKeypoints = null; - StreamGeometry? backgroundGeometry = null; if (innerRect.Width != 0 && innerRect.Height != 0) { - backgroundGeometry = new StreamGeometry(); - backgroundKeypoints = new BorderGeometryKeypoints(innerRect, borderThickness, cornerRadius, true); + var backgroundOuterKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( + boundRect, + borderThickness, + cornerRadius, + backgroundSizing); + var backgroundGeometry = new StreamGeometry(); using (var ctx = backgroundGeometry.Open()) { - CreateGeometry(ctx, innerRect, backgroundKeypoints); + GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref backgroundOuterKeypoints); } _backgroundGeometryCache = backgroundGeometry; @@ -63,21 +68,30 @@ void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius if (boundRect.Width != 0 && boundRect.Height != 0) { - var borderGeometryKeypoints = - new BorderGeometryKeypoints(boundRect, borderThickness, cornerRadius, false); - var borderGeometry = new StreamGeometry(); - - using (var ctx = borderGeometry.Open()) + var borderInnerKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( + boundRect, + borderThickness, + cornerRadius, + BackgroundSizing.InnerBorderEdge); + var borderOuterKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( + boundRect, + borderThickness, + cornerRadius, + BackgroundSizing.OuterBorderEdge); + + var borderInnerGeometry = new StreamGeometry(); + using (var ctx = borderInnerGeometry.Open()) { - CreateGeometry(ctx, boundRect, borderGeometryKeypoints); + GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref borderInnerKeypoints); + } - if (backgroundGeometry != null) - { - CreateGeometry(ctx, innerRect, backgroundKeypoints!); - } + var borderOuterGeometry = new StreamGeometry(); + using (var ctx = borderOuterGeometry.Open()) + { + GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref borderOuterKeypoints); } - _borderGeometryCache = borderGeometry; + _borderGeometryCache = new CombinedGeometry(GeometryCombineMode.Exclude, borderOuterGeometry, borderInnerGeometry); } else { @@ -86,211 +100,51 @@ void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius } } - public void Render(DrawingContext context, - Size finalSize, Thickness borderThickness, CornerRadius cornerRadius, - IBrush? background, IBrush? borderBrush, BoxShadows boxShadows) + public void Render( + DrawingContext context, + Size finalSize, + Thickness borderThickness, + CornerRadius cornerRadius, + BackgroundSizing backgroundSizing, + IBrush? background, + IBrush? borderBrush, + BoxShadows boxShadows) { if (_size != finalSize || _borderThickness != borderThickness || _cornerRadius != cornerRadius + || _backgroundSizing != backgroundSizing || !_initialized) - Update(finalSize, borderThickness, cornerRadius); - RenderCore(context, background, borderBrush, boxShadows); - } + { + Update(finalSize, borderThickness, cornerRadius, backgroundSizing); + } - void RenderCore(DrawingContext context, IBrush? background, IBrush? borderBrush, BoxShadows boxShadows) - { if (_useComplexRendering) { - var backgroundGeometry = _backgroundGeometryCache; - if (backgroundGeometry != null) + if (_backgroundGeometryCache != null) { - context.DrawGeometry(background, null, backgroundGeometry); + context.DrawGeometry(background, null, _backgroundGeometryCache); } - var borderGeometry = _borderGeometryCache; - if (borderGeometry != null) + if (_borderGeometryCache != null) { - context.DrawGeometry(borderBrush, null, borderGeometry); + context.DrawGeometry(borderBrush, null, _borderGeometryCache); } } else { - var borderThickness = _borderThickness.Top; + var thickness = _borderThickness.Top; - Pen.TryModifyOrCreate(ref _cachedPen, borderBrush, borderThickness); + Pen.TryModifyOrCreate(ref _cachedPen, borderBrush, thickness); var rect = new Rect(_size); - if (!MathUtilities.IsZero(borderThickness)) - rect = rect.Deflate(borderThickness * 0.5); + if (!MathUtilities.IsZero(thickness)) + rect = rect.Deflate(thickness * 0.5); var rrect = new RoundedRect(rect, _cornerRadius.TopLeft, _cornerRadius.TopRight, _cornerRadius.BottomRight, _cornerRadius.BottomLeft); context.DrawRectangle(background, _cachedPen, rrect, boxShadows); } } - - private static void CreateGeometry(StreamGeometryContext context, Rect boundRect, - BorderGeometryKeypoints keypoints) - { - context.BeginFigure(keypoints.TopLeft, true); - - // Top - context.LineTo(keypoints.TopRight); - - // TopRight corner - var radiusX = boundRect.TopRight.X - keypoints.TopRight.X; - var radiusY = keypoints.RightTop.Y - boundRect.TopRight.Y; - if (radiusX != 0 || radiusY != 0) - { - context.ArcTo(keypoints.RightTop, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise); - } - - // Right - context.LineTo(keypoints.RightBottom); - - // BottomRight corner - radiusX = boundRect.BottomRight.X - keypoints.BottomRight.X; - radiusY = boundRect.BottomRight.Y - keypoints.RightBottom.Y; - if (radiusX != 0 || radiusY != 0) - { - context.ArcTo(keypoints.BottomRight, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise); - } - - // Bottom - context.LineTo(keypoints.BottomLeft); - - // BottomLeft corner - radiusX = keypoints.BottomLeft.X - boundRect.BottomLeft.X; - radiusY = boundRect.BottomLeft.Y - keypoints.LeftBottom.Y; - if (radiusX != 0 || radiusY != 0) - { - context.ArcTo(keypoints.LeftBottom, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise); - } - - // Left - context.LineTo(keypoints.LeftTop); - - // TopLeft corner - radiusX = keypoints.TopLeft.X - boundRect.TopLeft.X; - radiusY = keypoints.LeftTop.Y - boundRect.TopLeft.Y; - - if (radiusX != 0 || radiusY != 0) - { - context.ArcTo(keypoints.TopLeft, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise); - } - - context.EndFigure(true); - } - - private class BorderGeometryKeypoints - { - internal BorderGeometryKeypoints(Rect boundRect, Thickness borderThickness, CornerRadius cornerRadius, - bool inner) - { - var left = 0.5 * borderThickness.Left; - var top = 0.5 * borderThickness.Top; - var right = 0.5 * borderThickness.Right; - var bottom = 0.5 * borderThickness.Bottom; - - double leftTopY; - double topLeftX; - double topRightX; - double rightTopY; - double rightBottomY; - double bottomRightX; - double bottomLeftX; - double leftBottomY; - - if (inner) - { - leftTopY = Math.Max(0, cornerRadius.TopLeft - top) + boundRect.TopLeft.Y; - topLeftX = Math.Max(0, cornerRadius.TopLeft - left) + boundRect.TopLeft.X; - topRightX = boundRect.Width - Math.Max(0, cornerRadius.TopRight - top) + boundRect.TopLeft.X; - rightTopY = Math.Max(0, cornerRadius.TopRight - right) + boundRect.TopLeft.Y; - rightBottomY = boundRect.Height - Math.Max(0, cornerRadius.BottomRight - bottom) + - boundRect.TopLeft.Y; - bottomRightX = boundRect.Width - Math.Max(0, cornerRadius.BottomRight - right) + - boundRect.TopLeft.X; - bottomLeftX = Math.Max(0, cornerRadius.BottomLeft - left) + boundRect.TopLeft.X; - leftBottomY = boundRect.Height - Math.Max(0, cornerRadius.BottomLeft - bottom) + - boundRect.TopLeft.Y; - } - else - { - leftTopY = cornerRadius.TopLeft + top + boundRect.TopLeft.Y; - topLeftX = cornerRadius.TopLeft + left + boundRect.TopLeft.X; - topRightX = boundRect.Width - (cornerRadius.TopRight + right) + boundRect.TopLeft.X; - rightTopY = cornerRadius.TopRight + top + boundRect.TopLeft.Y; - rightBottomY = boundRect.Height - (cornerRadius.BottomRight + bottom) + boundRect.TopLeft.Y; - bottomRightX = boundRect.Width - (cornerRadius.BottomRight + right) + boundRect.TopLeft.X; - bottomLeftX = cornerRadius.BottomLeft + left + boundRect.TopLeft.X; - leftBottomY = boundRect.Height - (cornerRadius.BottomLeft + bottom) + boundRect.TopLeft.Y; - } - - var leftTopX = boundRect.TopLeft.X; - var topLeftY = boundRect.TopLeft.Y; - var topRightY = boundRect.TopLeft.Y; - var rightTopX = boundRect.Width + boundRect.TopLeft.X; - var rightBottomX = boundRect.Width + boundRect.TopLeft.X; - var bottomRightY = boundRect.Height + boundRect.TopLeft.Y; - var bottomLeftY = boundRect.Height + boundRect.TopLeft.Y; - var leftBottomX = boundRect.TopLeft.X; - - LeftTop = new Point(leftTopX, leftTopY); - TopLeft = new Point(topLeftX, topLeftY); - TopRight = new Point(topRightX, topRightY); - RightTop = new Point(rightTopX, rightTopY); - RightBottom = new Point(rightBottomX, rightBottomY); - BottomRight = new Point(bottomRightX, bottomRightY); - BottomLeft = new Point(bottomLeftX, bottomLeftY); - LeftBottom = new Point(leftBottomX, leftBottomY); - - // Fix overlap - if (TopLeft.X > TopRight.X) - { - var scaledX = topLeftX / (topLeftX + topRightX) * boundRect.Width; - TopLeft = new Point(scaledX, TopLeft.Y); - TopRight = new Point(scaledX, TopRight.Y); - } - - if (RightTop.Y > RightBottom.Y) - { - var scaledY = rightBottomY / (rightTopY + rightBottomY) * boundRect.Height; - RightTop = new Point(RightTop.X, scaledY); - RightBottom = new Point(RightBottom.X, scaledY); - } - - if (BottomRight.X < BottomLeft.X) - { - var scaledX = bottomLeftX / (bottomLeftX + bottomRightX) * boundRect.Width; - BottomRight = new Point(scaledX, BottomRight.Y); - BottomLeft = new Point(scaledX, BottomLeft.Y); - } - - if (LeftBottom.Y < LeftTop.Y) - { - var scaledY = leftTopY / (leftTopY + leftBottomY) * boundRect.Height; - LeftBottom = new Point(LeftBottom.X, scaledY); - LeftTop = new Point(LeftTop.X, scaledY); - } - } - - internal Point LeftTop { get; } - - internal Point TopLeft { get; } - - internal Point TopRight { get; } - - internal Point RightTop { get; } - - internal Point RightBottom { get; } - - internal Point BottomRight { get; } - - internal Point BottomLeft { get; } - - internal Point LeftBottom { get; } - } } }
diff --git a/tests/Avalonia.Base.UnitTests/Media/GeometryBuilderTests.cs b/tests/Avalonia.Base.UnitTests/Media/GeometryBuilderTests.cs new file mode 100644 index 00000000000..a7d390bffea --- /dev/null +++ b/tests/Avalonia.Base.UnitTests/Media/GeometryBuilderTests.cs @@ -0,0 +1,61 @@ +using Avalonia.Media; +using Xunit; + +namespace Avalonia.Base.UnitTests.Media +{ + public class GeometryBuilderTests + { + [Theory] + [InlineData(20.0, 10.0)] + [InlineData(10.0, 5.0)] + [InlineData(2.0, 1.0)] + [InlineData(1.0, 0.0)] + public void CalculateRoundedCornersRectangleWinUI_InnerBorderEdge_Borders_Larger_Than_Corners_Test( + double uniformBorders, + double uniformCorners) + { + var bounds = new Rect(new Size(100, 100)); + var borderThickness = new Thickness(uniformBorders); + var cornerRadius = new CornerRadius(uniformCorners); + + var points = GeometryBuilder.CalculateRoundedCornersRectangleWinUI(bounds, borderThickness, cornerRadius, BackgroundSizing.InnerBorderEdge); + + Assert.Equal(new Point(uniformBorders, uniformBorders), points.LeftTop); + Assert.Equal(new Point(uniformBorders, uniformBorders), points.TopLeft); + Assert.Equal(new Point(100 - uniformBorders, uniformBorders), points.TopRight); + Assert.Equal(new Point(100 - uniformBorders, uniformBorders), points.RightTop); + Assert.Equal(new Point(100 - uniformBorders, 100 - uniformBorders), points.RightBottom); + Assert.Equal(new Point(100 - uniformBorders, 100 - uniformBorders), points.BottomRight); + Assert.Equal(new Point(uniformBorders, 100 - uniformBorders), points.BottomLeft); + Assert.Equal(new Point(uniformBorders, 100 - uniformBorders), points.LeftBottom); + + Assert.False(points.IsRounded); + } + + [Theory] + [InlineData(20.0, 10.0)] + [InlineData(10.0, 5.0)] + [InlineData(2.0, 1.0)] + public void CalculateRoundedCornersRectangleWinUI_OuterBorderEdge_Borders_Larger_Than_Corners_Test( + double uniformBorders, + double uniformCorners) + { + var bounds = new Rect(new Size(100, 100)); + var borderThickness = new Thickness(uniformBorders); + var cornerRadius = new CornerRadius(uniformCorners); + + var points = GeometryBuilder.CalculateRoundedCornersRectangleWinUI(bounds, borderThickness, cornerRadius, BackgroundSizing.OuterBorderEdge); + + Assert.Equal(new Point(0, uniformBorders), points.LeftTop); + Assert.Equal(new Point(uniformBorders, 0), points.TopLeft); + Assert.Equal(new Point(100 - uniformBorders, 0), points.TopRight); + Assert.Equal(new Point(100, uniformBorders), points.RightTop); + Assert.Equal(new Point(100, 100 - uniformBorders), points.RightBottom); + Assert.Equal(new Point(100 - uniformBorders, 100), points.BottomRight); + Assert.Equal(new Point(uniformBorders, 100), points.BottomLeft); + Assert.Equal(new Point(0, 100 - uniformBorders), points.LeftBottom); + + Assert.True(points.IsRounded); + } + } +}
Add RadiusX/RadiusY to RectangleGeometry In WPF RectangleGeometry has `RadiusX` and `RadiusY` properties to get rounded corners. I'd like to use a rounded rectangle as a clipping to a control in Avalonia. In [WPF](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-round-the-corners-of-a-rectanglegeometry?view=netframeworkdesktop-4.8): ```xaml <!-- Create a rectangle with rounded corners by giving the RectangleGeometry a RadiusX and a RadiusY of 10. --> <RectangleGeometry Rect="20,20,150,50" RadiusX="10" RadiusY="10" /> ``` Non-uniform Border Thickness is rendered with corner radius **Describe the bug** Same code ```xaml <Border Width="100" Height="100" BorderBrush="Red" BorderThickness="20,20,20,1" /> ``` In Avalonia ![image](https://github.com/AvaloniaUI/Avalonia/assets/14807942/c5dd11b8-5514-4629-a82e-f448159b1aa3) In WPF ![image](https://github.com/AvaloniaUI/Avalonia/assets/14807942/36f36d42-3b87-4618-9729-1113f917990c) **To Reproduce** **Expected behavior** **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: Windows11 - Version 11p8 **Additional context**
I might get to this over the holidays along with the BackgroundSizing work. What is required here is also similar to what I did for Rectangle itself and I can use it there too. This is coming in with BackgroundSizing. It's sharing the same code a few other places. I think this is not quite a bug but something that can be defined in the render options. In SVG it's common to specify how corner should be rendered. If would really be great if we can define this in `RenderOptions`. Probably defualt to sharp edges. See: - https://inkscape-manuals.readthedocs.io/en/latest/strokes.html?highlight=Join%20type#id4 - https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap - https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linejoin - https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit @Gillibald I think you are quite experienced in this kind of stuff. What do you think about it? For XAML frameworks with separate BorderThickness and CornerRadius properties WPF is correct. This appears to be a bug in Avalonia. That said, both border render paths are going to have to change in order to support BackgroundSizing. It might not be worth the time to fix this right now. WPF has a code path that uses line segments to draw individual borders so that might be the difference here
2023-12-27T21:02:32Z
0.2
['Avalonia.Base.UnitTests.Media.GeometryBuilderTests.CalculateRoundedCornersRectangleWinUI_InnerBorderEdge_Borders_Larger_Than_Corners_Test', 'Avalonia.Base.UnitTests.Media.GeometryBuilderTests.CalculateRoundedCornersRectangleWinUI_OuterBorderEdge_Borders_Larger_Than_Corners_Test']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-14013
2a7b5568b7f61fe6df9c46a05bf1c9d474c9290e
diff --git a/src/Avalonia.Base/Media/PathMarkupParser.cs b/src/Avalonia.Base/Media/PathMarkupParser.cs index 7b9fdf9330d..fa790c17c00 100644 --- a/src/Avalonia.Base/Media/PathMarkupParser.cs +++ b/src/Avalonia.Base/Media/PathMarkupParser.cs @@ -259,7 +259,7 @@ private void AddLine(ref ReadOnlySpan<char> span, bool relative) { ThrowIfDisposed(); - _currentPoint = relative + var next = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); @@ -268,14 +268,15 @@ private void AddLine(ref ReadOnlySpan<char> span, bool relative) CreateFigure(); } - _geometryContext.LineTo(_currentPoint); + _geometryContext.LineTo(next); + _currentPoint = next; } private void AddHorizontalLine(ref ReadOnlySpan<char> span, bool relative) { ThrowIfDisposed(); - _currentPoint = relative + var next = relative ? new Point(_currentPoint.X + ReadDouble(ref span), _currentPoint.Y) : _currentPoint.WithX(ReadDouble(ref span)); @@ -284,14 +285,15 @@ private void AddHorizontalLine(ref ReadOnlySpan<char> span, bool relative) CreateFigure(); } - _geometryContext.LineTo(_currentPoint); + _geometryContext.LineTo(next); + _currentPoint = next; } private void AddVerticalLine(ref ReadOnlySpan<char> span, bool relative) { ThrowIfDisposed(); - _currentPoint = relative + var next = relative ? new Point(_currentPoint.X, _currentPoint.Y + ReadDouble(ref span)) : _currentPoint.WithY(ReadDouble(ref span)); @@ -300,7 +302,8 @@ private void AddVerticalLine(ref ReadOnlySpan<char> span, bool relative) CreateFigure(); } - _geometryContext.LineTo(_currentPoint); + _geometryContext.LineTo(next); + _currentPoint = next; } private void AddCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative)
diff --git a/tests/Avalonia.Base.UnitTests/Media/PathMarkupParserTests.cs b/tests/Avalonia.Base.UnitTests/Media/PathMarkupParserTests.cs index c829690eb4a..755ab7ff25a 100644 --- a/tests/Avalonia.Base.UnitTests/Media/PathMarkupParserTests.cs +++ b/tests/Avalonia.Base.UnitTests/Media/PathMarkupParserTests.cs @@ -319,5 +319,24 @@ public void Should_Parse_Flags_Without_Separator() Assert.IsType<ArcSegment>(arcSegment); } } + + [Fact] + public void Should_Handle_StartPoint_After_Empty_Figure() + { + var pathGeometry = new PathGeometry(); + using var context = new PathGeometryContext(pathGeometry); + using var parser = new PathMarkupParser(context); + parser.Parse("M50,50z l -5,-5"); + + Assert.Equal(2, pathGeometry.Figures.Count); + + var firstFigure = pathGeometry.Figures[0]; + + Assert.Equal(new Point(50, 50), firstFigure.StartPoint); + + var secondFigure = pathGeometry.Figures[1]; + + Assert.Equal(new Point(50, 50), secondFigure.StartPoint); + } } }
Text alignment mismatch when using icon fonts ## Describe the bug Text alignment mismatch when using icon fonts such as SegoeFluentIcons. ## To Reproduce Check out `icon-font-err` branch for both repo: [Avalonia Test](https://github.com/laolarou726/TypesettingErrorDemo) [WPF Test](https://github.com/laolarou726/TypesettingErrorDemoWPF) ## Screenshots In Avalonia: <img width="225" alt="image" src="https://github.com/AvaloniaUI/Avalonia/assets/25716486/cbcc067e-c8d8-4d5c-aa9d-6caff4924f8c"> In WPF: <img width="186" alt="image" src="https://github.com/AvaloniaUI/Avalonia/assets/25716486/2c85bcb6-a93f-4cf1-a7f9-fa337d3d7325"> ## Environment - OS: Windows 11 22H2 - Avalonia-Version: 11.1.999-cibuild0040792-beta
Two notes here: 1. This may be a Skia issue 2. I recall UWP/WinUI has a similar problem that remains unfixed: https://github.com/microsoft/microsoft-ui-xaml/issues/3077. This was not for fonts though, just paths. I saw this issue as well with a piece of art I made myself. It almost seemed like it was using relative pathing even when the absolute path symbols were used (capital letters instead of lower case). In my case I was able to move an arc that was being drawn incorrectly to the front of the path and it corrected itself. It really was quite bizarre. @Alshain01 Do you happen to have the path data you can share? That is probably easier to debug than a font. > @Alshain01 Do you happen to have the path data you can share? That is probably easier to debug than a font. I would love to help but while I made it, I did so on the job, so it's proprietary and doesn't belong to me. I have a similar situation, but I don’t know if it is the same problem as you. My icon will have one or two extra paddngs on the left. I always thought it was a problem with the default Text HorizontalAlignment, but I found that the normal text is Normal, only IconFont has this problem (normal on WPF) Avalonia: ![image](https://github.com/AvaloniaUI/Avalonia/assets/45205313/5b204152-a742-4d01-aaaa-29966d0ebfb0) WPF: ![(Q5)7@FL0LDI CE8JM 9GCG](https://github.com/AvaloniaUI/Avalonia/assets/45205313/7ae0a7c7-4fa4-45e0-af88-25da814e8e49) @SmRiley do you have a sample xaml and font file for us ? > @SmRiley do you have a sample xaml and font file for us ? [AvaloniaIconFontErrorDemo.zip](https://github.com/AvaloniaUI/Avalonia/files/13191450/AvaloniaIconFontErrorDemo.zip) Sure, and this is the demo running result ![image](https://github.com/AvaloniaUI/Avalonia/assets/45205313/53855632-ea0b-4042-a871-804b68b83407) @timunie thx ❤️ Any update on this?
2023-12-21T18:06:39Z
0.2
['Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Should_Handle_StartPoint_After_Empty_Figure']
['Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parsed_Geometry_ToString_Should_Produce_Valid_Value', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Implicit_Line_Command_After_Move', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Should_AlwaysEndFigure', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.CloseFigure_Should_Move_CurrentPoint_To_CreateFigurePoint', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parsed_Geometry_ToString_Should_Format_Value', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Close', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Implicit_Line_Command_After_Relative_Move', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Throws_InvalidDataException_On_None_Defined_Command', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Scientific_Notation_Double', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Move', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_Line', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Parses_FillMode_Before_Move', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Should_Parse_Flags_Without_Separator', 'Avalonia.Base.UnitTests.Media.PathMarkupParserTests.Should_Parse']
AvaloniaUI/Avalonia
avaloniaui__avalonia-13969
79b79bbc707f4172ffe7d92d84211cf4a6195d58
diff --git a/src/Avalonia.Base/Styling/ControlTheme.cs b/src/Avalonia.Base/Styling/ControlTheme.cs index 75a3beb9078..6cd09e18081 100644 --- a/src/Avalonia.Base/Styling/ControlTheme.cs +++ b/src/Avalonia.Base/Styling/ControlTheme.cs @@ -48,7 +48,7 @@ internal SelectorMatchResult TryAttach(StyledElement target, FrameType type) if (HasSettersOrAnimations && TargetType.IsAssignableFrom(StyledElement.GetStyleKey(target))) { - Attach(target, null, type); + Attach(target, null, type, true); return SelectorMatchResult.AlwaysThisType; } diff --git a/src/Avalonia.Base/Styling/Style.cs b/src/Avalonia.Base/Styling/Style.cs index a5d89392e97..44ffc22e915 100644 --- a/src/Avalonia.Base/Styling/Style.cs +++ b/src/Avalonia.Base/Styling/Style.cs @@ -74,7 +74,7 @@ internal SelectorMatchResult TryAttach(StyledElement target, object? host, Frame if (match.IsMatch) { - Attach(target, match.Activator, type); + Attach(target, match.Activator, type, Selector is not OrSelector); } result = match.Result; diff --git a/src/Avalonia.Base/Styling/StyleBase.cs b/src/Avalonia.Base/Styling/StyleBase.cs index 318e8d68901..bc3457cb481 100644 --- a/src/Avalonia.Base/Styling/StyleBase.cs +++ b/src/Avalonia.Base/Styling/StyleBase.cs @@ -92,20 +92,24 @@ public bool TryGetResource(object key, ThemeVariant? themeVariant, out object? r return false; } - internal ValueFrame Attach(StyledElement target, IStyleActivator? activator, FrameType type) + internal ValueFrame Attach( + StyledElement target, + IStyleActivator? activator, + FrameType type, + bool canShareInstance) { if (target is not AvaloniaObject ao) throw new InvalidOperationException("Styles can only be applied to AvaloniaObjects."); StyleInstance instance; - if (_sharedInstance is not null) + if (_sharedInstance is not null && canShareInstance) { instance = _sharedInstance; } else { - var canShareInstance = activator is null; + canShareInstance &= activator is null; instance = new StyleInstance(this, activator, type);
diff --git a/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs b/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs index 52bee42d9d9..b44078caeb5 100644 --- a/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs +++ b/tests/Avalonia.Base.UnitTests/Styling/StyleTests.cs @@ -1029,6 +1029,28 @@ public void Animations_With_Activator_Trigger_Should_Be_Activated_And_Deactivate Assert.Equal(Brushes.Blue, border.Background); } + [Fact] + public void Should_Not_Share_Instance_When_Or_Selector_Is_Present() + { + // Issue #13910 + Style style = new Style(x => Selectors.Or(x.OfType<Class1>(), x.OfType<Class2>().Class("bar"))) + { + Setters = + { + new Setter(Class1.FooProperty, "Foo"), + }, + }; + + var target1 = new Class1 { Classes = { "foo" } }; + var target2 = new Class2(); + + StyleHelpers.TryAttach(style, target1); + StyleHelpers.TryAttach(style, target2); + + Assert.Equal("Foo", target1.Foo); + Assert.Equal("foodefault", target2.Foo); + } + private class Class1 : Control { public static readonly StyledProperty<string> FooProperty = @@ -1063,5 +1085,22 @@ protected override Size MeasureOverride(Size availableSize) throw new NotImplementedException(); } } + + private class Class2 : Control + { + public static readonly StyledProperty<string> FooProperty = + Class1.FooProperty.AddOwner<Class2>(); + + public string Foo + { + get { return GetValue(FooProperty); } + set { SetValue(FooProperty, value); } + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + } + } } }
Styles are mistakenly activated when multiple selectors (with and without activators) are combined on the same Style instance ### Discussed in https://github.com/AvaloniaUI/Avalonia/discussions/13908 Having complex and mixed selector like `Button.SingleLineButton, ToggleButton.SingleLineButton, ComboBox.SingleLineCombobox, MenuItem` at some point of styles evaluation Style will be attached to the MenuItem without any activator (as it always matches). Unfortunately, it will break `Style._sharedInstance`, as current Style system will share instance for all parts of the selector, not only MenuItem. CC @grokys I might take a look this week if I can fix it. But if you have a clear idea how to fix it now - please do. <div type='discussions-op-text'> <sup>Originally posted by **giacarrea** December 11, 2023</sup> Hello, I'm busy trying to port an existing app from avalonia 10 to 11 and I'm having the following issue: I have a class specific styling for button mixed in with other controls, but when switching to avalonia 11, some buttons that weren't assigned to that class in my axaml file were somehow assigned to it regardless - as I could notice in the ui dev tool. Weirder still, when I split my styling over two différent styles, it then worked as intended... (see screenshot) ![image](https://github.com/AvaloniaUI/Avalonia/assets/60611503/6eeafddb-2a30-44f6-adba-3b2ef000e3a7) Also, the same window presenting the issue will be displayed correctly the first time its rendered. If I close it, open another one, then reopen the first one, then I get my styling issue... Similarly, I have a button with a flyout menu; if I remove the menuItem, I don't have the styling issue anymore (which happens on another window...) ![image](https://github.com/AvaloniaUI/Avalonia/assets/60611503/93c6e4e3-08fc-44b1-979a-c5eb6005ba70) Has anyone ever had a similar issue or know where it could come from?</div>
Workaround: create separated styles with and without activators (with and without classes/pseudoclasses/properties selectors).
2023-12-15T17:08:54Z
0.2
['Avalonia.Base.UnitTests.Styling.StyleTests.Should_Not_Share_Instance_When_Or_Selector_Is_Present']
['Avalonia.Base.UnitTests.Styling.StyleTests.Animations_Should_Be_Activated', 'Avalonia.Base.UnitTests.Styling.StyleTests.Inactive_Bindings_Should_Not_Be_Made_Active_During_Style_Attach', 'Avalonia.Base.UnitTests.Styling.StyleTests.Style_With_Only_Type_Selector_Should_Update_Value', 'Avalonia.Base.UnitTests.Styling.StyleTests.Animations_With_Activator_Trigger_Should_Be_Activated_And_Deactivated', 'Avalonia.Base.UnitTests.Styling.StyleTests.Adding_Style_With_No_Setters_Or_Animations_Should_Not_Invalidate_Styles', 'Avalonia.Base.UnitTests.Styling.StyleTests.Style_With_No_Selector_Should_Not_Apply_To_Other_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Removing_Nested_Style_Should_Detach_From_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Should_Set_Owner_On_Assigned_Resources_2', 'Avalonia.Base.UnitTests.Styling.StyleTests.Later_Styles_Should_Override_Earlier_With_Begin_End_Styling', 'Avalonia.Base.UnitTests.Styling.StyleTests.Later_Styles_Should_Override_Earlier_4', 'Avalonia.Base.UnitTests.Styling.StyleTests.Nested_Or_Style_Can_Be_Added', 'Avalonia.Base.UnitTests.Styling.StyleTests.Adding_Style_Should_Attach_To_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Later_Styles_Should_Override_Earlier', 'Avalonia.Base.UnitTests.Styling.StyleTests.Should_Throw_For_Selector_With_Trailing_Template_Selector', 'Avalonia.Base.UnitTests.Styling.StyleTests.Inactive_Values_Should_Not_Be_Made_Active_During_Style_Detach_2', 'Avalonia.Base.UnitTests.Styling.StyleTests.Adding_Nested_Style_Should_Attach_To_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Nested_Style_Without_Selector_Throws', 'Avalonia.Base.UnitTests.Styling.StyleTests.Later_Styles_Should_Override_Earlier_2', 'Avalonia.Base.UnitTests.Styling.StyleTests.Removing_Style_With_Nested_Style_Should_Detach_From_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Removing_Style_Should_Detach_From_Control', 'Avalonia.Base.UnitTests.Styling.StyleTests.Style_Should_Detach_When_Control_Removed_From_Logical_Tree', 'Avalonia.Base.UnitTests.Styling.StyleTests.Invalidating_Styles_Should_Detach_Activator', 'Avalonia.Base.UnitTests.Styling.StyleTests.Animations_With_Trigger_Should_Be_Activated_And_Deactivated', 'Avalonia.Base.UnitTests.Styling.StyleTests.Style_With_Class_Selector_Should_Update_And_Restore_Value', 'Avalonia.Base.UnitTests.Styling.StyleTests.Inactive_Values_Should_Not_Be_Made_Active_During_Style_Detach', 'Avalonia.Base.UnitTests.Styling.StyleTests.Inactive_Values_Should_Not_Be_Made_Active_During_Style_Attach', 'Avalonia.Base.UnitTests.Styling.StyleTests.Nested_Style_Can_Be_Added', 'Avalonia.Base.UnitTests.Styling.StyleTests.Template_In_Inactive_Style_Is_Not_Built', 'Avalonia.Base.UnitTests.Styling.StyleTests.Later_Styles_Should_Override_Earlier_3', 'Avalonia.Base.UnitTests.Styling.StyleTests.LocalValue_Should_Override_Style', 'Avalonia.Base.UnitTests.Styling.StyleTests.Inactive_Bindings_Should_Not_Be_Made_Active_During_Style_Detach', 'Avalonia.Base.UnitTests.Styling.StyleTests.Should_Set_Owner_On_Assigned_Resources', 'Avalonia.Base.UnitTests.Styling.StyleTests.Template_In_Non_Matching_Style_Is_Not_Built', 'Avalonia.Base.UnitTests.Styling.StyleTests.Style_With_No_Selector_Should_Apply_To_Containing_Control']
AvaloniaUI/Avalonia
avaloniaui__avalonia-13188
b83a5eb8b737f5c9239fadce7860264ea736a4b0
diff --git a/src/Avalonia.Base/Layout/LayoutManager.cs b/src/Avalonia.Base/Layout/LayoutManager.cs index dee16191d69..cffda3e84c7 100644 --- a/src/Avalonia.Base/Layout/LayoutManager.cs +++ b/src/Avalonia.Base/Layout/LayoutManager.cs @@ -423,12 +423,16 @@ private void CalculateEffectiveViewport(Visual target, Visual control, ref Rect // Translate the viewport into this control's coordinate space. viewport = viewport.Translate(-control.Bounds.Position); - if (control != target && control.RenderTransform is object) + if (control != target && control.RenderTransform is { } transform) { - var origin = control.RenderTransformOrigin.ToPixels(control.Bounds.Size); - var offset = Matrix.CreateTranslation(origin); - var renderTransform = (-offset) * control.RenderTransform.Value.Invert() * (offset); - viewport = viewport.TransformToAABB(renderTransform); + if (transform.Value.TryInvert(out var invertedMatrix)) + { + var origin = control.RenderTransformOrigin.ToPixels(control.Bounds.Size); + var offset = Matrix.CreateTranslation(origin); + viewport = viewport.TransformToAABB(-offset * invertedMatrix * offset); + } + else + viewport = default; } }
diff --git a/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs b/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs index 5a493cb741a..63eb6589ca1 100644 --- a/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs +++ b/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs @@ -341,6 +341,32 @@ void OnTargetOnEffectiveViewportChanged(object s, EffectiveViewportChangedEventA }); } + // https://github.com/AvaloniaUI/Avalonia/issues/12452 + [Fact] + public async Task Zero_ScaleTransform_Sets_Empty_EffectiveViewport() + { + await RunOnUIThread.Execute(async () => + { + var effectiveViewport = new Rect(Size.Infinity); + + var root = CreateRoot(); + var target = new Canvas { Width = 100, Height = 100 }; + var parent = new Border { Width = 100, Height = 100, Child = target }; + + target.EffectiveViewportChanged += (_, e) => effectiveViewport = e.EffectiveViewport; + + root.Child = parent; + + await ExecuteInitialLayoutPass(root); + + parent.RenderTransform = new ScaleTransform(0, 0); + + await ExecuteLayoutPass(root); + + Assert.Equal(new Rect(0, 0, 0, 0), effectiveViewport); + }); + } + private static TestRoot CreateRoot() => new TestRoot { Width = 1200, Height = 900 }; private static Task ExecuteInitialLayoutPass(TestRoot root)
VirtualizingStackPanel with animated ScaleTransform starting from 0 crashes the renderer **Describe the bug** When we add ListBox with VirtualizingStackPanel and animation for ScaleTransform (which starting from 0) to visual tree, it will crash the renderer. But with the ListBox'es, which initially in the content (e.g. in the Window markup) - no issue. **To Reproduce** Repro solution: https://github.com/SKProCH/AvaloniaBugsRepros Steps to reproduce the behavior: 1. Add listbox animation: ```xaml <Style Selector="ListBox"> <Style.Animations> <Animation Duration="0:0:3" Easing="SineEaseInOut"> <KeyFrame Cue="0%"> <Setter Property="ScaleTransform.ScaleY" Value="0" /> <Setter Property="ScaleTransform.ScaleX" Value="0" /> </KeyFrame> <KeyFrame Cue="100%"> <Setter Property="ScaleTransform.ScaleY" Value="1" /> <Setter Property="ScaleTransform.ScaleX" Value="1" /> </KeyFrame> </Animation> </Style.Animations> </Style> ``` 2. Add an ListBox after window load: ```csharp ContentPresenter1.Content = new ListBox() { ItemsSource = new List<object>() { new ListBoxItem() { Content = 1 } } }; ``` 3. See error **Expected behavior** ListBox should be rendered properly. **Screenshots** https://github.com/AvaloniaUI/Avalonia/assets/29896317/276dab9b-a487-4ed1-adc9-a32fc2114916 In some cases it will render ListBox after resize: https://github.com/AvaloniaUI/Avalonia/assets/29896317/e30cf3f2-5b86-4cb5-a230-8339115f3e12 **Desktop (please complete the following information):** - OS: Windows (but i think any) - Version: 11.0.2 **Additional context** If ScaleTranform starting from non-zero value (such as 0.1) - everything works fine. Also, i think what ListBoxes which loaded with Window (inside Window markup) renders properly because it actually skips the frame with ScaleTransform 0. This is related to DialogHost.Avalonia issue: https://github.com/AvaloniaUtils/DialogHost.Avalonia/issues/35 Probably this is `System.InvalidOperationException` is thrown with the message "Transform is not invertible": ![image](https://github.com/AvaloniaUI/Avalonia/assets/29896317/4b6a52cb-4048-4a69-a047-c36a4a621ff5) And probably related to [Exception in OnApplyTemplate after initial app doesn't rethrown and makes all app logiс hangs](https://github.com/AvaloniaUI/Avalonia/issues/12388) Avalonia issue (since no exception re-throws when renderer crashes).
null
2023-10-09T20:46:56Z
0.3
['Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Zero_ScaleTransform_Sets_Empty_EffectiveViewport']
['Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Invalidating_In_Handler_Causes_Layout_To_Be_Rerun_Before_LayoutUpdated_Raised', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Rotate_Transform_On_Parent_Affects_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.ScrollViewer_Determines_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.EffectiveViewportChanged_Raised_Before_LayoutUpdated', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Viewport_Extends_Beyond_Centered_Control', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Translate_Transform_Doesnt_Affect_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Viewport_Extends_Beyond_Nested_Centered_Control', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Translate_Transform_On_Parent_Affects_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Parent_Affects_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Event_Unsubscribed_While_Inside_Callback', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.EffectiveViewportChanged_Not_Raised_When_Control_Added_To_Tree', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Moving_Parent_Updates_EffectiveViewport', 'Avalonia.Base.UnitTests.Layout.LayoutableTests_EffectiveViewportChanged.Scrolled_ScrollViewer_Determines_EffectiveViewport']
AvaloniaUI/Avalonia
avaloniaui__avalonia-13185
bbe4ad875515aa69b916f654d0046251fcba5a05
diff --git a/src/Avalonia.Base/Input/AccessKeyHandler.cs b/src/Avalonia.Base/Input/AccessKeyHandler.cs index 38692d8b77d..fe5e2c46a21 100644 --- a/src/Avalonia.Base/Input/AccessKeyHandler.cs +++ b/src/Avalonia.Base/Input/AccessKeyHandler.cs @@ -183,7 +183,8 @@ protected virtual void OnKeyDown(object? sender, KeyEventArgs e) var text = e.Key.ToString(); var matches = _registered .Where(x => string.Equals(x.AccessKey, text, StringComparison.OrdinalIgnoreCase) - && x.Element.IsEffectivelyVisible) + && x.Element.IsEffectivelyVisible + && x.Element.IsEffectivelyEnabled) .Select(x => x.Element); // If the menu is open, only match controls in the menu's visual tree.
diff --git a/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs b/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs index 4d8ece4ddaa..ed1061e85a9 100644 --- a/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs +++ b/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs @@ -165,6 +165,30 @@ public void Should_Raise_AccessKeyPressed_For_Registered_Access_Key() Assert.Equal(1, raised); } + [Fact] + public void Should_Not_Raise_AccessKeyPressed_For_Registered_Access_Key_When_Not_Effectively_Enabled() + { + var button = new Button(); + var root = new TestRoot(button) { IsEnabled = false }; + var target = new AccessKeyHandler(); + var raised = 0; + + target.SetOwner(root); + target.Register('A', button); + button.AddHandler(AccessKeyHandler.AccessKeyPressedEvent, (s, e) => ++raised); + + KeyDown(root, Key.LeftAlt); + Assert.Equal(0, raised); + + KeyDown(root, Key.A, KeyModifiers.Alt); + Assert.Equal(0, raised); + + KeyUp(root, Key.A, KeyModifiers.Alt); + KeyUp(root, Key.LeftAlt); + + Assert.Equal(0, raised); + } + [Fact] public void Should_Open_MainMenu_On_Alt_KeyUp() {
AccessKeyHandler should not match on disabled elements ## Describe the bug Multiple input elements can be registered with the same access key. When the `AccessKeyHandler` attempts to locate the element associated with a key, the logic does not consider the enabled state of the element and will return the first match even if it is disabled and the second match is enabled. ## To Reproduce Steps to reproduce the behavior: 1. Create two button controls with the same access key; e.g., "_Button1" and "_Button2" 2. Add an event handler for each button to know when it is invoked. 3. Press `Alt+B` to initiate the `AccessKeyHandler` and "_Button1" will be invoked. 4. Disable "_Button1" 5. Press `Alt+B` to initiate the `AccessKeyHandler` and nothing happens because the access key was sent to "_Button1", but it is disabled. ## Expected behavior In Step 5 the access key should have invoked "_Button2" since it was the better match. ## Additional context - WPF's `AccessKeyManager` ignores disabled elements when attempting to find a match, so this change will bring Avalonia closer to matching WPF's behavior.
null
2023-10-09T19:04:42Z
0.3
['Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Not_Raise_AccessKeyPressed_For_Registered_Access_Key_When_Not_Effectively_Enabled']
['Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_Key_Events_For_Alt_Key_With_MainMenu', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_Key_Events_For_Unregistered_Access_Key_With_MainMenu', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Open_MainMenu_On_Alt_KeyUp', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_Key_Events_For_Alt_Key', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_Key_Events_For_Registered_Access_Key', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_Key_Events_For_Unregistered_Access_Key', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_AccessKeyPressed_For_Registered_Access_Key']
AvaloniaUI/Avalonia
avaloniaui__avalonia-12666
f6809ad4e6b1f68d7cb1d797e5bd0d147910ce36
diff --git a/src/Avalonia.Base/Input/GestureRecognizers/GestureRecognizerCollection.cs b/src/Avalonia.Base/Input/GestureRecognizers/GestureRecognizerCollection.cs index 05dce8214b1..74e8061292e 100644 --- a/src/Avalonia.Base/Input/GestureRecognizers/GestureRecognizerCollection.cs +++ b/src/Avalonia.Base/Input/GestureRecognizers/GestureRecognizerCollection.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using Avalonia.Controls; @@ -59,6 +60,20 @@ internal bool HandlePointerPressed(PointerPressedEventArgs e) return e.Handled; } + internal void HandleCaptureLost(IPointer pointer) + { + if (_recognizers == null || pointer is not Pointer p) + return; + + foreach (var r in _recognizers) + { + if (p.CapturedGestureRecognizer == r) + continue; + + r.PointerCaptureLostInternal(pointer); + } + } + internal bool HandlePointerReleased(PointerReleasedEventArgs e) { if (_recognizers == null) diff --git a/src/Avalonia.Base/Input/GestureRecognizers/PinchGestureRecognizer.cs b/src/Avalonia.Base/Input/GestureRecognizers/PinchGestureRecognizer.cs index b02c82a0660..5a22ba7a142 100644 --- a/src/Avalonia.Base/Input/GestureRecognizers/PinchGestureRecognizer.cs +++ b/src/Avalonia.Base/Input/GestureRecognizers/PinchGestureRecognizer.cs @@ -1,4 +1,5 @@ -using Avalonia.Input.GestureRecognizers; +using System.Diagnostics; +using Avalonia.Input.GestureRecognizers; namespace Avalonia.Input { @@ -110,6 +111,7 @@ private void RemoveContact(IPointer pointer) _secondContact = null; } + Target?.RaiseEvent(new PinchEndedEventArgs()); } } diff --git a/src/Avalonia.Base/Input/InputElement.cs b/src/Avalonia.Base/Input/InputElement.cs index 46f543d25bd..91dae88dbb4 100644 --- a/src/Avalonia.Base/Input/InputElement.cs +++ b/src/Avalonia.Base/Input/InputElement.cs @@ -230,6 +230,7 @@ static InputElement() PointerMovedEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerMoved(e), handledEventsToo: true); PointerPressedEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerPressed(e), handledEventsToo: true); PointerReleasedEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerReleased(e), handledEventsToo: true); + PointerCaptureLostEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerCaptureLost(e), handledEventsToo: true); } public InputElement() @@ -615,6 +616,11 @@ private void OnGesturePointerReleased(PointerReleasedEventArgs e) } } + private void OnGesturePointerCaptureLost(PointerCaptureLostEventArgs e) + { + _gestureRecognizers?.HandleCaptureLost(e.Pointer); + } + private void OnGesturePointerPressed(PointerPressedEventArgs e) { if (!e.IsGestureRecognitionSkipped) diff --git a/src/Avalonia.Base/Input/Pointer.cs b/src/Avalonia.Base/Input/Pointer.cs index 5744ddf963a..e82432a00db 100644 --- a/src/Avalonia.Base/Input/Pointer.cs +++ b/src/Avalonia.Base/Input/Pointer.cs @@ -91,12 +91,16 @@ public void Dispose() internal void CaptureGestureRecognizer(GestureRecognizer? gestureRecognizer) { if (CapturedGestureRecognizer != gestureRecognizer) + { CapturedGestureRecognizer?.PointerCaptureLostInternal(this); + } + + CapturedGestureRecognizer = gestureRecognizer; if (gestureRecognizer != null) + { Capture(null); - - CapturedGestureRecognizer = gestureRecognizer; + } } } }
diff --git a/tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs b/tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs index 14fa242146f..a2afdd0af27 100644 --- a/tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs +++ b/tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs @@ -487,6 +487,40 @@ public void Pinched_Should_Be_Raised_For_Two_Pointers_Moving() Assert.True(raised); } + [Fact] + public void Gestures_Should_Be_Cancelled_When_Pointer_Capture_Is_Lost() + { + Border border = new Border() + { + Width = 100, + Height = 100, + Background = new SolidColorBrush(Colors.Red) + }; + border.GestureRecognizers.Add(new PinchGestureRecognizer()); + var root = new TestRoot + { + Child = border + }; + var raised = false; + + root.AddHandler(Gestures.PinchEvent, (_, _) => raised = true); + + var firstPoint = new Point(5, 5); + var secondPoint = new Point(10, 10); + + var firstTouch = new TouchTestHelper(); + var secondTouch = new TouchTestHelper(); + + firstTouch.Down(border, position: firstPoint); + + firstTouch.Cancel(); + + secondTouch.Down(border, position: secondPoint); + secondTouch.Move(border, position: new Point(20, 20)); + + Assert.False(raised); + } + [Fact] public void Scrolling_Should_Start_After_Start_Distance_Is_Exceeded() { diff --git a/tests/Avalonia.UnitTests/TouchTestHelper.cs b/tests/Avalonia.UnitTests/TouchTestHelper.cs index 574599d1ad6..120b0c06705 100644 --- a/tests/Avalonia.UnitTests/TouchTestHelper.cs +++ b/tests/Avalonia.UnitTests/TouchTestHelper.cs @@ -61,5 +61,11 @@ public void Tap(Interactive target, Interactive source, Point position = default Down(target, source, position, modifiers); Up(target, source, position, modifiers); } + + public void Cancel() + { + _pointer.Capture(null); + _pointer.CaptureGestureRecognizer(null); + } } }
[11.0.0] Android touch control breaks after swiping back **Describe the bug** When using the "swipe back" function on modern android devices (see here: [Image](https://image.winudf.com/v2/image1/dGhyZWVkcm9pZC5nZXN0dXJlLmNvbnRyb2xfc2NyZWVuXzBfMTU1NTk1NTYwNV8wODk/screen-0.webp?fakeurl=1&type=.webp)) the device detects a touch input at that point even after the finger was released. This results in every further drag being detected as pinch. I haven't found a way to release the imaginary finger again. **To Reproduce** Steps to reproduce the behavior: 1. Create an android app that is detecting PointerMoved and Pinch Events (drag an image on screen for example) 2. Swipe back on the edge of the screen (which will in most cases let you return to the home screen) 3. Reopen the app 4. Experience strange behaviour when touching the screen. **Expected behavior** The touch input should work the same after performing the swipe back gesture. **Desktop (please complete the following information):** - OS: [Android] - Version [11.0.0]
null
2023-08-25T14:07:31Z
0.3
['Avalonia.Base.UnitTests.Input.GesturesTests.Gestures_Should_Be_Cancelled_When_Pointer_Capture_Is_Lost']
['Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Be_Raised_After_Hold_Duration', 'Avalonia.Base.UnitTests.Input.GesturesTests.Tapped_Should_Follow_Pointer_Pressed_Released', 'Avalonia.Base.UnitTests.Input.GesturesTests.RightTapped_Should_Be_Raised_For_Right_Button', 'Avalonia.Base.UnitTests.Input.GesturesTests.DoubleTapped_Should_Follow_Pointer_Pressed_Released_Pressed', 'Avalonia.Base.UnitTests.Input.GesturesTests.Tapped_Should_Not_Be_Raised_For_Middle_Button', 'Avalonia.Base.UnitTests.Input.GesturesTests.DoubleTapped_Should_Be_Raised_Even_When_Pressed_Released_Handled', 'Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Not_Be_Raised_For_Multiple_Contacts', 'Avalonia.Base.UnitTests.Input.GesturesTests.Tapped_Should_Be_Raised_Even_When_Pressed_Released_Handled', 'Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Be_Cancelled_When_Second_Contact_Is_Detected', 'Avalonia.Base.UnitTests.Input.GesturesTests.Pinched_Should_Be_Raised_For_Two_Pointers_Moving', 'Avalonia.Base.UnitTests.Input.GesturesTests.DoubleTapped_Should_Not_Be_Raised_For_Middle_Button', 'Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Not_Raised_When_Pointer_Is_Moved_Before_Timer', 'Avalonia.Base.UnitTests.Input.GesturesTests.Tapped_Should_Not_Be_Raised_For_Right_Button', 'Avalonia.Base.UnitTests.Input.GesturesTests.Pinched_Should_Not_Be_Raised_For_Same_Pointer', 'Avalonia.Base.UnitTests.Input.GesturesTests.Scrolling_Should_Start_After_Start_Distance_Is_Exceeded', 'Avalonia.Base.UnitTests.Input.GesturesTests.DoubleTapped_Should_Not_Be_Raised_For_Right_Button', 'Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Be_Cancelled_When_Pointer_Moves_Too_Far', 'Avalonia.Base.UnitTests.Input.GesturesTests.Hold_Should_Not_Raised_When_Pointer_Released_Before_Timer']
restsharp/RestSharp
restsharp__restsharp-2241
dd52ff6cd18cce2a74475f97374d431280ac10cf
diff --git a/Directory.Packages.props b/Directory.Packages.props index 64df33b50..61c85f4c3 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -16,8 +16,8 @@ <PackageVersion Include="Newtonsoft.Json" Version="13.0.3" /> <PackageVersion Include="CsvHelper" Version="33.0.1" /> <PackageVersion Include="PolySharp" Version="1.14.1" /> - <PackageVersion Include="System.Text.Json" Version="8.0.3" /> - <PackageVersion Include="WireMock.Net" Version="1.5.51" /> + <PackageVersion Include="System.Text.Json" Version="8.0.4" /> + <PackageVersion Include="WireMock.Net" Version="1.5.60" /> <PackageVersion Include="WireMock.Net.FluentAssertions" Version="1.5.51" /> </ItemGroup> <ItemGroup Label="Compile dependencies"> @@ -28,7 +28,7 @@ <PackageVersion Include="Nullable" Version="1.3.1" /> <PackageVersion Include="Microsoft.NETFramework.ReferenceAssemblies.net472" Version="1.0.3" /> <PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" /> - <PackageVersion Include="JetBrains.Annotations" Version="2023.3.0" /> + <PackageVersion Include="JetBrains.Annotations" Version="2024.2.0" /> </ItemGroup> <ItemGroup Label="Testing dependencies"> <PackageVersion Include="AutoFixture" Version="4.18.1" /> @@ -36,14 +36,14 @@ <PackageVersion Include="FluentAssertions" Version="6.12.0" /> <PackageVersion Include="HttpTracer" Version="2.1.1" /> <PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="$(MicrosoftTestHostVer)" /> - <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" /> + <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.10.0" /> <PackageVersion Include="Moq" Version="4.20.70" /> - <PackageVersion Include="Polly" Version="8.3.1" /> + <PackageVersion Include="Polly" Version="8.4.1" /> <PackageVersion Include="rest-mock-core" Version="0.7.12" /> <PackageVersion Include="RichardSzalay.MockHttp" Version="7.0.0" /> <PackageVersion Include="System.Net.Http.Json" Version="8.0.0" /> <PackageVersion Include="Xunit.Extensions.Logging" Version="1.1.0" /> - <PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" PrivateAssets="All" /> - <PackageVersion Include="xunit" Version="2.8.1" /> + <PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" PrivateAssets="All" /> + <PackageVersion Include="xunit" Version="2.9.0" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/gen/SourceGenerator/ImmutableGenerator.cs b/gen/SourceGenerator/ImmutableGenerator.cs index 54ea9101b..7576359bd 100644 --- a/gen/SourceGenerator/ImmutableGenerator.cs +++ b/gen/SourceGenerator/ImmutableGenerator.cs @@ -32,22 +32,24 @@ public void Execute(GeneratorExecutionContext context) { static string GenerateImmutableClass(TypeDeclarationSyntax mutableClass, Compilation compilation) { var containingNamespace = compilation.GetSemanticModel(mutableClass.SyntaxTree).GetDeclaredSymbol(mutableClass)!.ContainingNamespace; - - var namespaceName = containingNamespace.ToDisplayString(); - - var className = mutableClass.Identifier.Text; - - var usings = mutableClass.SyntaxTree.GetCompilationUnitRoot().Usings.Select(u => u.ToString()); + var namespaceName = containingNamespace.ToDisplayString(); + var className = mutableClass.Identifier.Text; + var usings = mutableClass.SyntaxTree.GetCompilationUnitRoot().Usings.Select(u => u.ToString()); var properties = GetDefinitions(SyntaxKind.SetKeyword) - .Select(prop => $" public {prop.Type} {prop.Identifier.Text} {{ get; }}") + .Select( + prop => { + var xml = prop.GetLeadingTrivia().FirstOrDefault(x => x.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)).GetStructure(); + return $"/// {xml} public {prop.Type} {prop.Identifier.Text} {{ get; }}"; + } + ) .ToArray(); var props = GetDefinitions(SyntaxKind.SetKeyword).ToArray(); const string argName = "inner"; - var mutableProperties = props - .Select(prop => $" {prop.Identifier.Text} = {argName}.{prop.Identifier.Text};"); + + var mutableProperties = props.Select(prop => $" {prop.Identifier.Text} = {argName}.{prop.Identifier.Text};"); var constructor = $$""" public ReadOnly{{className}}({{className}} {{argName}}) { @@ -85,7 +87,8 @@ IEnumerable<PropertyDeclarationSyntax> GetDefinitions(SyntaxKind kind) .OfType<PropertyDeclarationSyntax>() .Where( prop => - prop.AccessorList!.Accessors.Any(accessor => accessor.Keyword.IsKind(kind)) && prop.AttributeLists.All(list => list.Attributes.All(attr => attr.Name.ToString() != "Exclude")) + prop.AccessorList!.Accessors.Any(accessor => accessor.Keyword.IsKind(kind)) && + prop.AttributeLists.All(list => list.Attributes.All(attr => attr.Name.ToString() != "Exclude")) ); } -} +} \ No newline at end of file diff --git a/src/RestSharp/Authenticators/JwtAuthenticator.cs b/src/RestSharp/Authenticators/JwtAuthenticator.cs index 1b90bdd60..cadbd2a64 100644 --- a/src/RestSharp/Authenticators/JwtAuthenticator.cs +++ b/src/RestSharp/Authenticators/JwtAuthenticator.cs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace RestSharp.Authenticators; +namespace RestSharp.Authenticators; /// <summary> /// JSON WEB TOKEN (JWT) Authenticator class. @@ -26,7 +26,8 @@ public class JwtAuthenticator(string accessToken) : AuthenticatorBase(GetToken(a [PublicAPI] public void SetBearerToken(string accessToken) => Token = GetToken(accessToken); - static string GetToken(string accessToken) => Ensure.NotEmpty(accessToken, nameof(accessToken)).StartsWith("Bearer ") ? accessToken : $"Bearer {accessToken}"; + static string GetToken(string accessToken) + => Ensure.NotEmptyString(accessToken, nameof(accessToken)).StartsWith("Bearer ") ? accessToken : $"Bearer {accessToken}"; protected override ValueTask<Parameter> GetAuthenticationParameter(string accessToken) => new(new HeaderParameter(KnownHeaders.Authorization, accessToken)); diff --git a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs index 9b7a41837..894bb24f9 100644 --- a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs +++ b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs @@ -48,7 +48,7 @@ sealed class OAuthWorkflow { /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> /// <returns></returns> public OAuthParameters BuildRequestTokenSignature(string method, WebPairCollection parameters) { - Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey)); + Ensure.NotEmptyString(ConsumerKey, nameof(ConsumerKey)); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); @@ -76,8 +76,8 @@ public OAuthParameters BuildRequestTokenSignature(string method, WebPairCollecti /// <param name="method">The HTTP method for the intended request</param> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> public OAuthParameters BuildAccessTokenSignature(string method, WebPairCollection parameters) { - Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey)); - Ensure.NotEmpty(Token, nameof(Token)); + Ensure.NotEmptyString(ConsumerKey, nameof(ConsumerKey)); + Ensure.NotEmptyString(Token, nameof(Token)); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); @@ -105,8 +105,8 @@ public OAuthParameters BuildAccessTokenSignature(string method, WebPairCollectio /// <param name="method">The HTTP method for the intended request</param> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPairCollection parameters) { - Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey)); - Ensure.NotEmpty(ClientUsername, nameof(ClientUsername)); + Ensure.NotEmptyString(ConsumerKey, nameof(ConsumerKey)); + Ensure.NotEmptyString(ClientUsername, nameof(ClientUsername)); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); @@ -127,7 +127,7 @@ public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPai } public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCollection parameters) { - Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey)); + Ensure.NotEmptyString(ConsumerKey, nameof(ConsumerKey)); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); diff --git a/src/RestSharp/Ensure.cs b/src/RestSharp/Ensure.cs index 5d985c860..dbdb56f9d 100644 --- a/src/RestSharp/Ensure.cs +++ b/src/RestSharp/Ensure.cs @@ -17,11 +17,10 @@ namespace RestSharp; static class Ensure { public static T NotNull<T>(T? value, [InvokerParameterName] string name) => value ?? throw new ArgumentNullException(name); - public static string NotEmpty(string? value, [InvokerParameterName] string name) - => string.IsNullOrWhiteSpace(value) ? throw new ArgumentNullException(name) : value!; - public static string NotEmptyString(object? value, [InvokerParameterName] string name) { var s = value as string ?? value?.ToString(); - return string.IsNullOrWhiteSpace(s) ? throw new ArgumentNullException(name) : s!; + if (s == null) throw new ArgumentNullException(name); + + return string.IsNullOrWhiteSpace(s) ? throw new ArgumentException("Parameter cannot be an empty string", name) : s; } } \ No newline at end of file diff --git a/src/RestSharp/Options/RestClientOptions.cs b/src/RestSharp/Options/RestClientOptions.cs index b251a3115..96ebf9df1 100644 --- a/src/RestSharp/Options/RestClientOptions.cs +++ b/src/RestSharp/Options/RestClientOptions.cs @@ -210,6 +210,7 @@ public RestClientOptions(string baseUrl) : this(new Uri(Ensure.NotEmptyString(ba /// <summary> /// Set to true to allow multiple default parameters with the same name. Default is false. + /// This setting doesn't apply to headers as multiple header values for the same key is allowed. /// </summary> public bool AllowMultipleDefaultParametersWithSameName { get; set; } diff --git a/src/RestSharp/Parameters/DefaultParameters.cs b/src/RestSharp/Parameters/DefaultParameters.cs index 8ba19ccdc..a65b41846 100644 --- a/src/RestSharp/Parameters/DefaultParameters.cs +++ b/src/RestSharp/Parameters/DefaultParameters.cs @@ -28,12 +28,11 @@ public sealed class DefaultParameters(ReadOnlyRestClientOptions options) : Param [MethodImpl(MethodImplOptions.Synchronized)] public DefaultParameters AddParameter(Parameter parameter) { if (parameter.Type == ParameterType.RequestBody) - throw new NotSupportedException( - "Cannot set request body using default parameters. Use Request.AddBody() instead." - ); + throw new NotSupportedException("Cannot set request body using default parameters. Use Request.AddBody() instead."); if (!options.AllowMultipleDefaultParametersWithSameName && - !MultiParameterTypes.Contains(parameter.Type) && + parameter.Type != ParameterType.HttpHeader && + !MultiParameterTypes.Contains(parameter.Type) && this.Any(x => x.Name == parameter.Name)) { throw new ArgumentException("A default parameters with the same name has already been added", nameof(parameter)); } @@ -70,4 +69,4 @@ public DefaultParameters ReplaceParameter(Parameter parameter) .AddParameter(parameter); static readonly ParameterType[] MultiParameterTypes = [ParameterType.QueryString, ParameterType.GetOrPost]; -} +} \ No newline at end of file diff --git a/src/RestSharp/Parameters/HeaderParameter.cs b/src/RestSharp/Parameters/HeaderParameter.cs index 55830a63f..1607eaeda 100644 --- a/src/RestSharp/Parameters/HeaderParameter.cs +++ b/src/RestSharp/Parameters/HeaderParameter.cs @@ -21,5 +21,14 @@ public record HeaderParameter : Parameter { /// </summary> /// <param name="name">Parameter name</param> /// <param name="value">Parameter value</param> - public HeaderParameter(string? name, string? value) : base(name, value, ParameterType.HttpHeader, false) { } + public HeaderParameter(string name, string value) + : base( + Ensure.NotEmptyString(name, nameof(name)), + Ensure.NotNull(value, nameof(value)), + ParameterType.HttpHeader, + false + ) { } + + public new string Name => base.Name!; + public new string Value => (string)base.Value!; } \ No newline at end of file diff --git a/src/RestSharp/Parameters/Parameter.cs b/src/RestSharp/Parameters/Parameter.cs index 93de83479..903b33402 100644 --- a/src/RestSharp/Parameters/Parameter.cs +++ b/src/RestSharp/Parameters/Parameter.cs @@ -12,32 +12,66 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; + namespace RestSharp; /// <summary> /// Parameter container for REST requests /// </summary> -public abstract record Parameter(string? Name, object? Value, ParameterType Type, bool Encode) { +[DebuggerDisplay($"{{{nameof(DebuggerDisplay)}()}}")] +public abstract record Parameter { + /// <summary> + /// Parameter container for REST requests + /// </summary> + protected Parameter(string? name, object? value, ParameterType type, bool encode) { + Name = name; + Value = value; + Type = type; + Encode = encode; + } + /// <summary> /// MIME content type of the parameter /// </summary> public ContentType ContentType { get; protected init; } = ContentType.Undefined; + public string? Name { get; } + public object? Value { get; } + public ParameterType Type { get; } + public bool Encode { get; } /// <summary> /// Return a human-readable representation of this parameter /// </summary> /// <returns>String</returns> - public sealed override string ToString() => Value == null ? $"{Name}" : $"{Name}={Value}"; + public sealed override string ToString() => Value == null ? $"{Name}" : $"{Name}={ValueString}"; + + protected virtual string ValueString => Value?.ToString() ?? "null"; public static Parameter CreateParameter(string? name, object? value, ParameterType type, bool encode = true) // ReSharper disable once SwitchExpressionHandlesSomeKnownEnumValuesWithExceptionInDefault => type switch { ParameterType.GetOrPost => new GetOrPostParameter(Ensure.NotEmptyString(name, nameof(name)), value?.ToString(), encode), ParameterType.UrlSegment => new UrlSegmentParameter(Ensure.NotEmptyString(name, nameof(name)), value?.ToString()!, encode), - ParameterType.HttpHeader => new HeaderParameter(name, value?.ToString()), + ParameterType.HttpHeader => new HeaderParameter(name!, value?.ToString()!), ParameterType.QueryString => new QueryParameter(Ensure.NotEmptyString(name, nameof(name)), value?.ToString(), encode), _ => throw new ArgumentOutOfRangeException(nameof(type), type, null) }; + + [PublicAPI] + public void Deconstruct(out string? name, out object? value, out ParameterType type, out bool encode) { + name = Name; + value = Value; + type = Type; + encode = Encode; + } + + /// <summary> + /// Assists with debugging by displaying in the debugger output + /// </summary> + /// <returns></returns> + [UsedImplicitly] + protected string DebuggerDisplay() => $"{GetType().Name.Replace("Parameter", "")} {ToString()}"; } public record NamedParameter : Parameter { diff --git a/src/RestSharp/Parameters/ParametersCollection.cs b/src/RestSharp/Parameters/ParametersCollection.cs index 2d675820e..299f2d498 100644 --- a/src/RestSharp/Parameters/ParametersCollection.cs +++ b/src/RestSharp/Parameters/ParametersCollection.cs @@ -17,25 +17,27 @@ namespace RestSharp; -public abstract class ParametersCollection : IReadOnlyCollection<Parameter> { - protected readonly List<Parameter> Parameters = []; +public abstract class ParametersCollection<T> : IReadOnlyCollection<T> where T : Parameter { + protected readonly List<T> Parameters = []; // public ParametersCollection(IEnumerable<Parameter> parameters) => _parameters.AddRange(parameters); - static readonly Func<Parameter, string?, bool> SearchPredicate = (p, name) + static readonly Func<T, string?, bool> SearchPredicate = (p, name) => p.Name != null && p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase); - public bool Exists(Parameter parameter) => Parameters.Any(p => SearchPredicate(p, parameter.Name) && p.Type == parameter.Type); + public bool Exists(T parameter) => Parameters.Any(p => SearchPredicate(p, parameter.Name) && p.Type == parameter.Type); - public Parameter? TryFind(string parameterName) => Parameters.FirstOrDefault(x => SearchPredicate(x, parameterName)); + public T? TryFind(string parameterName) => Parameters.FirstOrDefault(x => SearchPredicate(x, parameterName)); - public IEnumerable<Parameter> GetParameters(ParameterType parameterType) => Parameters.Where(x => x.Type == parameterType); - - public IEnumerable<T> GetParameters<T>() where T : class => Parameters.OfType<T>(); + public IEnumerable<TParameter> GetParameters<TParameter>() where TParameter : class, T => Parameters.OfType<TParameter>(); - public IEnumerator<Parameter> GetEnumerator() => Parameters.GetEnumerator(); + public IEnumerator<T> GetEnumerator() => Parameters.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public int Count => Parameters.Count; +} + +public abstract class ParametersCollection : ParametersCollection<Parameter> { + public IEnumerable<Parameter> GetParameters(ParameterType parameterType) => Parameters.Where(x => x.Type == parameterType); } \ No newline at end of file diff --git a/src/RestSharp/Parameters/RequestParameters.cs b/src/RestSharp/Parameters/RequestParameters.cs index 96d5c8a98..2d673f9bd 100644 --- a/src/RestSharp/Parameters/RequestParameters.cs +++ b/src/RestSharp/Parameters/RequestParameters.cs @@ -42,7 +42,7 @@ public ParametersCollection AddParameters(IEnumerable<Parameter> parameters) { } /// <summary> - /// Add parameters from another parameters collection + /// Add parameters from another parameter collection /// </summary> /// <param name="parameters"></param> /// <returns></returns> diff --git a/src/RestSharp/Parameters/UrlSegmentParameter.cs b/src/RestSharp/Parameters/UrlSegmentParameter.cs index 82d6dc2fd..b9da7752a 100644 --- a/src/RestSharp/Parameters/UrlSegmentParameter.cs +++ b/src/RestSharp/Parameters/UrlSegmentParameter.cs @@ -29,7 +29,7 @@ public partial record UrlSegmentParameter : NamedParameter { public UrlSegmentParameter(string name, string value, bool encode = true) : base( name, - RegexPattern.Replace(Ensure.NotEmpty(value, nameof(value)), "/"), + RegexPattern.Replace(Ensure.NotEmptyString(value, nameof(value)), "/"), ParameterType.UrlSegment, encode ) { } diff --git a/src/RestSharp/Request/HttpRequestMessageExtensions.cs b/src/RestSharp/Request/HttpRequestMessageExtensions.cs index 00601d2d5..923f9364f 100644 --- a/src/RestSharp/Request/HttpRequestMessageExtensions.cs +++ b/src/RestSharp/Request/HttpRequestMessageExtensions.cs @@ -20,16 +20,16 @@ namespace RestSharp; static class HttpRequestMessageExtensions { public static void AddHeaders(this HttpRequestMessage message, RequestHeaders headers) { - var headerParameters = headers.Parameters.Where(x => !KnownHeaders.IsContentHeader(x.Name!)); + var headerParameters = headers.Where(x => !KnownHeaders.IsContentHeader(x.Name)); - headerParameters.ForEach(x => AddHeader(x, message.Headers)); + headerParameters.GroupBy(x => x.Name).ForEach(x => AddHeader(x, message.Headers)); return; - void AddHeader(Parameter parameter, HttpHeaders httpHeaders) { - var parameterStringValue = parameter.Value!.ToString(); + void AddHeader(IGrouping<string, HeaderParameter> group, HttpHeaders httpHeaders) { + var parameterStringValues = group.Select(x => x.Value); - httpHeaders.Remove(parameter.Name!); - httpHeaders.TryAddWithoutValidation(parameter.Name!, parameterStringValue); + httpHeaders.Remove(group.Key); + httpHeaders.TryAddWithoutValidation(group.Key, parameterStringValues); } } } \ No newline at end of file diff --git a/src/RestSharp/Request/RequestHeaders.cs b/src/RestSharp/Request/RequestHeaders.cs index 9458cad47..10677d6e3 100644 --- a/src/RestSharp/Request/RequestHeaders.cs +++ b/src/RestSharp/Request/RequestHeaders.cs @@ -19,19 +19,17 @@ namespace RestSharp; -class RequestHeaders { - public RequestParameters Parameters { get; } = new(); - +class RequestHeaders : ParametersCollection<HeaderParameter> { public RequestHeaders AddHeaders(ParametersCollection parameters) { - Parameters.AddParameters(parameters.GetParameters<HeaderParameter>()); + Parameters.AddRange(parameters.GetParameters<HeaderParameter>()); return this; } // Add Accept header based on registered deserializers if the caller has set none. public RequestHeaders AddAcceptHeader(string[] acceptedContentTypes) { - if (Parameters.TryFind(KnownHeaders.Accept) == null) { + if (TryFind(KnownHeaders.Accept) == null) { var accepts = acceptedContentTypes.JoinToString(", "); - Parameters.AddParameter(new HeaderParameter(KnownHeaders.Accept, accepts)); + Parameters.Add(new(KnownHeaders.Accept, accepts)); } return this; @@ -46,13 +44,13 @@ public RequestHeaders AddCookieHeaders(Uri uri, CookieContainer? cookieContainer if (string.IsNullOrWhiteSpace(cookies)) return this; var newCookies = SplitHeader(cookies); - var existing = Parameters.GetParameters<HeaderParameter>().FirstOrDefault(x => x.Name == KnownHeaders.Cookie); + var existing = GetParameters<HeaderParameter>().FirstOrDefault(x => x.Name == KnownHeaders.Cookie); if (existing?.Value != null) { - newCookies = newCookies.Union(SplitHeader(existing.Value.ToString()!)); + newCookies = newCookies.Union(SplitHeader(existing.Value!)); } - Parameters.AddParameter(new HeaderParameter(KnownHeaders.Cookie, string.Join("; ", newCookies))); + Parameters.Add(new(KnownHeaders.Cookie, string.Join("; ", newCookies))); return this; diff --git a/src/RestSharp/Request/RestRequest.cs b/src/RestSharp/Request/RestRequest.cs index e0e696517..eaad89972 100644 --- a/src/RestSharp/Request/RestRequest.cs +++ b/src/RestSharp/Request/RestRequest.cs @@ -16,8 +16,8 @@ using RestSharp.Authenticators; using RestSharp.Extensions; using RestSharp.Interceptors; -// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global +// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global // ReSharper disable UnusedAutoPropertyAccessor.Global namespace RestSharp; @@ -190,7 +190,7 @@ public RestRequest(Uri resource, Method method = Method.Get) internal void IncreaseNumberOfAttempts() => Attempts++; /// <summary> - /// How many attempts were made to send this Request + /// The number of attempts that were made to send this request /// </summary> /// <remarks> /// This number is incremented each time the RestClient sends the request. diff --git a/src/RestSharp/Request/RestRequestExtensions.Headers.cs b/src/RestSharp/Request/RestRequestExtensions.Headers.cs index dfd2d8b44..8091a1a50 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Headers.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Headers.cs @@ -17,6 +17,21 @@ namespace RestSharp; public static partial class RestRequestExtensions { + /// <summary> + /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. + /// </summary> + /// <param name="request">Request instance</param> + /// <param name="name">Header name</param> + /// <param name="values">Header values</param> + /// <returns></returns> + public static RestRequest AddHeader(this RestRequest request, string name, string[] values) { + foreach (var value in values) { + AddHeader(request, name, value); + } + + return request; + } + /// <summary> /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. /// </summary> @@ -41,7 +56,7 @@ public static RestRequest AddHeader<T>(this RestRequest request, string name, T /// <summary> /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. - /// Existing header with the same name will be replaced. + /// The existing header with the same name will be replaced. /// </summary> /// <param name="request">Request instance</param> /// <param name="name">Header name</param> @@ -54,7 +69,7 @@ public static RestRequest AddOrUpdateHeader(this RestRequest request, string nam /// <summary> /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. - /// Existing header with the same name will be replaced. + /// The existing header with the same name will be replaced. /// </summary> /// <param name="request">Request instance</param> /// <param name="name">Header name</param> diff --git a/src/RestSharp/Request/UriExtensions.cs b/src/RestSharp/Request/UriExtensions.cs index f6e414f42..5aa9bd3cd 100644 --- a/src/RestSharp/Request/UriExtensions.cs +++ b/src/RestSharp/Request/UriExtensions.cs @@ -40,7 +40,7 @@ public static Uri AddQueryString(this Uri uri, string? query) { var absoluteUri = uri.AbsoluteUri; var separator = absoluteUri.Contains('?') ? "&" : "?"; - return new Uri($"{absoluteUri}{separator}{query}"); + return new($"{absoluteUri}{separator}{query}"); } public static UrlSegmentParamsValues GetUrlSegmentParamsValues( diff --git a/src/RestSharp/Response/RestResponseBase.cs b/src/RestSharp/Response/RestResponseBase.cs index 1ba9ec509..383895fb4 100644 --- a/src/RestSharp/Response/RestResponseBase.cs +++ b/src/RestSharp/Response/RestResponseBase.cs @@ -21,7 +21,7 @@ namespace RestSharp; /// <summary> /// Base class for common properties shared by RestResponse and RestResponse[[T]] /// </summary> -[DebuggerDisplay("{" + nameof(DebuggerDisplay) + "()}")] +[DebuggerDisplay($"{{{nameof(DebuggerDisplay)}()}}")] public abstract class RestResponseBase { /// <summary> /// Default constructor diff --git a/src/RestSharp/RestClient.cs b/src/RestSharp/RestClient.cs index 0b3f58380..95fd432cb 100644 --- a/src/RestSharp/RestClient.cs +++ b/src/RestSharp/RestClient.cs @@ -74,8 +74,8 @@ public RestClient( } ConfigureSerializers(configureSerialization); - Options = new ReadOnlyRestClientOptions(options); - DefaultParameters = new DefaultParameters(Options); + Options = new(options); + DefaultParameters = new(Options); if (useClientFactory) { _disposeHttpClient = false; @@ -121,8 +121,7 @@ public RestClient( ConfigureHeaders? configureDefaultHeaders = null, ConfigureSerialization? configureSerialization = null, bool useClientFactory = false - ) - : this(ConfigureOptions(new RestClientOptions(), configureRestClient), configureDefaultHeaders, configureSerialization, useClientFactory) { } + ) : this(ConfigureOptions(new(), configureRestClient), configureDefaultHeaders, configureSerialization, useClientFactory) { } /// <inheritdoc /> /// <summary> @@ -141,7 +140,7 @@ public RestClient( bool useClientFactory = false ) : this( - ConfigureOptions(new RestClientOptions { BaseUrl = baseUrl }, configureRestClient), + ConfigureOptions(new() { BaseUrl = baseUrl }, configureRestClient), configureDefaultHeaders, configureSerialization, useClientFactory @@ -185,8 +184,8 @@ public RestClient( } var opt = options ?? new RestClientOptions(); - Options = new ReadOnlyRestClientOptions(opt); - DefaultParameters = new DefaultParameters(Options); + Options = new(opt); + DefaultParameters = new(Options); if (options != null) { ConfigureHttpClient(httpClient, options); @@ -207,7 +206,7 @@ public RestClient( ConfigureRestClient? configureRestClient = null, ConfigureSerialization? configureSerialization = null ) - : this(httpClient, ConfigureOptions(new RestClientOptions(), configureRestClient), disposeHttpClient, configureSerialization) { } + : this(httpClient, ConfigureOptions(new(), configureRestClient), disposeHttpClient, configureSerialization) { } /// <summary> /// Creates a new instance of RestSharp using the message handler provided. By default, HttpClient disposes the provided handler @@ -270,7 +269,7 @@ void ConfigureSerializers(ConfigureSerialization? configureSerialization) { var serializerConfig = new SerializerConfig(); serializerConfig.UseDefaultSerializers(); configureSerialization?.Invoke(serializerConfig); - Serializers = new RestSerializers(serializerConfig); + Serializers = new(serializerConfig); AcceptedContentTypes = Serializers.GetAcceptedContentTypes(); }
diff --git a/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs b/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs index 6d5618283..559c6435a 100644 --- a/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs +++ b/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs @@ -50,8 +50,7 @@ public async Task Should_use_both_default_and_request_headers() { _client.AddDefaultHeader(defaultHeader.Name, defaultHeader.Value); - var request = new RestRequest("/headers") - .AddHeader(requestHeader.Name, requestHeader.Value); + var request = new RestRequest("/headers").AddHeader(requestHeader.Name, requestHeader.Value); var response = await _client.ExecuteAsync<TestServerResponse[]>(request); CheckHeader(response, defaultHeader); diff --git a/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs b/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs index 3a10375d9..1afe25fc3 100644 --- a/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs +++ b/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs @@ -1,14 +1,15 @@ using RestSharp.Serializers; + // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable ClassNeverInstantiated.Global +#pragma warning disable CS8981 // The type name only contains lower-cased ascii characters. Such names may become reserved for the language. #pragma warning disable CS8981 -namespace RestSharp.Tests.Serializers.Xml.SampleClasses; +namespace RestSharp.Tests.Serializers.Xml.SampleClasses; #pragma warning disable CS8981 public class status { -#pragma warning restore CS8981 public bool truncated { get; set; } public string created_at { get; set; } @@ -113,4 +114,5 @@ public class complexStatus { public long id { get; set; } public string text { get; set; } -} \ No newline at end of file +} +#pragma warning restore CS8981 \ No newline at end of file diff --git a/test/RestSharp.Tests/RequestHeaderTests.cs b/test/RestSharp.Tests/RequestHeaderTests.cs index 8752dca10..6fa6c8215 100644 --- a/test/RestSharp.Tests/RequestHeaderTests.cs +++ b/test/RestSharp.Tests/RequestHeaderTests.cs @@ -21,7 +21,7 @@ public void AddHeaders_SameCaseDuplicatesExist_ThrowsException() { [Fact] public void AddHeaders_DifferentCaseDuplicatesExist_ThrowsException() { var headers = _headers; - headers.Add(new KeyValuePair<string, string>(KnownHeaders.Accept, ContentType.Json)); + headers.Add(new(KnownHeaders.Accept, ContentType.Json)); var request = new RestRequest(); @@ -63,7 +63,6 @@ public void AddOrUpdateHeader_ShouldUpdateExistingHeader_WhenHeaderExist() { request.AddOrUpdateHeader(KnownHeaders.Accept, ContentType.Json); // Assert - var headers = GetHeaders(request); GetHeader(request, KnownHeaders.Accept).Should().Be(ContentType.Json); } @@ -121,10 +120,8 @@ public void AddOrUpdateHeaders_ShouldUpdateHeaders_WhenAllExists() { // Assert var requestHeaders = GetHeaders(request); - HeaderParameter[] expected = [ - new HeaderParameter(KnownHeaders.Accept, ContentType.Xml), - new HeaderParameter(KnownHeaders.KeepAlive, "400") - ]; + + HeaderParameter[] expected = [new(KnownHeaders.Accept, ContentType.Xml), new(KnownHeaders.KeepAlive, "400")]; requestHeaders.Should().BeEquivalentTo(expected); } @@ -151,13 +148,33 @@ public void AddOrUpdateHeaders_ShouldAddAndUpdateHeaders_WhenSomeExists() { var requestHeaders = GetHeaders(request); HeaderParameter[] expected = [ - new HeaderParameter(KnownHeaders.Accept, ContentType.Xml), - new HeaderParameter(KnownHeaders.AcceptLanguage, "en-us,en;q=0.5"), - new HeaderParameter(KnownHeaders.KeepAlive, "300") + new(KnownHeaders.Accept, ContentType.Xml), + new(KnownHeaders.AcceptLanguage, "en-us,en;q=0.5"), + new(KnownHeaders.KeepAlive, "300") ]; requestHeaders.Should().BeEquivalentTo(expected); } + [Fact] + public void Should_not_allow_null_header_value() { + string value = null; + var request = new RestRequest(); + // ReSharper disable once AssignNullToNotNullAttribute + Assert.Throws<ArgumentNullException>("value", () => request.AddHeader("name", value)); + } + + [Fact] + public void Should_not_allow_null_header_name() { + var request = new RestRequest(); + Assert.Throws<ArgumentNullException>("name", () => request.AddHeader(null!, "value")); + } + + [Fact] + public void Should_not_allow_empty_header_name() { + var request = new RestRequest(); + Assert.Throws<ArgumentException>("name", () => request.AddHeader("", "value")); + } + static Parameter[] GetHeaders(RestRequest request) => request.Parameters.Where(x => x.Type == ParameterType.HttpHeader).ToArray(); static string GetHeader(RestRequest request, string name) => request.Parameters.FirstOrDefault(x => x.Name == name)?.Value?.ToString();
Unexpected behavoir when upgrading to 111.3.0 Hi Upgraded a little internal tool which uses restsharp to use version 111.3.0 instead 110.2.0 and started to get the following error : ```` A default parameters with the same name has already been added ```` After quick check i found that the following code is the problem ```` var cli = new RestClient(); cli.AddDefaultHeader("User-Agent", "myagent"); return cli; ```` AddDefaultHeader throws the exception and changing the code to : ```` var cli = new RestClient(); cli.DefaultParameters.RemoveParameter("User-Agent", ParameterType.HttpHeader); cli.AddDefaultHeader("User-Agent", "myAgent"); return cli; ```` Workarounds this problem. Is this behavior is by design ?
null
2024-07-11T12:04:51Z
0.1
['RestSharp.Tests.RequestHeaderTests.Should_not_allow_null_header_value', 'RestSharp.Tests.RequestHeaderTests.Should_not_allow_null_header_name', 'RestSharp.Tests.RequestHeaderTests.Should_not_allow_empty_header_name']
['RestSharp.Tests.Integrated.HttpHeadersTests.Should_use_both_default_and_request_headers', 'RestSharp.Tests.RequestHeaderTests.AddHeaders_SameCaseDuplicatesExist_ThrowsException', 'RestSharp.Tests.RequestHeaderTests.AddHeaders_DifferentCaseDuplicatesExist_ThrowsException', 'RestSharp.Tests.RequestHeaderTests.AddOrUpdateHeader_ShouldUpdateExistingHeader_WhenHeaderExist', 'RestSharp.Tests.RequestHeaderTests.AddOrUpdateHeaders_ShouldUpdateHeaders_WhenAllExists', 'RestSharp.Tests.RequestHeaderTests.AddOrUpdateHeaders_ShouldAddAndUpdateHeaders_WhenSomeExists']
restsharp/RestSharp
restsharp__restsharp-2021
620a5576525ac9eab70bcc00337a15aa2750716c
diff --git a/src/RestSharp/Request/RequestContent.cs b/src/RestSharp/Request/RequestContent.cs index bf900be82..7064b5854 100644 --- a/src/RestSharp/Request/RequestContent.cs +++ b/src/RestSharp/Request/RequestContent.cs @@ -23,20 +23,22 @@ namespace RestSharp; class RequestContent : IDisposable { - readonly RestClient _client; - readonly RestRequest _request; - readonly List<Stream> _streams = new(); + readonly RestClient _client; + readonly RestRequest _request; + readonly List<Stream> _streams = new(); + readonly ParametersCollection _parameters; HttpContent? Content { get; set; } public RequestContent(RestClient client, RestRequest request) { - _client = client; - _request = request; + _client = client; + _request = request; + _parameters = new ParametersCollection(_request.Parameters.Union(_client.DefaultParameters)); } public HttpContent BuildContent() { AddFiles(); - var postParameters = _request.Parameters.GetContentParameters(_request.Method).ToArray(); + var postParameters = _parameters.GetContentParameters(_request.Method).ToArray(); AddBody(postParameters.Length > 0); AddPostParameters(postParameters); AddHeaders(); @@ -170,7 +172,7 @@ void AddPostParameters(GetOrPostParameter[] postParameters) { #else // However due to bugs in HttpClient FormUrlEncodedContent (see https://github.com/restsharp/RestSharp/issues/1814) we // do the encoding ourselves using WebUtility.UrlEncode instead. - var encodedItems = postParameters.Select(x => $"{x.Name!.UrlEncode()}={x.Value?.ToString()?.UrlEncode() ?? string.Empty}"); + var encodedItems = postParameters.Select(x => $"{x.Name!.UrlEncode()}={x.Value?.ToString()?.UrlEncode() ?? string.Empty}"); var encodedContent = new StringContent(encodedItems.JoinToString("&"), null, ContentType.FormUrlEncoded.Value); Content = encodedContent; #endif @@ -178,7 +180,7 @@ void AddPostParameters(GetOrPostParameter[] postParameters) { } void AddHeaders() { - var contentHeaders = _request.Parameters + var contentHeaders = _parameters .GetParameters<HeaderParameter>() .Where(x => IsContentHeader(x.Name!)) .ToArray();
diff --git a/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs b/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs index 0e19c5d38..d5714eadd 100644 --- a/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs +++ b/test/RestSharp.Tests.Integrated/HttpHeadersTests.cs @@ -1,24 +1,26 @@ +using System.Net; using RestSharp.Tests.Integrated.Fixtures; +using RestSharp.Tests.Integrated.Server; using RestSharp.Tests.Shared.Fixtures; namespace RestSharp.Tests.Integrated; -public class HttpHeadersTests : CaptureFixture { +[Collection(nameof(TestServerCollection))] +public class HttpHeadersTests { readonly ITestOutputHelper _output; + readonly RestClient _client; - public HttpHeadersTests(ITestOutputHelper output) => _output = output; + public HttpHeadersTests(TestServerFixture fixture, ITestOutputHelper output) { + _output = output; + _client = new RestClient(new RestClientOptions(fixture.Server.Url) { ThrowOnAnyError = true }); + } [Fact] public async Task Ensure_headers_correctly_set_in_the_hook() { const string headerName = "HeaderName"; const string headerValue = "HeaderValue"; - using var server = SimpleServer.Create(Handlers.Generic<RequestHeadCapturer>()); - - // Prepare - var client = new RestClient(server.Url); - - var request = new RestRequest(RequestHeadCapturer.Resource) { + var request = new RestRequest("/headers") { OnBeforeRequest = http => { http.Headers.Add(headerName, headerValue); return default; @@ -26,9 +28,35 @@ public async Task Ensure_headers_correctly_set_in_the_hook() { }; // Run - await client.ExecuteAsync(request); + var response = await _client.ExecuteAsync<TestServerResponse[]>(request); // Assert - RequestHeadCapturer.CapturedHeaders[headerName].Should().Be(headerValue); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var header = response.Data!.First(x => x.Name == headerName); + header.Should().NotBeNull(); + header.Value.Should().Be(headerValue); } + + [Fact] + public async Task Should_use_both_default_and_request_headers() { + var defaultHeader = new Header("defName", "defValue"); + var requestHeader = new Header("reqName", "reqValue"); + + _client.AddDefaultHeader(defaultHeader.Name, defaultHeader.Value); + + var request = new RestRequest("/headers") + .AddHeader(requestHeader.Name, requestHeader.Value); + + var response = await _client.ExecuteAsync<TestServerResponse[]>(request); + CheckHeader(defaultHeader); + CheckHeader(requestHeader); + + void CheckHeader(Header header) { + var h = response.Data!.First(x => x.Name == header.Name); + h.Should().NotBeNull(); + h.Value.Should().Be(header.Value); + } + } + + record Header(string Name, string Value); } \ No newline at end of file diff --git a/test/RestSharp.Tests.Integrated/PostTests.cs b/test/RestSharp.Tests.Integrated/PostTests.cs index a37a454a6..4319aa06b 100644 --- a/test/RestSharp.Tests.Integrated/PostTests.cs +++ b/test/RestSharp.Tests.Integrated/PostTests.cs @@ -47,7 +47,32 @@ public async Task Should_post_large_form_data() { response.Data!.Message.Should().Be($"Works! Length: {length}"); } + [Fact] + public async Task Should_post_both_default_and_request_parameters() { + var defParam = new PostParameter("default", "default"); + var reqParam = new PostParameter("request", "request"); + + _client.AddDefaultParameter(defParam.Name, defParam.Value); + + var request = new RestRequest("post/data") + .AddParameter(reqParam.Name, reqParam.Value); + + var response = await _client.ExecutePostAsync<TestServerResponse[]>(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + CheckResponse(defParam); + CheckResponse(reqParam); + + void CheckResponse(PostParameter parameter) { + var p = response.Data!.FirstOrDefault(x => x.Name == parameter.Name); + p.Should().NotBeNull(); + p.Value.Should().Be(parameter.Value); + } + } + class Response { public string Message { get; set; } } + + record PostParameter(string Name, string Value); } diff --git a/test/RestSharp.Tests.Integrated/RequestHeadTests.cs b/test/RestSharp.Tests.Integrated/RequestHeadTests.cs index a69cc5b9b..1c5d98eb1 100644 --- a/test/RestSharp.Tests.Integrated/RequestHeadTests.cs +++ b/test/RestSharp.Tests.Integrated/RequestHeadTests.cs @@ -54,7 +54,7 @@ public async Task Passes_Default_Credentials_When_UseDefaultCredentials_Is_True( response.StatusCode.ToString().Should().BeOneOf(HttpStatusCode.OK.ToString(),HttpStatusCode.Unauthorized.ToString()); RequestHeadCapturer.CapturedHeaders.Should().NotBeNull(); - var keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast<string>().ToArray(); + var keys = RequestHeadCapturer.CapturedHeaders!.Keys.Cast<string>().ToArray(); keys.Should() .Contain( diff --git a/test/RestSharp.Tests.Integrated/Server/Handlers/FormRequest.cs b/test/RestSharp.Tests.Integrated/Server/Handlers/FormRequest.cs new file mode 100644 index 000000000..a4ab7f90c --- /dev/null +++ b/test/RestSharp.Tests.Integrated/Server/Handlers/FormRequest.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Http; + +namespace RestSharp.Tests.Integrated.Server.Handlers; + +public static class FormRequestHandler { + public static IResult HandleForm(HttpContext ctx) { + var response = ctx.Request.Form.Select( + x => new TestServerResponse(x.Key, x.Value) + ); + return Results.Ok(response); + } +} diff --git a/test/RestSharp.Tests.Integrated/Server/TestServer.cs b/test/RestSharp.Tests.Integrated/Server/TestServer.cs index df9307e07..4eed43032 100644 --- a/test/RestSharp.Tests.Integrated/Server/TestServer.cs +++ b/test/RestSharp.Tests.Integrated/Server/TestServer.cs @@ -61,6 +61,8 @@ public HttpServer(ITestOutputHelper? output = null) { "/post/form", (HttpContext context) => new TestResponse { Message = $"Works! Length: {context.Request.Form["big_string"].ToString().Length}" } ); + + _app.MapPost("/post/data", FormRequestHandler.HandleForm); } public Uri Url => new(Address); diff --git a/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs b/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs index 53cdb83b1..d09df6540 100644 --- a/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs +++ b/test/RestSharp.Tests.Serializers.Xml/SampleClasses/twitter.cs @@ -1,8 +1,11 @@ using RestSharp.Serializers; +// ReSharper disable InconsistentNaming namespace RestSharp.Tests.Serializers.Xml.SampleClasses; +#pragma warning disable CS8981 public class status { +#pragma warning restore CS8981 public bool truncated { get; set; } public string created_at { get; set; }
Adding a DefaultParameter on a RestClient and use it in a Post request doesn't work **Describe the bug** Adding a DefaultParameter on a RestClient and use it in a Post request doesn't work anymore in version 108.0.2. The parameter is ignored and not send in the request. This did work in version 106. **To Reproduce** Create a restclient and when created add a default parameter: ``` private RestClient CurrentRestClient { get; set; } = null; CurrentRestClient = new RestClient("myrestendpoint"); CurrentRestClient.AddDefaultParameter("f", "json"); RestRequest myrequest= new RestRequest("mypath", Method.Post); RestResponse response = CurrentRestClient.Execute(myrequest); ``` Response contains a HTML output because the server did not receive the f parameter. When adding the next line, the response is correct: `myrequest.AddParameter("f", "json");` So adding the parameter on the request works fine. **Expected behavior** When adding a default parameter as get/post, the parameter should also be sent to the server in case of a post request. **Desktop (please complete the following information):** - OS: Windows - .NET version 6 - Version 108.0.2
I've created a workaround: ``` private RestResponse ExecuteWithDefaults(RestRequest request) { foreach (Parameter parameter in CurrentRestClient.DefaultParameters) { request.AddParameter(parameter); } return CurrentRestClient.Execute(request, Method.Post); } ``` This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. ⚠️ This issue has been marked wontfix and will be closed in 3 days
2023-03-12T17:07:33Z
0.1
['RestSharp.Tests.Integrated.HttpHeadersTests.Should_use_both_default_and_request_headers', 'RestSharp.Tests.Integrated.PostTests.Should_post_both_default_and_request_parameters']
['RestSharp.Tests.Integrated.HttpHeadersTests.Ensure_headers_correctly_set_in_the_hook', 'RestSharp.Tests.Integrated.PostTests.Should_post_large_form_data']
restsharp/RestSharp
restsharp__restsharp-2020
620a5576525ac9eab70bcc00337a15aa2750716c
diff --git a/src/RestSharp/Request/RequestContent.cs b/src/RestSharp/Request/RequestContent.cs index bf900be82..1b3db3c9c 100644 --- a/src/RestSharp/Request/RequestContent.cs +++ b/src/RestSharp/Request/RequestContent.cs @@ -47,7 +47,7 @@ public HttpContent BuildContent() { void AddFiles() { if (!_request.HasFiles() && !_request.AlwaysMultipartFormData) return; - var mpContent = new MultipartFormDataContent(GetOrSetFormBoundary()); + var mpContent = CreateMultipartFormDataContent(); foreach (var file in _request.Files) { var stream = file.GetFile(); @@ -58,10 +58,7 @@ void AddFiles() { var dispositionHeader = file.Options.DisableFilenameEncoding ? ContentDispositionHeaderValue.Parse($"form-data; name=\"{file.Name}\"; filename=\"{file.FileName}\"") - : new ContentDispositionHeaderValue("form-data") { - Name = $"\"{file.Name}\"", - FileName = $"\"{file.FileName}\"" - }; + : new ContentDispositionHeaderValue("form-data") { Name = $"\"{file.Name}\"", FileName = $"\"{file.FileName}\"" }; if (!file.Options.DisableFileNameStar) dispositionHeader.FileNameStar = file.FileName; fileContent.Headers.ContentDisposition = dispositionHeader; @@ -102,11 +99,7 @@ HttpContent GetSerialized() { var contentType = body.ContentType.Or(serializer.Serializer.ContentType); - return new StringContent( - content, - _client.Options.Encoding, - contentType.Value - ); + return new StringContent(content, _client.Options.Encoding, contentType.Value); } } @@ -117,6 +110,15 @@ static bool BodyShouldBeMultipartForm(BodyParameter bodyParameter) { string GetOrSetFormBoundary() => _request.FormBoundary ?? (_request.FormBoundary = Guid.NewGuid().ToString()); + MultipartFormDataContent CreateMultipartFormDataContent() { + var boundary = GetOrSetFormBoundary(); + var mpContent = new MultipartFormDataContent(boundary); + var contentType = new MediaTypeHeaderValue("multipart/form-data"); + contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), GetBoundary(boundary, _request.MultipartFormQuoteParameters))); + mpContent.Headers.ContentType = contentType; + return mpContent; + } + void AddBody(bool hasPostParameters) { if (!_request.TryGetBodyParameter(out var bodyParameter)) return; @@ -125,7 +127,7 @@ void AddBody(bool hasPostParameters) { // we need to send the body if (hasPostParameters || _request.HasFiles() || BodyShouldBeMultipartForm(bodyParameter!) || _request.AlwaysMultipartFormData) { // here we must use multipart form data - var mpContent = Content as MultipartFormDataContent ?? new MultipartFormDataContent(GetOrSetFormBoundary()); + var mpContent = Content as MultipartFormDataContent ?? CreateMultipartFormDataContent(); var ct = bodyContent.Headers.ContentType?.MediaType; var name = bodyParameter!.Name.IsEmpty() ? ct : bodyParameter.Name; @@ -155,7 +157,7 @@ void AddPostParameters(GetOrPostParameter[] postParameters) { mpContent.Add( new StringContent(postParameter.Value?.ToString() ?? "", _client.Options.Encoding, postParameter.ContentType.Value), - _request.MultipartFormQuoteParameters ? $"\"{parameterName}\"" : parameterName + parameterName ); } } @@ -177,6 +179,8 @@ void AddPostParameters(GetOrPostParameter[] postParameters) { } } + static string GetBoundary(string boundary, bool quote) => quote ? $"\"{boundary}\"" : boundary; + void AddHeaders() { var contentHeaders = _request.Parameters .GetParameters<HeaderParameter>() @@ -203,7 +207,7 @@ void AddHeader(HeaderParameter parameter) { string GetContentTypeHeader(string contentType) => Content is MultipartFormDataContent - ? $"{contentType}; boundary=\"{GetOrSetFormBoundary()}\"" + ? $"{contentType}; boundary={GetBoundary(GetOrSetFormBoundary(), _request.MultipartFormQuoteParameters)}" : contentType; } diff --git a/src/RestSharp/Request/RestRequest.cs b/src/RestSharp/Request/RestRequest.cs index 0cc33ba16..023877522 100644 --- a/src/RestSharp/Request/RestRequest.cs +++ b/src/RestSharp/Request/RestRequest.cs @@ -86,7 +86,7 @@ public RestRequest(Uri resource, Method method = Method.Get) /// quotation marks. Default is false. Enable it if the remote endpoint requires parameters /// to be in quotes (for example, FreshDesk API). /// </summary> - public bool MultipartFormQuoteParameters { get; set; } + public bool MultipartFormQuoteParameters { get; set; } = true; public string? FormBoundary { get; set; }
diff --git a/test/RestSharp.Tests.Integrated/MultipartFormDataTests.cs b/test/RestSharp.Tests.Integrated/MultipartFormDataTests.cs index 4ea0e3c8b..6e4a995e9 100644 --- a/test/RestSharp.Tests.Integrated/MultipartFormDataTests.cs +++ b/test/RestSharp.Tests.Integrated/MultipartFormDataTests.cs @@ -32,13 +32,13 @@ public MultipartFormDataTests(ITestOutputHelper output) { $"--{{0}}--{LineBreak}"; const string ExpectedFileAndBodyRequestContent = - "--{0}" + - $"{LineBreak}{KnownHeaders.ContentType}: application/octet-stream" + + "--{0}" + + $"{LineBreak}{KnownHeaders.ContentType}: application/octet-stream" + $"{LineBreak}{KnownHeaders.ContentDisposition}: form-data; name=\"fileName\"; filename=\"TestFile.txt\"" + - $"{LineBreak}{LineBreak}This is a test file for RestSharp.{LineBreak}" + - $"--{{0}}{LineBreak}{KnownHeaders.ContentType}: application/json; {CharsetString}" + - $"{LineBreak}{KnownHeaders.ContentDisposition}: form-data; name=controlName" + - $"{LineBreak}{LineBreak}test{LineBreak}" + + $"{LineBreak}{LineBreak}This is a test file for RestSharp.{LineBreak}" + + $"--{{0}}{LineBreak}{KnownHeaders.ContentType}: application/json; {CharsetString}" + + $"{LineBreak}{KnownHeaders.ContentDisposition}: form-data; name=controlName" + + $"{LineBreak}{LineBreak}test{LineBreak}" + $"--{{0}}--{LineBreak}"; const string ExpectedDefaultMultipartContentType = "multipart/form-data; boundary=\"{0}\""; @@ -76,11 +76,24 @@ public async Task AlwaysMultipartFormData_WithParameter_Execute() { Assert.Null(response.ErrorException); } + [Fact] + public async Task MultipartFormData_NoBoundaryQuotes() { + var request = new RestRequest("/", Method.Post) { AlwaysMultipartFormData = true }; + + AddParameters(request); + request.MultipartFormQuoteParameters = false; + + var response = await _client.ExecuteAsync(request); + + var expected = string.Format(Expected, request.FormBoundary); + + response.Content.Should().Be(expected); + RequestHandler.CapturedContentType.Should().Be($"multipart/form-data; boundary={request.FormBoundary}"); + } + [Fact] public async Task MultipartFormData() { - var request = new RestRequest("/", Method.Post) { - AlwaysMultipartFormData = true - }; + var request = new RestRequest("/", Method.Post) { AlwaysMultipartFormData = true }; AddParameters(request); @@ -91,7 +104,8 @@ public async Task MultipartFormData() { _output.WriteLine($"Expected: {expected}"); _output.WriteLine($"Actual: {response.Content}"); - Assert.Equal(expected, response.Content); + response.Content.Should().Be(expected); + RequestHandler.CapturedContentType.Should().Be($"multipart/form-data; boundary=\"{request.FormBoundary}\""); } [Fact] @@ -187,4 +201,4 @@ public async Task ShouldHaveJsonContentType() { var response = await _client.ExecuteAsync(request); } -} \ No newline at end of file +}
Double quotes option for multipart/form-data boundary I tried migration 104 to 108. But since version 107, System.net.http is used for Http Request. It makes difference. When upload file using multipart/form-data, `AddFiles` called. And it makes MultipartFormDataContent and pass boundary to parameter. https://github.com/restsharp/RestSharp/blob/f7d3984244c4808ae7c068e028753c2857f325b9/src/RestSharp/Request/RequestContent.cs#L48-L51 Also this is : https://github.com/restsharp/RestSharp/blob/f7d3984244c4808ae7c068e028753c2857f325b9/src/RestSharp/Request/RequestContent.cs#L211 When MultipartFormDataContent created the boundary parameter will always wrapped "(double quotes). boundary will like this in version 107 : > boundary="gc0pJq0M8jU534c0p" But in version 104 : > boundary=gc0pJq0M8jU534c0p There is no double quotes. According to [RFC 2046](https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1) double quotes is selective option. How about add new option in RestSharp for double quotes?
null
2023-03-12T16:13:36Z
0.1
['RestSharp.Tests.Integrated.MultipartFormDataTests.MultipartFormData_NoBoundaryQuotes', 'RestSharp.Tests.Integrated.MultipartFormDataTests.MultipartFormData']
['RestSharp.Tests.Integrated.MultipartFormDataTests.AlwaysMultipartFormData_WithParameter_Execute']
restsharp/RestSharp
restsharp__restsharp-1962
e636ab4579e2bedf47391da062166a9d64f9a7a2
diff --git a/src/RestSharp/Extensions/HttpResponseExtensions.cs b/src/RestSharp/Extensions/HttpResponseExtensions.cs new file mode 100644 index 000000000..53b873e6c --- /dev/null +++ b/src/RestSharp/Extensions/HttpResponseExtensions.cs @@ -0,0 +1,27 @@ +// Copyright (c) .NET Foundation and Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace RestSharp.Extensions; + +public static class HttpResponseExtensions { + internal static Exception? MaybeException(this HttpResponseMessage httpResponse) + => httpResponse.IsSuccessStatusCode + ? null +#if NETSTANDARD + : new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}"); +#else + : new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode); +#endif +} diff --git a/src/RestSharp/Response/RestResponse.cs b/src/RestSharp/Response/RestResponse.cs index 503d2c7f2..a9225ec23 100644 --- a/src/RestSharp/Response/RestResponse.cs +++ b/src/RestSharp/Response/RestResponse.cs @@ -89,7 +89,7 @@ async Task<RestResponse> GetDefaultResponse() { ContentLength = httpResponse.Content.Headers.ContentLength, ContentType = httpResponse.Content.Headers.ContentType?.MediaType, ResponseStatus = calculateResponseStatus(httpResponse), - ErrorException = MaybeException(), + ErrorException = httpResponse.MaybeException(), ResponseUri = httpResponse.RequestMessage!.RequestUri, Server = httpResponse.Headers.Server.ToString(), StatusCode = httpResponse.StatusCode, @@ -102,15 +102,6 @@ async Task<RestResponse> GetDefaultResponse() { RootElement = request.RootElement }; - Exception? MaybeException() - => httpResponse.IsSuccessStatusCode - ? null -#if NETSTANDARD - : new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}"); -#else - : new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode); -#endif - Task<Stream?> ReadResponse() => httpResponse.ReadResponse(cancellationToken); async Task<Stream?> ReadAndConvertResponse() { diff --git a/src/RestSharp/RestClient.Async.cs b/src/RestSharp/RestClient.Async.cs index 7a353e550..0a57d189f 100644 --- a/src/RestSharp/RestClient.Async.cs +++ b/src/RestSharp/RestClient.Async.cs @@ -50,8 +50,7 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo using var requestContent = new RequestContent(this, request); - if (Authenticator != null) - await Authenticator.Authenticate(this, request).ConfigureAwait(false); + if (Authenticator != null) await Authenticator.Authenticate(this, request).ConfigureAwait(false); var httpMethod = AsHttpMethod(request.Method); var url = BuildUri(request); @@ -61,7 +60,8 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo using var timeoutCts = new CancellationTokenSource(request.Timeout > 0 ? request.Timeout : int.MaxValue); using var cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken); - var ct = cts.Token; + + var ct = cts.Token; try { var headers = new RequestHeaders() @@ -70,13 +70,11 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo .AddAcceptHeader(AcceptedContentTypes); message.AddHeaders(headers); - if (request.OnBeforeRequest != null) - await request.OnBeforeRequest(message).ConfigureAwait(false); + if (request.OnBeforeRequest != null) await request.OnBeforeRequest(message).ConfigureAwait(false); var responseMessage = await HttpClient.SendAsync(message, request.CompletionOption, ct).ConfigureAwait(false); - if (request.OnAfterRequest != null) - await request.OnAfterRequest(responseMessage).ConfigureAwait(false); + if (request.OnAfterRequest != null) await request.OnAfterRequest(responseMessage).ConfigureAwait(false); return new InternalResponse(responseMessage, url, null, timeoutCts.Token); } @@ -99,8 +97,10 @@ record InternalResponse(HttpResponseMessage? ResponseMessage, Uri Url, Exception request.CompletionOption = HttpCompletionOption.ResponseHeadersRead; var response = await ExecuteInternal(request, cancellationToken).ConfigureAwait(false); - if (response.Exception != null) { - return Options.ThrowOnAnyError ? throw response.Exception : null; + var exception = response.Exception ?? response.ResponseMessage?.MaybeException(); + + if (exception != null) { + return Options.ThrowOnAnyError ? throw exception : null; } if (response.ResponseMessage == null) return null; @@ -141,7 +141,7 @@ static HttpMethod AsHttpMethod(Method method) #if NETSTANDARD Method.Patch => new HttpMethod("PATCH"), #else - Method.Patch => HttpMethod.Patch, + Method.Patch => HttpMethod.Patch, #endif Method.Merge => new HttpMethod("MERGE"), Method.Copy => new HttpMethod("COPY"), @@ -157,11 +157,11 @@ public static RestResponse ThrowIfError(this RestResponse response) { return response; } - + public static RestResponse<T> ThrowIfError<T>(this RestResponse<T> response) { var exception = response.GetException(); if (exception != null) throw exception; return response; } -} \ No newline at end of file +}
diff --git a/test/RestSharp.Tests.Integrated/DownloadFileTests.cs b/test/RestSharp.Tests.Integrated/DownloadFileTests.cs index fe7a2fde3..aa30a158e 100644 --- a/test/RestSharp.Tests.Integrated/DownloadFileTests.cs +++ b/test/RestSharp.Tests.Integrated/DownloadFileTests.cs @@ -7,7 +7,8 @@ namespace RestSharp.Tests.Integrated; public sealed class DownloadFileTests : IDisposable { public DownloadFileTests() { _server = HttpServerFixture.StartServer("Assets/Koala.jpg", FileHandler); - _client = new RestClient(_server.Url); + var options = new RestClientOptions(_server.Url) { ThrowOnAnyError = true }; + _client = new RestClient(options); } public void Dispose() => _server.Dispose(); @@ -46,6 +47,13 @@ public async Task AdvancedResponseWriter_without_ResponseWriter_reads_stream() { Assert.True(string.Compare("JFIF", tag, StringComparison.Ordinal) == 0); } + [Fact] + public async Task Handles_File_Download_Failure() { + var request = new RestRequest("Assets/Koala1.jpg"); + var task = () => _client.DownloadDataAsync(request); + await task.Should().ThrowAsync<HttpRequestException>().WithMessage("Request failed with status code NotFound"); + } + [Fact] public async Task Handles_Binary_File_Download() { var request = new RestRequest("Assets/Koala.jpg"); @@ -76,4 +84,4 @@ public async Task Writes_Response_To_Stream() { Assert.Equal(expected, fromTemp); } -} \ No newline at end of file +}
DownloadStreamAsync does not handle 404 pages? **DO NOT USE ISSUES FOR QUESTIONS** **Describe the bug** As it stands currently, DownloadStreamAsync executes the request and blindly downloads whatever response it gets back regardless of whether the request was successful on or. So if you have someone rendering a fancy 404 page like this one: http://bti-usa.com/images/pictures/sf/sf3058.jpg It gets happily downloaded as a file (which of course is not actually a jpg file, but that is not the root issue here :) ). **To Reproduce** Download the URL above using DownloadStreamAsync and it will download the contents. **Expected behavior** I think the correct behavior here is that DownloadStreamAsync should check for a valid HTTP status (say 200/OK?) and then return null or something if the status is not valid? I am not sure if that would be a breaking change or not, as it is not clear what the callers would expect for the resulting stream on error. Perhaps it would expect an exception to be thrown if something was wrong, otherwise it expects a valid stream and would not expect a null (and would crash with an NRE). For now I am simply going to implement my own download code that handles the response codes, but I think this is something that the library should be responsible for doing correctly?
Yeah, that's a miss. I will add a test, and then we can decide what to do with it. If the client is set to throw, I can accommodate that. However, 404 isn't currently considered as an error. Maybe returning nothing would be a good solution? I already have a fix in my own branch, so you could pull that over for the 404 handling? Also added an exception when we attempt to use a disposed RestClient :) https://github.com/kendallb/RestSharp/commit/27c47663a0ea9bf10206125d49fdf00d1a83d10f I think adding this would be too big of a change, as it doesn't work this way now ``` if (!responseMessage.IsSuccessStatusCode) { var statusCode = responseMessage.StatusCode; throw new WebException($"The remote server returned an error: ({(int)statusCode}) {statusCode}"); } ``` What I can do is to move the check downstream, particularly to the `Download` function. I am not sure yet if it's doable. The default behaviour was always that RestSharp doesn't throw by default and rather return an error response. For example, you can examine the response content to find out what it says. The client throws in `GetAsync` etc overloads, it's by design, or when the client `ThrowOnAnyError` is set. As the download function is relatively new, I can change its behaviour without breaking too much, but it still needs to be a major version update. Well I am not sure you can move it any higher up, as the function I am calling is DownloadStreamAsync so for my use case it is already as high up the food chain as possible. So while it is not how it functions today, it is also impossible to implement the mechanism of returning an Exception from that function because there is no return response from DownloadStream or Download to inspect. We could change it to only throw that exception if Options.ThrowOnAnyError is set so it would be the same as the exception handling above it, but I do wonder if that option makes any sense at all inside DownloadStreamAsync because there is no way for the caller to ever get the underlying exception that occurred if Options.ThrowOnAnyError is false? It will just silently fail and you get really strange results downloaded.
2022-11-08T09:52:13Z
0.1
['RestSharp.Tests.Integrated.DownloadFileTests.Handles_File_Download_Failure']
['RestSharp.Tests.Integrated.DownloadFileTests.AdvancedResponseWriter_without_ResponseWriter_reads_stream', 'RestSharp.Tests.Integrated.DownloadFileTests.Handles_Binary_File_Download', 'RestSharp.Tests.Integrated.DownloadFileTests.Writes_Response_To_Stream']
restsharp/RestSharp
restsharp__restsharp-1676
49ce0280cf54e6dde45d3753846e547473f0c59a
diff --git a/src/RestSharp/Response/RestResponse.cs b/src/RestSharp/Response/RestResponse.cs index dafd9b3d8..eed4b500d 100644 --- a/src/RestSharp/Response/RestResponse.cs +++ b/src/RestSharp/Response/RestResponse.cs @@ -42,6 +42,7 @@ public static RestResponse<T> FromResponse(RestResponse response) ErrorMessage = response.ErrorMessage, ErrorException = response.ErrorException, Headers = response.Headers, + IsSuccessful = response.IsSuccessful, ResponseStatus = response.ResponseStatus, ResponseUri = response.ResponseUri, Server = response.Server,
diff --git a/test/RestSharp.IntegrationTests/StatusCodeTests.cs b/test/RestSharp.IntegrationTests/StatusCodeTests.cs index ff035f47f..af4f44ed3 100644 --- a/test/RestSharp.IntegrationTests/StatusCodeTests.cs +++ b/test/RestSharp.IntegrationTests/StatusCodeTests.cs @@ -36,6 +36,7 @@ public async Task ContentType_Additional_Information() { var response = await _client.ExecuteAsync<TestResponse>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); + response.IsSuccessful.Should().BeTrue(); } [Fact]
IsSuccessful always false when using RestResponse<T> When using the latest RestSharp version, the property `IsSuccessful` of `RestReponse<T>` is always `false`. When using `RestResponse`, `IsSuccessful` is set to `true` whenever the request was successful. ## Expected Behavior The value of `IsSuccessful` does not depend on whether you use `RestResponse<T>` or `RestResponse`. ## Actual Behavior The value of `IsSuccessful` does depend on whether you use `RestResponse<T>` or `RestResponse`. ## Steps to Reproduce the Problem Code example: ```csharp public class Program { class GithubRepo { public int Id { get; set; } public string Name { get; set; } } public static async Task Main(string[] args) { var restClient = new RestClient("https://api.github.com/"); var request = new RestRequest("repos/RestSharp/RestSharp", Method.Get); var response1 = await restClient.ExecuteAsync<GithubRepo>(request); var response2 = await restClient.ExecuteAsync(request); Console.WriteLine(response1.IsSuccessful); Console.WriteLine(response2.IsSuccessful); } } ``` This outputs: ``` False True ``` Using RestSharp 106, the result is ``` True True ``` ## Specifications - Version: 107.0.0.-preview.13 - Platform: .NET Core 3.1 @ Ubuntu - Subsystem:
null
2021-12-23T12:49:50Z
0.1
['RestSharp.IntegrationTests.StatusCodeTests.ContentType_Additional_Information']
[]
ThreeMammals/Ocelot
threemammals__ocelot-2170
41fc9bd5b183f6e5e6a710f46400f32a58113347
diff --git a/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs b/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs index 5f5f727f3..f85acf510 100644 --- a/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs @@ -1,9 +1,8 @@ using Ocelot.Configuration.File; -namespace Ocelot.Configuration.Creator +namespace Ocelot.Configuration.Creator; + +public interface ISecurityOptionsCreator { - public interface ISecurityOptionsCreator - { - SecurityOptions Create(FileSecurityOptions securityOptions); - } + SecurityOptions Create(FileSecurityOptions securityOptions, FileGlobalConfiguration global); } diff --git a/src/Ocelot/Configuration/Creator/RoutesCreator.cs b/src/Ocelot/Configuration/Creator/RoutesCreator.cs index 015944014..409257700 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -108,7 +108,7 @@ private DownstreamRoute SetUpDownstreamRoute(FileRoute fileRoute, FileGlobalConf var lbOptions = _loadBalancerOptionsCreator.Create(fileRoute.LoadBalancerOptions); - var securityOptions = _securityOptionsCreator.Create(fileRoute.SecurityOptions); + var securityOptions = _securityOptionsCreator.Create(fileRoute.SecurityOptions, globalConfiguration); var downstreamHttpVersion = _versionCreator.Create(fileRoute.DownstreamHttpVersion); diff --git a/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs b/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs index 3c4c93d80..8e53e963a 100644 --- a/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs @@ -1,39 +1,28 @@ using NetTools; // <PackageReference Include="IPAddressRange" Version="6.0.0" /> using Ocelot.Configuration.File; -namespace Ocelot.Configuration.Creator +namespace Ocelot.Configuration.Creator; + +public class SecurityOptionsCreator : ISecurityOptionsCreator { - public class SecurityOptionsCreator : ISecurityOptionsCreator + public SecurityOptions Create(FileSecurityOptions securityOptions, FileGlobalConfiguration global) { - public SecurityOptions Create(FileSecurityOptions securityOptions) - { - var ipAllowedList = new List<string>(); - var ipBlockedList = new List<string>(); - - foreach (var allowed in securityOptions.IPAllowedList) - { - if (IPAddressRange.TryParse(allowed, out var allowedIpAddressRange)) - { - var allowedIps = allowedIpAddressRange.Select<IPAddress, string>(x => x.ToString()); - ipAllowedList.AddRange(allowedIps); - } - } - - foreach (var blocked in securityOptions.IPBlockedList) - { - if (IPAddressRange.TryParse(blocked, out var blockedIpAddressRange)) - { - var blockedIps = blockedIpAddressRange.Select<IPAddress, string>(x => x.ToString()); - ipBlockedList.AddRange(blockedIps); - } - } - - if (securityOptions.ExcludeAllowedFromBlocked) - { - ipBlockedList = ipBlockedList.Except(ipAllowedList).ToList(); - } + var options = securityOptions.IsEmpty() ? global.SecurityOptions : securityOptions; + var allowedIPs = options.IPAllowedList.SelectMany(Parse) + .ToArray(); + var blockedIPs = options.IPBlockedList.SelectMany(Parse) + .Except(options.ExcludeAllowedFromBlocked ? allowedIPs : Enumerable.Empty<string>()) + .ToArray(); + return new(allowedIPs, blockedIPs); + } - return new SecurityOptions(ipAllowedList, ipBlockedList); + private static string[] Parse(string ipValue) + { + if (IPAddressRange.TryParse(ipValue, out var range)) + { + return range.Select<IPAddress, string>(ip => ip.ToString()).ToArray(); } + + return Array.Empty<string>(); } } diff --git a/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs b/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs index 7ce35f99e..1675680d3 100644 --- a/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs +++ b/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs @@ -13,6 +13,7 @@ public FileGlobalConfiguration() HttpHandlerOptions = new FileHttpHandlerOptions(); CacheOptions = new FileCacheOptions(); MetadataOptions = new FileMetadataOptions(); + SecurityOptions = new FileSecurityOptions(); } public string RequestIdKey { get; set; } @@ -48,5 +49,7 @@ public FileGlobalConfiguration() public FileCacheOptions CacheOptions { get; set; } public FileMetadataOptions MetadataOptions { get; set; } + + public FileSecurityOptions SecurityOptions { get; set; } } } diff --git a/src/Ocelot/Configuration/File/FileSecurityOptions.cs b/src/Ocelot/Configuration/File/FileSecurityOptions.cs index ffd595cb4..e3aa1fdd0 100644 --- a/src/Ocelot/Configuration/File/FileSecurityOptions.cs +++ b/src/Ocelot/Configuration/File/FileSecurityOptions.cs @@ -1,54 +1,51 @@ -namespace Ocelot.Configuration.File +namespace Ocelot.Configuration.File; + +public class FileSecurityOptions { - public class FileSecurityOptions + public FileSecurityOptions() { - public FileSecurityOptions() - { - IPAllowedList = new List<string>(); - IPBlockedList = new List<string>(); - ExcludeAllowedFromBlocked = false; - } + IPAllowedList = new(); + IPBlockedList = new(); + ExcludeAllowedFromBlocked = false; + } - public FileSecurityOptions(FileSecurityOptions from) - { - IPAllowedList = new(from.IPAllowedList); - IPBlockedList = new(from.IPBlockedList); - ExcludeAllowedFromBlocked = from.ExcludeAllowedFromBlocked; - } + public FileSecurityOptions(FileSecurityOptions from) + { + IPAllowedList = new(from.IPAllowedList); + IPBlockedList = new(from.IPBlockedList); + ExcludeAllowedFromBlocked = from.ExcludeAllowedFromBlocked; + } - public FileSecurityOptions(string allowedIPs = null, string blockedIPs = null, bool? excludeAllowedFromBlocked = null) - : this() + public FileSecurityOptions(string allowedIPs = null, string blockedIPs = null, bool? excludeAllowedFromBlocked = null) + : this() + { + if (!string.IsNullOrEmpty(allowedIPs)) { - if (!string.IsNullOrEmpty(allowedIPs)) - { - IPAllowedList.Add(allowedIPs); - } - - if (!string.IsNullOrEmpty(blockedIPs)) - { - IPBlockedList.Add(blockedIPs); - } - - ExcludeAllowedFromBlocked = excludeAllowedFromBlocked ?? false; + IPAllowedList.Add(allowedIPs); } - public FileSecurityOptions(IEnumerable<string> allowedIPs = null, IEnumerable<string> blockedIPs = null, bool? excludeAllowedFromBlocked = null) - : this() + if (!string.IsNullOrEmpty(blockedIPs)) { - IPAllowedList.AddRange(allowedIPs ?? Enumerable.Empty<string>()); - IPBlockedList.AddRange(blockedIPs ?? Enumerable.Empty<string>()); - ExcludeAllowedFromBlocked = excludeAllowedFromBlocked ?? false; + IPBlockedList.Add(blockedIPs); } - public List<string> IPAllowedList { get; set; } - public List<string> IPBlockedList { get; set; } + ExcludeAllowedFromBlocked = excludeAllowedFromBlocked ?? false; + } - /// <summary> - /// Provides the ability to specify a wide range of blocked IP addresses and allow a subrange of IP addresses. - /// </summary> - /// <value> - /// Default value: false. - /// </value> - public bool ExcludeAllowedFromBlocked { get; set; } + public FileSecurityOptions(IEnumerable<string> allowedIPs = null, IEnumerable<string> blockedIPs = null, bool? excludeAllowedFromBlocked = null) + : this() + { + IPAllowedList.AddRange(allowedIPs ?? Enumerable.Empty<string>()); + IPBlockedList.AddRange(blockedIPs ?? Enumerable.Empty<string>()); + ExcludeAllowedFromBlocked = excludeAllowedFromBlocked ?? false; } + + public List<string> IPAllowedList { get; set; } + public List<string> IPBlockedList { get; set; } + + /// <summary>Provides the ability to specify a wide range of blocked IP addresses and allow a subrange of IP addresses.</summary> + /// <value>A <see cref="bool"/> value, defaults to <see langword="false"/>.</value> + public bool ExcludeAllowedFromBlocked { get; set; } + + public bool IsEmpty() => IPAllowedList.Count == 0 && IPBlockedList.Count == 0; } diff --git a/src/Ocelot/Configuration/SecurityOptions.cs b/src/Ocelot/Configuration/SecurityOptions.cs index 96186fe65..09dd9a662 100644 --- a/src/Ocelot/Configuration/SecurityOptions.cs +++ b/src/Ocelot/Configuration/SecurityOptions.cs @@ -4,8 +4,8 @@ public class SecurityOptions { public SecurityOptions() { - IPAllowedList = new(); - IPBlockedList = new(); + IPAllowedList = new List<string>(); + IPBlockedList = new List<string>(); } public SecurityOptions(string allowed = null, string blocked = null) @@ -22,13 +22,13 @@ public SecurityOptions(string allowed = null, string blocked = null) } } - public SecurityOptions(List<string> allowedList = null, List<string> blockedList = null) + public SecurityOptions(IList<string> allowedList = null, IList<string> blockedList = null) { - IPAllowedList = allowedList ?? new(); - IPBlockedList = blockedList ?? new(); + IPAllowedList = allowedList ?? new List<string>(); + IPBlockedList = blockedList ?? new List<string>(); } - public List<string> IPAllowedList { get; } - public List<string> IPBlockedList { get; } + public IList<string> IPAllowedList { get; } + public IList<string> IPBlockedList { get; } } } diff --git a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs index e76044ecf..8437af39e 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -3,38 +3,40 @@ using Ocelot.Middleware; using Ocelot.Responses; -namespace Ocelot.Security.IPSecurity +namespace Ocelot.Security.IPSecurity; + +public class IPSecurityPolicy : ISecurityPolicy { - public class IPSecurityPolicy : ISecurityPolicy + public Response Security(DownstreamRoute downstreamRoute, HttpContext context) { - public async Task<Response> Security(DownstreamRoute downstreamRoute, HttpContext httpContext) + var clientIp = context.Connection.RemoteIpAddress; + var options = downstreamRoute.SecurityOptions; + if (options == null || clientIp == null) { - var clientIp = httpContext.Connection.RemoteIpAddress; - var securityOptions = downstreamRoute.SecurityOptions; - if (securityOptions == null) - { - return new OkResponse(); - } + return new OkResponse(); + } - if (securityOptions.IPBlockedList != null) + if (options.IPBlockedList?.Count > 0) + { + if (options.IPBlockedList.Contains(clientIp.ToString())) { - if (securityOptions.IPBlockedList.Exists(f => f == clientIp.ToString())) - { - var error = new UnauthenticatedError($" This request rejects access to {clientIp} IP"); - return new ErrorResponse(error); - } + var error = new UnauthenticatedError($"This request rejects access to {clientIp} IP"); + return new ErrorResponse(error); } + } - if (securityOptions.IPAllowedList?.Count > 0) + if (options.IPAllowedList?.Count > 0) + { + if (!options.IPAllowedList.Contains(clientIp.ToString())) { - if (!securityOptions.IPAllowedList.Exists(f => f == clientIp.ToString())) - { - var error = new UnauthenticatedError($"{clientIp} does not allow access, the request is invalid"); - return new ErrorResponse(error); - } + var error = new UnauthenticatedError($"{clientIp} does not allow access, the request is invalid"); + return new ErrorResponse(error); } - - return await Task.FromResult(new OkResponse()); } + + return new OkResponse(); } + + public Task<Response> SecurityAsync(DownstreamRoute downstreamRoute, HttpContext context) + => Task.Run(() => Security(downstreamRoute, context)); } diff --git a/src/Ocelot/Security/ISecurityPolicy.cs b/src/Ocelot/Security/ISecurityPolicy.cs index 783d1b5ac..b4eb5bf75 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -2,10 +2,10 @@ using Ocelot.Configuration; using Ocelot.Responses; -namespace Ocelot.Security +namespace Ocelot.Security; + +public interface ISecurityPolicy { - public interface ISecurityPolicy - { - Task<Response> Security(DownstreamRoute downstreamRoute, HttpContext httpContext); - } + Response Security(DownstreamRoute downstreamRoute, HttpContext context); + Task<Response> SecurityAsync(DownstreamRoute downstreamRoute, HttpContext context); } diff --git a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs index 068ff2ea0..ebbd80248 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -11,8 +11,7 @@ public class SecurityMiddleware : OcelotMiddleware public SecurityMiddleware(RequestDelegate next, IOcelotLoggerFactory loggerFactory, - IEnumerable<ISecurityPolicy> securityPolicies - ) + IEnumerable<ISecurityPolicy> securityPolicies) : base(loggerFactory.CreateLogger<SecurityMiddleware>()) { _securityPolicies = securityPolicies; @@ -27,7 +26,7 @@ public async Task Invoke(HttpContext httpContext) { foreach (var policy in _securityPolicies) { - var result = await policy.Security(downstreamRoute, httpContext); + var result = policy.Security(downstreamRoute, httpContext); if (!result.IsError) { continue;
diff --git a/test/Ocelot.AcceptanceTests/Security/SecurityOptionsTests.cs b/test/Ocelot.AcceptanceTests/Security/SecurityOptionsTests.cs new file mode 100644 index 000000000..7a33207b7 --- /dev/null +++ b/test/Ocelot.AcceptanceTests/Security/SecurityOptionsTests.cs @@ -0,0 +1,162 @@ +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration.File; + +namespace Ocelot.AcceptanceTests.Security; + +public sealed class SecurityOptionsTests: Steps +{ + private readonly ServiceHandler _serviceHandler; + + public SecurityOptionsTests() + { + _serviceHandler = new ServiceHandler(); + } + + public override void Dispose() + { + _serviceHandler.Dispose(); + base.Dispose(); + } + + [Fact] + [Trait("Feat", "2170")] + public void Should_call_with_allowed_ip_in_global_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.35")[0]; + var route = GivenRoute(port, "/myPath", "/worldPath"); + var configuration = GivenGlobalConfiguration(route, "192.168.1.30-50", "192.168.1.1-100"); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)); + } + + [Fact] + [Trait("Feat", "2170")] + public void Should_block_call_with_blocked_ip_in_global_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.55")[0]; + var route = GivenRoute(port, "/myPath", "/worldPath"); + var configuration = GivenGlobalConfiguration(route, "192.168.1.30-50", "192.168.1.1-100"); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)); + } + + [Fact] + public void Should_call_with_allowed_ip_in_route_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.1")[0]; + var securityConfig = new FileSecurityOptions + { + IPAllowedList = new() { "192.168.1.1" }, + }; + var route = GivenRoute(port, "/myPath", "/worldPath", securityConfig); + var configuration = GivenConfiguration(route); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)); + } + + [Fact] + public void Should_block_call_with_blocked_ip_in_route_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.1")[0]; + var securityConfig = new FileSecurityOptions + { + IPBlockedList = new() { "192.168.1.1" }, + }; + var route = GivenRoute(port, "/myPath", "/worldPath", securityConfig); + var configuration = GivenConfiguration(route); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)); + } + + [Fact] + [Trait("Feat", "2170")] + public void Should_call_with_allowed_ip_in_route_config_and_blocked_ip_in_global_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.55")[0]; + var securityConfig = new FileSecurityOptions + { + IPAllowedList = new() { "192.168.1.55" }, + }; + var route = GivenRoute(port, "/myPath", "/worldPath", securityConfig); + var configuration = GivenGlobalConfiguration(route, "192.168.1.30-50", "192.168.1.1-100"); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .Then(x => ThenTheResponseBodyShouldBe("Hello from Fabrizio")); + } + + [Fact] + [Trait("Feat", "2170")] + public void Should_block_call_with_blocked_ip_in_route_config_and_allowed_ip_in_global_config() + { + var port = PortFinder.GetRandomPort(); + var ip = Dns.GetHostAddresses("192.168.1.35")[0]; + var securityConfig = new FileSecurityOptions + { + IPBlockedList = new() { "192.168.1.35" }, + }; + var route = GivenRoute(port, "/myPath", "/worldPath", securityConfig); + var configuration = GivenGlobalConfiguration(route, "192.168.1.30-50", "192.168.1.1-100"); + + this.Given(x => x.GivenThereIsAServiceRunningOn(port, ip)) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .When(x => WhenIGetUrlOnTheApiGateway("/worldPath")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)); + } + + private void GivenThereIsAServiceRunningOn(int port, IPAddress ipAddess) + { + string url = DownstreamUrl(port); + _serviceHandler.GivenThereIsAServiceRunningOn(url, async context => + { + context.Connection.RemoteIpAddress = ipAddess; + context.Response.StatusCode = (int)HttpStatusCode.OK; + await context.Response.WriteAsync("Hello from Fabrizio"); + }); + } + + private static FileConfiguration GivenGlobalConfiguration(FileRoute route, string allowed, string blocked, bool exclude = true) + { + var config = GivenConfiguration(route); + config.GlobalConfiguration.SecurityOptions = new FileSecurityOptions + { + IPAllowedList = new() { allowed }, + IPBlockedList = new() { blocked }, + ExcludeAllowedFromBlocked = exclude, + }; + return config; + } + + private static FileRoute GivenRoute(int port, string downstream, string upstream, FileSecurityOptions fileSecurityOptions = null) => new() + { + DownstreamPathTemplate = downstream, + UpstreamPathTemplate = upstream, + UpstreamHttpMethod = new() { HttpMethods.Get }, + SecurityOptions = fileSecurityOptions ?? new(), + }; +} diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index dbb9ef25a..2c2b6e9bc 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -303,7 +303,7 @@ private void ThenTheDepsAreCalledFor(FileRoute fileRoute, FileGlobalConfiguratio _hfarCreator.Verify(x => x.Create(fileRoute), Times.Once); _daCreator.Verify(x => x.Create(fileRoute), Times.Once); _lboCreator.Verify(x => x.Create(fileRoute.LoadBalancerOptions), Times.Once); - _soCreator.Verify(x => x.Create(fileRoute.SecurityOptions), Times.Once); + _soCreator.Verify(x => x.Create(fileRoute.SecurityOptions, globalConfig), Times.Once); _metadataCreator.Verify(x => x.Create(fileRoute.Metadata, globalConfig), Times.Once); } } diff --git a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs index 81d9fd36d..2a223c78f 100644 --- a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs @@ -2,62 +2,98 @@ using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; -namespace Ocelot.UnitTests.Configuration +namespace Ocelot.UnitTests.Configuration; + +public sealed class SecurityOptionsCreatorTests : UnitTest { - public class SecurityOptionsCreatorTests : UnitTest - { - private FileRoute _fileRoute; - private SecurityOptions _result; - private readonly ISecurityOptionsCreator _creator; + private readonly SecurityOptionsCreator _creator = new(); - public SecurityOptionsCreatorTests() + [Fact] + public void Should_create_route_security_config() + { + // Arrange + var ipAllowedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var ipBlockedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var securityOptions = new FileSecurityOptions { - _creator = new SecurityOptionsCreator(); - } + IPAllowedList = ipAllowedList, + IPBlockedList = ipBlockedList, + }; + var expected = new SecurityOptions(ipAllowedList, ipBlockedList); + var globalConfig = new FileGlobalConfiguration(); + + // Act + var actual = _creator.Create(securityOptions, globalConfig); + + // Assert + ThenTheResultIs(actual, expected); + } - [Fact] - public void should_create_security_config() + [Fact] + [Trait("Feat", "2170")] + public void Should_create_global_security_config() + { + // Arrange + var ipAllowedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var ipBlockedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var globalConfig = new FileGlobalConfiguration { - var ipAllowedList = new List<string> { "127.0.0.1", "192.168.1.1" }; - var ipBlockedList = new List<string> { "127.0.0.1", "192.168.1.1" }; - var fileRoute = new FileRoute + SecurityOptions = new() { - SecurityOptions = new FileSecurityOptions - { - IPAllowedList = ipAllowedList, - IPBlockedList = ipBlockedList, - }, - }; - - var expected = new SecurityOptions(ipAllowedList, ipBlockedList); - - this.Given(x => x.GivenThe(fileRoute)) - .When(x => x.WhenICreate()) - .Then(x => x.ThenTheResultIs(expected)) - .BDDfy(); - } + IPAllowedList = ipAllowedList, + IPBlockedList = ipBlockedList, + }, + }; + var expected = new SecurityOptions(ipAllowedList, ipBlockedList); + + // Act + var actual = _creator.Create(new(), globalConfig); + + // Assert + ThenTheResultIs(actual, expected); + } - private void GivenThe(FileRoute route) + [Fact] + [Trait("Feat", "2170")] + public void Should_create_global_route_security_config() + { + // Arrange + var routeIpAllowedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var routeIpBlockedList = new List<string> { "127.0.0.1", "192.168.1.1" }; + var securityOptions = new FileSecurityOptions { - _fileRoute = route; - } + IPAllowedList = routeIpAllowedList, + IPBlockedList = routeIpBlockedList, + }; + var globalIpAllowedList = new List<string> { "127.0.0.2", "192.168.1.2" }; + var globalIpBlockedList = new List<string> { "127.0.0.2", "192.168.1.2" }; + var globalConfig = new FileGlobalConfiguration + { + SecurityOptions = new FileSecurityOptions + { + IPAllowedList = globalIpAllowedList, + IPBlockedList = globalIpBlockedList, + }, + }; + var expected = new SecurityOptions(routeIpAllowedList, routeIpBlockedList); + + // Act + var actual = _creator.Create(securityOptions, globalConfig); - private void WhenICreate() + // Assert + ThenTheResultIs(actual, expected); + } + + private static void ThenTheResultIs(SecurityOptions actual, SecurityOptions expected) + { + for (var i = 0; i < expected.IPAllowedList.Count; i++) { - _result = _creator.Create(_fileRoute.SecurityOptions); + actual.IPAllowedList[i].ShouldBe(expected.IPAllowedList[i]); } - private void ThenTheResultIs(SecurityOptions expected) + for (var i = 0; i < expected.IPBlockedList.Count; i++) { - for (var i = 0; i < expected.IPAllowedList.Count; i++) - { - _result.IPAllowedList[i].ShouldBe(expected.IPAllowedList[i]); - } - - for (var i = 0; i < expected.IPBlockedList.Count; i++) - { - _result.IPBlockedList[i].ShouldBe(expected.IPBlockedList[i]); - } + actual.IPBlockedList[i].ShouldBe(expected.IPBlockedList[i]); } } } diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index 83d7bb73f..bd7b9cd3d 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -8,404 +8,391 @@ using Ocelot.Responses; using Ocelot.Security.IPSecurity; -namespace Ocelot.UnitTests.Security +namespace Ocelot.UnitTests.Security; + +public sealed class IPSecurityPolicyTests : UnitTest { - public class IPSecurityPolicyTests : UnitTest + private readonly DownstreamRouteBuilder _downstreamRouteBuilder; + private readonly IPSecurityPolicy _policy; + private readonly HttpContext _context; + private readonly SecurityOptionsCreator _securityOptionsCreator; + private static readonly FileGlobalConfiguration Empty = new(); + + public IPSecurityPolicyTests() { - private readonly DownstreamRouteBuilder _downstreamRouteBuilder; - private readonly IPSecurityPolicy _ipSecurityPolicy; - private Response response; - private readonly HttpContext _httpContext; - private readonly SecurityOptionsCreator _securityOptionsCreator; + _context = new DefaultHttpContext(); + _context.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com"))); + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; + _downstreamRouteBuilder = new DownstreamRouteBuilder(); + _policy = new IPSecurityPolicy(); + _securityOptionsCreator = new SecurityOptionsCreator(); + } - public IPSecurityPolicyTests() - { - _httpContext = new DefaultHttpContext(); - _httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com"))); - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; - _downstreamRouteBuilder = new DownstreamRouteBuilder(); - _ipSecurityPolicy = new IPSecurityPolicy(); - _securityOptionsCreator = new SecurityOptionsCreator(); - } - - [Fact] - public void should_No_blocked_Ip_and_allowed_Ip() - { - this.Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_blockedIp_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; - this.Given(x => x.GivenSetBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_blockedIp_clientIp_Not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.2")[0]; - this.Given(x => x.GivenSetBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_allowedIp_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; - this.Given(x => x.GivenSetAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_allowedIp_clientIp_Not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.2")[0]; - this.Given(x => x.GivenSetAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_cidrNotation_allowed24_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.5")[0]; - this.Given(x => x.GivenCidr24AllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_cidrNotation_allowed24_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; - this.Given(x => x.GivenCidr24AllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_cidrNotation_allowed29_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; - this.Given(x => x.GivenCidr29AllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_cidrNotation_blocked24_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; - this.Given(x => x.GivenCidr24BlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_cidrNotation_blocked24_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.1")[0]; - this.Given(x => x.GivenCidr24BlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_range_allowed_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenRangeAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_range_allowed_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.8")[0]; - this.Given(x => x.GivenRangeAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_range_blocked_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; - this.Given(x => x.GivenRangeBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_range_blocked_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenRangeBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_shortRange_allowed_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenShortRangeAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_shortRange_allowed_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.8")[0]; - this.Given(x => x.GivenShortRangeAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_shortRange_blocked_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; - this.Given(x => x.GivenShortRangeBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_shortRange_blocked_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenShortRangeBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_ipSubnet_allowed_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.15")[0]; - this.Given(x => x.GivenIpSubnetAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_ipSubnet_allowed_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenIpSubnetAllowedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_ipSubnet_blocked_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; - this.Given(x => x.GivenIpSubnetBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_ipSubnet_blocked_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.1")[0]; - this.Given(x => x.GivenIpSubnetBlockedIP()) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_exludeAllowedFromBlocked_moreAllowed_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.150")[0]; - this.Given(x => x.GivenIpMoreAllowedThanBlocked(false)) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_exludeAllowedFromBlocked_moreAllowed_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.150")[0]; - this.Given(x => x.GivenIpMoreAllowedThanBlocked(true)) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_exludeAllowedFromBlocked_moreBlocked_clientIp_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; - this.Given(x => x.GivenIpMoreBlockedThanAllowed(false)) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenNotSecurityPassing()) - .BDDfy(); - } - - [Fact] - public void should_exludeAllowedFromBlocked_moreBlocked_clientIp_not_block() - { - _httpContext.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; - this.Given(x => x.GivenIpMoreBlockedThanAllowed(true)) - .Given(x => x.GivenSetDownstreamRoute()) - .When(x => x.WhenTheSecurityPolicy()) - .Then(x => x.ThenSecurityPassing()) - .BDDfy(); - } - - private void GivenSetAllowedIP() - { - _downstreamRouteBuilder.WithSecurityOptions(new SecurityOptions("192.168.1.1")); - } + [Fact] + public void Should_No_blocked_Ip_and_allowed_Ip() + { + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenSetBlockedIP() - { - _downstreamRouteBuilder.WithSecurityOptions(new SecurityOptions(blocked: "192.168.1.1")); - } + [Fact] + public void Should_blockedIp_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; + GivenSetBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenSetDownstreamRoute() - { - _httpContext.Items.UpsertDownstreamRoute(_downstreamRouteBuilder.Build()); - } + [Fact] + public void Should_blockedIp_clientIp_Not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.2")[0]; + GivenSetBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenCidr24AllowedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/24")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_allowedIp_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; + GivenSetAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenCidr29AllowedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/29")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_allowedIp_clientIp_Not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.2")[0]; + GivenSetAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenCidr24BlockedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0/24")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_cidrNotation_allowed24_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.5")[0]; + GivenCidr24AllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenRangeAllowedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0-192.168.1.10")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_cidrNotation_allowed24_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; + GivenCidr24AllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenRangeBlockedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0-192.168.1.10")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_cidrNotation_allowed29_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; + GivenCidr29AllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenShortRangeAllowedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0-10")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_cidrNotation_blocked24_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.1")[0]; + GivenCidr24BlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenShortRangeBlockedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0-10")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_cidrNotation_blocked24_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.1")[0]; + GivenCidr24BlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenIpSubnetAllowedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/255.255.255.0")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_range_allowed_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenRangeAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenIpSubnetBlockedIP() - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0/255.255.255.0")); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_range_allowed_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.8")[0]; + GivenRangeAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private void GivenIpMoreAllowedThanBlocked(bool excludeAllowedInBlocked) - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.0.0/255.255.0.0", "192.168.1.100-200", excludeAllowedInBlocked)); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_range_blocked_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; + GivenRangeBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void GivenIpMoreBlockedThanAllowed(bool excludeAllowedInBlocked) - { - var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.10-20", "192.168.1.0/23", excludeAllowedInBlocked)); - _downstreamRouteBuilder.WithSecurityOptions(securityOptions); - } + [Fact] + public void Should_range_blocked_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenRangeBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } - private async Task WhenTheSecurityPolicy() - { - response = await _ipSecurityPolicy.Security(_httpContext.Items.DownstreamRoute(), _httpContext); - } + [Fact] + public void Should_shortRange_allowed_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenShortRangeAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void ThenSecurityPassing() - { - Assert.False(response.IsError); - } + [Fact] + public void Should_shortRange_allowed_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.8")[0]; + GivenShortRangeAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + public void Should_shortRange_blocked_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.5")[0]; + GivenShortRangeBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } + + [Fact] + public void Should_shortRange_blocked_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenShortRangeBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + public void Should_ipSubnet_allowed_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.15")[0]; + GivenIpSubnetAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } + + [Fact] + public void Should_ipSubnet_allowed_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenIpSubnetAllowedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + public void Should_ipSubnet_blocked_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.15")[0]; + GivenIpSubnetBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } + + [Fact] + public void Should_ipSubnet_blocked_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.10.1")[0]; + GivenIpSubnetBlockedIP(); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + public void Should_exludeAllowedFromBlocked_moreAllowed_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.150")[0]; + GivenIpMoreAllowedThanBlocked(false); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } - private void ThenNotSecurityPassing() + [Fact] + public void Should_exludeAllowedFromBlocked_moreAllowed_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.150")[0]; + GivenIpMoreAllowedThanBlocked(true); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + public void Should_exludeAllowedFromBlocked_moreBlocked_clientIp_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; + GivenIpMoreBlockedThanAllowed(false); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.True(actual.IsError); + } + + [Fact] + public void Should_exludeAllowedFromBlocked_moreBlocked_clientIp_not_block() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; + GivenIpMoreBlockedThanAllowed(true); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + [Fact] + [Trait("Feat", "2170")] + public void Should_route_config_overrides_global_config() + { + _context.Connection.RemoteIpAddress = Dns.GetHostAddresses("192.168.1.10")[0]; + GivenRouteConfigAndGlobalConfig(false); + GivenSetDownstreamRoute(); + var actual = WhenTheSecurityPolicy(); + Assert.False(actual.IsError); + } + + private void GivenSetAllowedIP() + { + _downstreamRouteBuilder.WithSecurityOptions(new SecurityOptions("192.168.1.1")); + } + + private void GivenSetBlockedIP() + { + _downstreamRouteBuilder.WithSecurityOptions(new SecurityOptions(blocked: "192.168.1.1")); + } + + private void GivenSetDownstreamRoute() + { + _context.Items.UpsertDownstreamRoute(_downstreamRouteBuilder.Build()); + } + + private void GivenCidr24AllowedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/24"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenCidr29AllowedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/29"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenCidr24BlockedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0/24"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenRangeAllowedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0-192.168.1.10"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenRangeBlockedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0-192.168.1.10"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenShortRangeAllowedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0-10"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenShortRangeBlockedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0-10"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenIpSubnetAllowedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.0/255.255.255.0"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenIpSubnetBlockedIP() + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions(blockedIPs: "192.168.1.0/255.255.255.0"), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenIpMoreAllowedThanBlocked(bool excludeAllowedInBlocked) + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.0.0/255.255.0.0", "192.168.1.100-200", excludeAllowedInBlocked), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenIpMoreBlockedThanAllowed(bool excludeAllowedInBlocked) + { + var securityOptions = _securityOptionsCreator.Create(new FileSecurityOptions("192.168.1.10-20", "192.168.1.0/23", excludeAllowedInBlocked), Empty); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private void GivenRouteConfigAndGlobalConfig(bool excludeAllowedInBlocked) + { + var globalConfig = new FileGlobalConfiguration { - Assert.True(response.IsError); - } + SecurityOptions = new FileSecurityOptions("192.168.1.30-50", "192.168.1.1-100", true), + }; + + var localConfig = new FileSecurityOptions("192.168.1.10", "", excludeAllowedInBlocked); + + var securityOptions = _securityOptionsCreator.Create(localConfig, globalConfig); + _downstreamRouteBuilder.WithSecurityOptions(securityOptions); + } + + private Response WhenTheSecurityPolicy() + { + return _policy.Security(_context.Items.DownstreamRoute(), _context); } } diff --git a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs index 9f493391c..60818f015 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -7,83 +7,84 @@ using Ocelot.Security; using Ocelot.Security.Middleware; -namespace Ocelot.UnitTests.Security +namespace Ocelot.UnitTests.Security; + +public sealed class SecurityMiddlewareTests : UnitTest { - public class SecurityMiddlewareTests : UnitTest - { - private readonly List<Mock<ISecurityPolicy>> _securityPolicyList; - private readonly Mock<IOcelotLoggerFactory> _loggerFactory; - private readonly Mock<IOcelotLogger> _logger; - private readonly SecurityMiddleware _middleware; - private readonly RequestDelegate _next; - private readonly HttpContext _httpContext; + private readonly List<Mock<ISecurityPolicy>> _securityPolicyList; + private readonly Mock<IOcelotLoggerFactory> _loggerFactory; + private readonly Mock<IOcelotLogger> _logger; + private readonly SecurityMiddleware _middleware; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; - public SecurityMiddlewareTests() + public SecurityMiddlewareTests() + { + _httpContext = new DefaultHttpContext(); + _loggerFactory = new Mock<IOcelotLoggerFactory>(); + _logger = new Mock<IOcelotLogger>(); + _loggerFactory.Setup(x => x.CreateLogger<SecurityMiddleware>()).Returns(_logger.Object); + _securityPolicyList = new List<Mock<ISecurityPolicy>> { - _httpContext = new DefaultHttpContext(); - _loggerFactory = new Mock<IOcelotLoggerFactory>(); - _logger = new Mock<IOcelotLogger>(); - _loggerFactory.Setup(x => x.CreateLogger<SecurityMiddleware>()).Returns(_logger.Object); - _securityPolicyList = new List<Mock<ISecurityPolicy>> - { - new(), - new(), - }; - _next = context => Task.CompletedTask; - _middleware = new SecurityMiddleware(_next, _loggerFactory.Object, _securityPolicyList.Select(f => f.Object).ToList()); - _httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com"))); - } + new(), + new(), + }; + _next = context => Task.CompletedTask; + _middleware = new SecurityMiddleware(_next, _loggerFactory.Object, _securityPolicyList.Select(f => f.Object).ToList()); + _httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com"))); + } - [Fact] - public void Should_legal_request() - { - this.Given(x => x.GivenPassingSecurityVerification()) - .When(x => x.WhenICallTheMiddleware()) - .Then(x => x.ThenTheRequestIsPassingSecurity()) - .BDDfy(); - } + [Fact] + public async Task Should_legal_request() + { + // Arrange + GivenPassingSecurityVerification(); + + // Act + await _middleware.Invoke(_httpContext); + + // Assert: security passed + _httpContext.Items.Errors().Count.ShouldBe(0); + } + + [Fact] + public async Task Should_verification_failed_request() + { + // Arrange + GivenNotPassingSecurityVerification(); - [Fact] - public void Should_verification_failed_request() + // Act + await _middleware.Invoke(_httpContext); + + // Assert: security not passed + _httpContext.Items.Errors().Count.ShouldBeGreaterThan(0); + } + + private void GivenPassingSecurityVerification() + { + foreach (var item in _securityPolicyList) { - this.Given(x => x.GivenNotPassingSecurityVerification()) - .When(x => x.WhenICallTheMiddleware()) - .Then(x => x.ThenTheRequestIsNotPassingSecurity()) - .BDDfy(); + Response response = new OkResponse(); + item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(response); } + } - private void GivenPassingSecurityVerification() + private void GivenNotPassingSecurityVerification() + { + for (var i = 0; i < _securityPolicyList.Count; i++) { - foreach (var item in _securityPolicyList) + var item = _securityPolicyList[i]; + if (i == 0) { - Response response = new OkResponse(); - item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(Task.FromResult(response)); + Error error = new UnauthenticatedError("Not passing security verification"); + Response response = new ErrorResponse(error); + item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(response); } - } - - private void GivenNotPassingSecurityVerification() - { - for (var i = 0; i < _securityPolicyList.Count; i++) + else { - var item = _securityPolicyList[i]; - if (i == 0) - { - Error error = new UnauthenticatedError("Not passing security verification"); - Response response = new ErrorResponse(error); - item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(Task.FromResult(response)); - } - else - { - Response response = new OkResponse(); - item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(Task.FromResult(response)); - } + Response response = new OkResponse(); + item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(response); } } - - private Task WhenICallTheMiddleware() => _middleware.Invoke(_httpContext); - - private void ThenTheRequestIsPassingSecurity() => _httpContext.Items.Errors().Count.ShouldBe(0); - - private void ThenTheRequestIsNotPassingSecurity() => _httpContext.Items.Errors().Count.ShouldBeGreaterThan(0); } }
Issue with IP Blocking and Allowing in global configuration I configured IP blocking and allowing in Ocelot using SecurityOptions, but it's not working. ``` { "GlobalConfiguration": { "BaseUrl": "http://localhost:5000", "SecurityOptions": { "IPBlockedList": ["192.168.0.23"] } } } ``` The IP blocking configuration is not working as expected.
Hello, Cavid! It seems we lack support for global settings. The potential solutions could be: 1. Solely using `ocelot.json`. Define the options for each route individually. 2. Utilizing C# coding. Replace the `ISecurityOptionsCreator` service in the DI container by redeveloping the `SecurityOptionsCreator` class to consider only the global settings. https://github.com/ThreeMammals/Ocelot/blob/6088515173b70abd52798e544e5ded409680dbdb/src/Ocelot/DependencyInjection/OcelotBuilder.cs#L141 Which solution would be more convenient for you? Hello @Fabman08, The absence of global settings support is a significant issue. Here's the current usage of [SecurityOptionsCreator](https://github.com/ThreeMammals/Ocelot/blob/develop/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs): https://github.com/ThreeMammals/Ocelot/blob/6088515173b70abd52798e544e5ded409680dbdb/src/Ocelot/Configuration/Creator/RoutesCreator.cs#L111 Consequently, the method should accept two arguments, including global settings: https://github.com/ThreeMammals/Ocelot/blob/6088515173b70abd52798e544e5ded409680dbdb/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs#L8 Would you be able to allocate some time to address this? Hi @raman-m! Sure, I'll be able to fix the issue this or next week. ☺️ @CavidH thank you for reporting this issue! 👍 Thank you very much for your help. We will eagerly await the new version. > Hello, Cavid! It seems we lack support for global settings. The potential solutions could be: > > 1. Solely using `ocelot.json`. Define the options for each route individually. > 2. Utilizing C# coding. Replace the `ISecurityOptionsCreator` service in the DI container by redeveloping the `SecurityOptionsCreator` class to consider only the global settings. > https://github.com/ThreeMammals/Ocelot/blob/6088515173b70abd52798e544e5ded409680dbdb/src/Ocelot/DependencyInjection/OcelotBuilder.cs#L141 > > Which solution would be more convenient for you? I had thought of the first option, but since I have too many services, it will be difficult to control this @raman-m just a little question about Global Settings behaviours. I've found three ways to fix the issue: 1. Every properties in Route FileSecurityOptions overrides their Global Settings values eg. - Global: Allowed: B,C Blocked: E ExcludeAllowedFromBlocked: true - Route: Allowed: **A,B,C** Blocked: **D,E,F** ExcludeAllowedFromBlocked: **false** - Final: Allowed: **A,B,C** Blocked: **D,E,F** ExcludeAllowedFromBlocked: **false** 2. Only the existing properties in Route FileSecurityOptions overrides their Global Settings values eg. - Global: Allowed: B,C Blocked: **E** ExcludeAllowedFromBlocked: **true** - Route: Allowed: **A,B,C** Blocked: *null* ExcludeAllowedFromBlocked: *null* - Final: Allowed: ***A,B,C*** Blocked: **E** ExcludeAllowedFromBlocked: **true** 3. The Route FileSecurityOptions values will be merged to Global Settings values eg. - Global: Allowed: **A,B,C** Blocked: **D,E** ExcludeAllowedFromBlocked: true - Route: Allowed: **F,G,H** Blocked: **I,K** ExcludeAllowedFromBlocked: **false** - Final: Allowed: **A,B,C,F,G,H** Blocked: **D,E,I,K** ExcludeAllowedFromBlocked: **false** Which one is the best? @Fabman08 Your research is too complicated! > Which one is the best? It is best to prioritize the route-specific `FileSecurityOptions` object over the global settings. Therefore, if route settings are defined, all global settings should be disregarded. In practice, if the route object is null, then the global settings should be utilized. > Every properties in Route FileSecurityOptions overrides their Global Settings values Yes, if route options are defined, all global ones should be ignored. We will highlight this in the documentation. There should be no merging whatsoever. This approach is the simplest and most correct solution, as merging properties would be erroneous due to potential conflicts within the algorithm. Therefore, merging is identified as a source of bugs.
2024-10-11T06:47:50Z
0.1
['Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_exludeAllowedFromBlocked_moreBlocked_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_blockedIp_clientIp_Not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_shortRange_allowed_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_route_config_overrides_global_config', 'Ocelot.UnitTests.Security.SecurityMiddlewareTests.Should_legal_request', 'Ocelot.UnitTests.Configuration.SecurityOptionsCreatorTests.Should_create_global_security_config', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_block_call_with_blocked_ip_in_route_config_and_allowed_ip_in_global_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_range_allowed_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_cidrNotation_allowed24_clientIp_not_block', 'Ocelot.UnitTests.Configuration.SecurityOptionsCreatorTests.Should_create_global_route_security_config', 'Ocelot.UnitTests.Configuration.SecurityOptionsCreatorTests.Should_create_route_security_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_cidrNotation_blocked24_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_ipSubnet_blocked_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_No_blocked_Ip_and_allowed_Ip', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_shortRange_blocked_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_exludeAllowedFromBlocked_moreBlocked_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_cidrNotation_allowed29_clientIp_block', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_call_with_allowed_ip_in_route_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_ipSubnet_allowed_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_ipSubnet_allowed_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_range_blocked_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_exludeAllowedFromBlocked_moreAllowed_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_allowedIp_clientIp_Not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_exludeAllowedFromBlocked_moreAllowed_clientIp_not_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_range_allowed_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_shortRange_blocked_clientIp_not_block', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_call_with_allowed_ip_in_route_config_and_blocked_ip_in_global_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_cidrNotation_blocked24_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_ipSubnet_blocked_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_blockedIp_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_range_blocked_clientIp_not_block', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_call_with_allowed_ip_in_global_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_cidrNotation_allowed24_clientIp_block', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_block_call_with_blocked_ip_in_global_config', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_allowedIp_clientIp_block', 'Ocelot.UnitTests.Security.IPSecurityPolicyTests.Should_shortRange_allowed_clientIp_block', 'Ocelot.UnitTests.Security.SecurityMiddlewareTests.Should_verification_failed_request', 'Ocelot.AcceptanceTests.Security.SecurityOptionsTests.Should_block_call_with_blocked_ip_in_route_config']
[]
dotnet/efcore
dotnet__efcore-33106
42e6cfbd0c5b431a89b1923e7b73296705cf7ddf
diff --git a/EFCore.sln.DotSettings b/EFCore.sln.DotSettings index 1b4974fd608..d1ddc281f56 100644 --- a/EFCore.sln.DotSettings +++ b/EFCore.sln.DotSettings @@ -291,14 +291,21 @@ The .NET Foundation licenses this file to you under the MIT license.&#xD; <s:Boolean x:Key="/Default/UserDictionary/Words/=Comparers/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=composability/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=composable/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=constantization/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=constantize/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=constantized/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Constructible/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=DATEADD/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=datetimeoffset/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=doesnt/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=efcore/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=evaluatability/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=evaluatable/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=Evaluatables/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=evaluatables/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=fallbacks/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=funcletization/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=Funcletizer/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Includable/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=initializers/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=keyless/@EntryIndexedValue">True</s:Boolean> @@ -316,6 +323,7 @@ The .NET Foundation licenses this file to you under the MIT license.&#xD; <s:Boolean x:Key="/Default/UserDictionary/Words/=pluralizer/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Poolable/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Postgre/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=precompilation/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=prunable/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=pushdown/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=queryables/@EntryIndexedValue">True</s:Boolean> diff --git a/src/EFCore/Properties/CoreStrings.Designer.cs b/src/EFCore/Properties/CoreStrings.Designer.cs index 1eb205020bb..4678648bc8d 100644 --- a/src/EFCore/Properties/CoreStrings.Designer.cs +++ b/src/EFCore/Properties/CoreStrings.Designer.cs @@ -982,8 +982,8 @@ public static string EFConstantInvoked /// <summary> /// The EF.Constant&lt;T&gt; method may only be used with an argument that can be evaluated client-side and does not contain any reference to database-side entities. /// </summary> - public static string EFConstantWithNonEvaluableArgument - => GetString("EFConstantWithNonEvaluableArgument"); + public static string EFConstantWithNonEvaluatableArgument + => GetString("EFConstantWithNonEvaluatableArgument"); /// <summary> /// The EF.Parameter&lt;T&gt; method may only be used within Entity Framework LINQ queries. @@ -991,6 +991,12 @@ public static string EFConstantWithNonEvaluableArgument public static string EFParameterInvoked => GetString("EFParameterInvoked"); + /// <summary> + /// The EF.Parameter&lt;T&gt; method may only be used with an argument that can be evaluated client-side and does not contain any reference to database-side entities. + /// </summary> + public static string EFParameterWithNonEvaluatableArgument + => GetString("EFParameterWithNonEvaluatableArgument"); + /// <summary> /// Complex type '{complexType}' has no properties defines. Configure at least one property or don't include this type in the model. /// </summary> @@ -1766,6 +1772,18 @@ public static string ManyToManyOneNav(object? entityType, object? navigation) GetString("ManyToManyOneNav", nameof(entityType), nameof(navigation)), entityType, navigation); + /// <summary> + /// EF Core does not support MemberListBinding: 'new Blog { Posts = { new Post(), new Post() } }'. + /// </summary> + public static string MemberListBindingNotSupported + => GetString("MemberListBindingNotSupported"); + + /// <summary> + /// EF Core does not support MemberMemberBinding: 'new Blog { Data = { Name = "hello world" } }'. + /// </summary> + public static string MemberMemberBindingNotSupported + => GetString("MemberMemberBindingNotSupported"); + /// <summary> /// The specified field '{field}' could not be found for property '{2_entityType}.{1_property}'. /// </summary> diff --git a/src/EFCore/Properties/CoreStrings.resx b/src/EFCore/Properties/CoreStrings.resx index 9d7fe91b5f7..7ad9abf40d8 100644 --- a/src/EFCore/Properties/CoreStrings.resx +++ b/src/EFCore/Properties/CoreStrings.resx @@ -480,12 +480,15 @@ <data name="EFConstantInvoked" xml:space="preserve"> <value>The EF.Constant&lt;T&gt; method may only be used within Entity Framework LINQ queries.</value> </data> - <data name="EFConstantWithNonEvaluableArgument" xml:space="preserve"> + <data name="EFConstantWithNonEvaluatableArgument" xml:space="preserve"> <value>The EF.Constant&lt;T&gt; method may only be used with an argument that can be evaluated client-side and does not contain any reference to database-side entities.</value> </data> <data name="EFParameterInvoked" xml:space="preserve"> <value>The EF.Parameter&lt;T&gt; method may only be used within Entity Framework LINQ queries.</value> </data> + <data name="EFParameterWithNonEvaluatableArgument" xml:space="preserve"> + <value>The EF.Parameter&lt;T&gt; method may only be used with an argument that can be evaluated client-side and does not contain any reference to database-side entities.</value> + </data> <data name="EmptyComplexType" xml:space="preserve"> <value>Complex type '{complexType}' has no properties defines. Configure at least one property or don't include this type in the model.</value> </data> @@ -1108,6 +1111,12 @@ <data name="ManyToManyOneNav" xml:space="preserve"> <value>The navigation '{entityType}.{navigation}' cannot be used for both sides of a many-to-many relationship. Many-to-many relationships must use two distinct navigation properties.</value> </data> + <data name="MemberListBindingNotSupported" xml:space="preserve"> + <value>EF Core does not support MemberListBinding: 'new Blog { Posts = { new Post(), new Post() } }'.</value> + </data> + <data name="MemberMemberBindingNotSupported" xml:space="preserve"> + <value>EF Core does not support MemberMemberBinding: 'new Blog { Data = { Name = "hello world" } }'.</value> + </data> <data name="MissingBackingField" xml:space="preserve"> <value>The specified field '{field}' could not be found for property '{2_entityType}.{1_property}'.</value> </data> diff --git a/src/EFCore/Query/Internal/ExpressionTreeFuncletizer.cs b/src/EFCore/Query/Internal/ExpressionTreeFuncletizer.cs new file mode 100644 index 00000000000..8469fccf688 --- /dev/null +++ b/src/EFCore/Query/Internal/ExpressionTreeFuncletizer.cs @@ -0,0 +1,2114 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Buffers; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using static System.Linq.Expressions.Expression; + +namespace Microsoft.EntityFrameworkCore.Query.Internal; + +/// <summary> +/// This visitor identifies subtrees in the query which can be evaluated client-side (i.e. no reference to server-side resources), +/// and evaluates those subtrees, integrating the result either as a constant (if the subtree contained no captured closure variables), +/// or as parameters. +/// </summary> +/// <remarks> +/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to +/// the same compatibility standards as public APIs. It may be changed or removed without notice in +/// any release. You should only use it directly in your code with extreme caution and knowing that +/// doing so can result in application failures when updating to a new Entity Framework Core release. +/// </remarks> +public class ExpressionTreeFuncletizer : ExpressionVisitor +{ + // The general algorithm here is the following. + // 1. First, for each node type, visit that node's children and get their states (evaluatable, contains evaluatable, no evaluatable). + // 2. Calculate the parent node's aggregate state from its children; a container node whose children are all evaluatable is itself + // evaluatable, etc. + // 3. If the parent node is evaluatable (because all its children are), simply bubble that up - nothing more to do + // 4. If the parent node isn't evaluatable but contains an evaluatable child, that child is an evaluatable root for its fragment. + // Evaluate it, making it either into a parameter (if it contains any captured variables), or into a constant (if not). + // 5. If we're in path extraction mode (precompiled queries), build a path back up from the evaluatable roots to the query root; this + // is what later gets used to generate code to evaluate and extract those fragments as parameters. If we're in regular parameter + // parameter extraction (not precompilation), don't do this (not needed) and just return "not evaluatable". + + /// <summary> + /// Indicates whether we're calculating the paths to all parameterized evaluatable roots (precompilation mode), or doing regular, + /// non-precompiled parameter extraction. + /// </summary> + private bool _calculatingPath; + + /// <summary> + /// Indicates whether we should parameterize. Is false in in compiled query mode, as well as when we're handling query filters + /// from NavigationExpandingExpressionVisitor. + /// </summary> + private bool _parameterize; + + /// <summary> + /// Indicates whether we're currently within a lambda. When not in a lambda, we evaluate evaluatables as constants even if they + /// don't contains a captured variable (Skip/Take case). + /// </summary> + private bool _inLambda; + + /// <summary> + /// A provider-facing extensibility hook to allow preventing certain expression nodes from being evaluated (typically specific + /// methods). + /// </summary> + private readonly IEvaluatableExpressionFilter _evaluatableExpressionFilter; + + /// <summary> + /// <see cref="ParameterExpression" /> is generally considered as non-evaluatable, since it represents a lambda parameter and we + /// don't evaluate lambdas. The one exception is a Select operator over something evaluatable (e.g. a parameterized list) - this + /// does need to get evaluated. This list contains <see cref="ParameterExpression" /> instances for that case, to allow + /// evaluatability. + /// </summary> + private readonly HashSet<ParameterExpression> _evaluatableParameters = new(); + + /// <summary> + /// A cache of tree fragments that have already been parameterized, along with their parameter. This allows us to reuse the same + /// query parameter twice when the same captured variable is referenced in the query. + /// </summary> + private readonly Dictionary<Expression, ParameterExpression> _parameterizedValues = new(ExpressionEqualityComparer.Instance); + + /// <summary> + /// Used only when evaluating arbitrary QueryRootExpressions (specifically SqlQueryRootExpression), to force any evaluatable nested + /// expressions to get evaluated as roots, since the query root itself is never evaluatable. + /// </summary> + private bool _evaluateRoot; + + /// <summary> + /// Enabled only when funcletization is invoked on query filters from within NavigationExpandingExpressionVisitor. Causes special + /// handling for DbContext when it's referenced from within the query filter (e.g. for the tenant ID). + /// </summary> + private readonly bool _generateContextAccessors; + + private IQueryProvider? _currentQueryProvider; + private State _state; + private IParameterValues _parameterValues = null!; + + private readonly IModel _model; + private readonly ContextParameterReplacer _contextParameterReplacer; + private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger; + + private static readonly MethodInfo ReadOnlyCollectionIndexerGetter = typeof(ReadOnlyCollection<Expression>).GetProperties() + .Single(p => p.GetIndexParameters() is { Length: 1 } indexParameters && indexParameters[0].ParameterType == typeof(int)).GetMethod!; + + private static readonly MethodInfo ReadOnlyMemberBindingCollectionIndexerGetter = typeof(ReadOnlyCollection<MemberBinding>) + .GetProperties() + .Single(p => p.GetIndexParameters() is { Length: 1 } indexParameters && indexParameters[0].ParameterType == typeof(int)).GetMethod!; + + private static readonly PropertyInfo MemberAssignmentExpressionProperty = + typeof(MemberAssignment).GetProperty(nameof(MemberAssignment.Expression))!; + + private static readonly ArrayPool<State> StateArrayPool = ArrayPool<State>.Shared; + + private const string QueryFilterPrefix = "ef_filter"; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public ExpressionTreeFuncletizer( + IModel model, + IEvaluatableExpressionFilter evaluatableExpressionFilter, + Type contextType, + bool generateContextAccessors, + IDiagnosticsLogger<DbLoggerCategory.Query> logger) + { + _model = model; + _evaluatableExpressionFilter = evaluatableExpressionFilter; + _generateContextAccessors = generateContextAccessors; + _contextParameterReplacer = _generateContextAccessors + ? new ContextParameterReplacer(contextType) + : null!; + _logger = logger; + } + + /// <summary> + /// Processes an expression tree, extracting parameters and evaluating evaluatable fragments as part of the pass. + /// Used for regular query execution (neither compiled nor pre-compiled). + /// </summary> + /// <remarks> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </remarks> + public virtual Expression ExtractParameters( + Expression expression, + IParameterValues parameterValues, + bool parameterize, + bool clearParameterizedValues) + { + Reset(clearParameterizedValues); + _parameterValues = parameterValues; + _parameterize = parameterize; + _calculatingPath = false; + + var root = Visit(expression, out var state); + + Check.DebugAssert(!state.ContainsEvaluatable, "In parameter extraction mode, end state should not contain evaluatable"); + + // If the top-most node in the tree is evaluatable, evaluate it. + if (state.IsEvaluatable) + { + root = ProcessEvaluatableRoot(root, ref state); + } + + return root; + } + + /// <summary> + /// Processes an expression tree, locates references to captured variables and returns information on how to extract them from + /// expression trees with the same shape. Used to generate C# code for query precompilation. + /// </summary> + /// <returns>A tree representing the path to each evaluatable root node in the tree.</returns> + /// <remarks> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </remarks> + public virtual PathNode? CalculatePathsToEvaluatableRoots(Expression expression) + { + Reset(); + _calculatingPath = true; + _parameterize = true; + + // In precompilation mode we don't actually extract parameter values; but we do need to generate the parameter names, using the + // same logic (and via the same code) used in parameter extraction, and that logic requires _parameterValues. + _parameterValues = new DummyParameterValues(); + + _ = Visit(expression, out var state); + + return state.Path; + } + + private void Reset(bool clearParameterizedValues = true) + { + _inLambda = false; + _currentQueryProvider = null; + _evaluateRoot = false; + _evaluatableParameters.Clear(); + + if (clearParameterizedValues) + { + _parameterizedValues.Clear(); + } + } + + [return: NotNullIfNotNull("expression")] + private Expression? Visit(Expression? expression, out State state) + { + _state = default; + var result = base.Visit(expression); + state = _state; + return result; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + [return: NotNullIfNotNull("expression")] + public override Expression? Visit(Expression? expression) + { + _state = default; + + if (_evaluateRoot) + { + // This path is only called from VisitExtension for query roots, as a way of evaluating expressions inside query roots + // (i.e. SqlQueryRootExpression.Arguments). + _evaluateRoot = false; + var result = base.Visit(expression); + _evaluateRoot = true; + + if (_state.IsEvaluatable) + { + result = ProcessEvaluatableRoot(result, ref _state); + // TODO: Test this scenario in path calculation mode (probably need to handle children path?) + } + + return result; + } + + return base.Visit(expression); + } + + #region Visitation implementations + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitBinary(BinaryExpression binary) + { + var left = Visit(binary.Left, out var leftState); + + // Perform short-circuiting checks to avoid evaluating the right side if not necessary + object? leftValue = null; + if (leftState.IsEvaluatable) + { + switch (binary.NodeType) + { + case ExpressionType.Coalesce: + leftValue = Evaluate(left); + + switch (leftValue) + { + case null: + return Visit(binary.Right, out _state); + case bool b: + _state = leftState with { StateType = StateType.EvaluatableWithoutCapturedVariable }; + return Constant(b); + default: + return left; + } + + case ExpressionType.OrElse or ExpressionType.AndAlso when Evaluate(left) is bool leftBoolValue: + { + left = Constant(leftBoolValue); + leftState = leftState with { StateType = StateType.EvaluatableWithoutCapturedVariable }; + + if (leftBoolValue && binary.NodeType is ExpressionType.OrElse + || !leftBoolValue && binary.NodeType is ExpressionType.AndAlso) + { + _state = leftState; + return left; + } + + binary = binary.Update(left, binary.Conversion, binary.Right); + break; + } + } + } + + var right = Visit(binary.Right, out var rightState); + + if (binary.NodeType is ExpressionType.AndAlso or ExpressionType.OrElse) + { + if (leftState.IsEvaluatable && leftValue is bool leftBoolValue) + { + switch ((leftConstant: leftBoolValue, binary.NodeType)) + { + case (true, ExpressionType.AndAlso) or (false, ExpressionType.OrElse): + _state = rightState; + return right; + case (true, ExpressionType.OrElse) or (false, ExpressionType.AndAlso): + throw new UnreachableException(); // Already handled above before visiting the right side + } + } + + if (rightState.IsEvaluatable && Evaluate(right) is bool rightBoolValue) + { + switch ((binary.NodeType, rightConstant: rightBoolValue)) + { + case (ExpressionType.AndAlso, true) or (ExpressionType.OrElse, false): + _state = leftState; + return left; + case (ExpressionType.OrElse, true) or (ExpressionType.AndAlso, false): + _state = rightState with { StateType = StateType.EvaluatableWithoutCapturedVariable }; + return Constant(rightBoolValue); + } + } + } + + // We're done with simplification/short-circuiting checks specific to BinaryExpression. + var state = CombineStateTypes(leftState.StateType, rightState.StateType); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(binary)) + { + _state = State.CreateEvaluatable(typeof(BinaryExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + if (leftState.IsEvaluatable) + { + left = ProcessEvaluatableRoot(left, ref leftState); + } + + if (rightState.IsEvaluatable) + { + right = ProcessEvaluatableRoot(right, ref rightState); + } + + List<PathNode>? children = null; + + if (_calculatingPath) + { + if (leftState.ContainsEvaluatable) + { + children = + [ + leftState.Path! with { PathFromParent = static e => Property(e, nameof(BinaryExpression.Left)) } + ]; + } + + if (rightState.ContainsEvaluatable) + { + children ??= new(); + children.Add(rightState.Path! with { PathFromParent = static e => Property(e, nameof(BinaryExpression.Right)) }); + } + } + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(BinaryExpression), children); + break; + + default: + throw new UnreachableException(); + } + + return binary.Update(left, binary.Conversion, right); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitConditional(ConditionalExpression conditional) + { + var test = Visit(conditional.Test, out var testState); + + // If the test evaluates, simplify the conditional away by bubbling up the leg that remains + if (testState.IsEvaluatable && Evaluate(conditional.Test) is bool testBoolValue) + { + return testBoolValue + ? Visit(conditional.IfTrue, out _state) + : Visit(conditional.IfFalse, out _state); + } + + var ifTrue = Visit(conditional.IfTrue, out var ifTrueState); + var ifFalse = Visit(conditional.IfFalse, out var ifFalseState); + + var state = CombineStateTypes(testState.StateType, CombineStateTypes(ifTrueState.StateType, ifFalseState.StateType)); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + // If all three children are evaluatable, so is this conditional expression; simply bubble up, we're part of an evaluatable + // fragment that will get evaluated somewhere above. + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(conditional)) + { + _state = State.CreateEvaluatable(typeof(ConditionalExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + if (testState.IsEvaluatable) + { + // Early optimization - if the test is evaluatable, simply reduce the conditional to the relevant clause + if (Evaluate(test) is bool testConstant) + { + _state = testConstant ? ifTrueState : ifFalseState; + return testConstant ? ifTrue : ifFalse; + } + + test = ProcessEvaluatableRoot(test, ref testState); + } + + if (ifTrueState.IsEvaluatable) + { + ifTrue = ProcessEvaluatableRoot(ifTrue, ref ifTrueState); + } + + if (ifFalseState.IsEvaluatable) + { + ifFalse = ProcessEvaluatableRoot(ifFalse, ref ifFalseState); + } + + List<PathNode>? children = null; + + if (_calculatingPath) + { + if (testState.ContainsEvaluatable) + { + children ??= new(); + children.Add( + testState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.Test)) }); + } + + if (ifTrueState.ContainsEvaluatable) + { + children ??= new(); + children.Add( + ifTrueState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.IfTrue)) }); + } + + if (ifFalseState.ContainsEvaluatable) + { + children ??= new(); + children.Add( + ifFalseState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.IfFalse)) }); + } + } + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(ConditionalExpression), children); + break; + + default: + throw new UnreachableException(); + } + + return conditional.Update(test, ifTrue, ifFalse); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitConstant(ConstantExpression constant) + { + // Whether this constant represents a captured variable determines whether we'll evaluate it as a parameter (if yes) or as a + // constant (if no). + var isCapturedVariable = + // This identifies compiler-generated closure types which contain captured variables. + (constant.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate) + && Attribute.IsDefined(constant.Type, typeof(CompilerGeneratedAttribute), inherit: true)) + // The following is for supporting the Find method (we should look into this and possibly clean it up). + || constant.Type == typeof(ValueBuffer); + + _state = constant.Value is IQueryable + ? State.NoEvaluatability + : State.CreateEvaluatable(typeof(ConstantExpression), isCapturedVariable); + + return constant; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitDefault(DefaultExpression node) + { + _state = State.CreateEvaluatable(typeof(DefaultExpression), containsCapturedVariable: false); + return node; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitExtension(Expression extension) + { + if (extension is QueryRootExpression queryRoot) + { + var queryProvider = queryRoot.QueryProvider; + if (_currentQueryProvider == null) + { + _currentQueryProvider = queryProvider; + } + else if (!ReferenceEquals(queryProvider, _currentQueryProvider)) + { + throw new InvalidOperationException(CoreStrings.ErrorInvalidQueryable); + } + + // Visit after detaching query provider since custom query roots can have additional components + extension = queryRoot.DetachQueryProvider(); + + // The following is somewhat hacky. We're going to visit the query root's children via VisitChildren - this is primarily for + // FromSqlQueryRootExpression. Since the query root itself is never evaluatable, its children should all be handled as + // evaluatable roots - we set _evaluateRoot and do that in Visit. + // In addition, FromSqlQueryRootExpression's Arguments need to be a parameter rather than constant, so we set _inLambda to + // make that happen (quite hacky, but was done this way in the old ParameterExtractingEV as well). Think about a better way. + _evaluateRoot = true; + var parentInLambda = _inLambda; + _inLambda = false; + var visitedExtension = base.VisitExtension(extension); + _evaluateRoot = false; + _inLambda = parentInLambda; + _state = State.NoEvaluatability; + return visitedExtension; + } + + return base.VisitExtension(extension); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitInvocation(InvocationExpression invocation) + { + var expression = Visit(invocation.Expression, out var expressionState); + var state = expressionState.StateType; + var arguments = Visit(invocation.Arguments, ref state, out var argumentStates); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(invocation)) + { + _state = State.CreateEvaluatable(typeof(InvocationExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + List<PathNode>? children = null; + + if (expressionState.IsEvaluatable) + { + expression = ProcessEvaluatableRoot(expression, ref expressionState); + } + + if (expressionState.ContainsEvaluatable && _calculatingPath) + { + children = + [ + expressionState.Path! with { PathFromParent = static e => Property(e, nameof(InvocationExpression.Expression)) } + ]; + } + + arguments = EvaluateList( + ((IReadOnlyList<Expression>?)arguments) ?? invocation.Arguments, + argumentStates, + ref children, + static i => e => + Call( + Property(e, nameof(InvocationExpression.Arguments)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(InvocationExpression), children); + break; + + default: + throw new UnreachableException(); + } + + StateArrayPool.Return(argumentStates); + return invocation.Update(expression, ((IReadOnlyList<Expression>?)arguments) ?? invocation.Arguments); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitIndex(IndexExpression index) + { + var @object = Visit(index.Object, out var objectState); + var state = objectState.StateType; + var arguments = Visit(index.Arguments, ref state, out var argumentStates); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(index)) + { + _state = State.CreateEvaluatable(typeof(IndexExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + List<PathNode>? children = null; + + if (objectState.IsEvaluatable) + { + @object = ProcessEvaluatableRoot(@object, ref objectState); + } + + if (objectState.ContainsEvaluatable && _calculatingPath) + { + children = [objectState.Path! with { PathFromParent = static e => Property(e, nameof(IndexExpression.Object)) }]; + } + + arguments = EvaluateList( + ((IReadOnlyList<Expression>?)arguments) ?? index.Arguments, + argumentStates, + ref children, + static i => e => + Call( + Property(e, nameof(IndexExpression.Arguments)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(IndexExpression), children); + break; + + default: + throw new UnreachableException(); + } + + StateArrayPool.Return(argumentStates); + + // TODO: https://github.com/dotnet/runtime/issues/96626 + return index.Update(@object!, ((IReadOnlyList<Expression>?)arguments) ?? index.Arguments); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitLambda<T>(Expression<T> lambda) + { + var oldInLambda = _inLambda; + _inLambda = true; + + var body = Visit(lambda.Body, out _state); + lambda = lambda.Update(body, lambda.Parameters); + + if (_state.StateType is StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable) + { + // The lambda body is evaluatable. If all lambda parameters are also in the _allowedParameters set (this happens for + // Select() over an evaluatable source, see VisitMethodCall()), then the whole lambda is evaluatable. Otherwise, evaluate + // the body. + if (lambda.Parameters.All(parameter => _evaluatableParameters.Contains(parameter))) + { + _state = State.CreateEvaluatable(typeof(LambdaExpression), _state.ContainsCapturedVariable); + return lambda; + } + + lambda = lambda.Update(ProcessEvaluatableRoot(lambda.Body, ref _state), lambda.Parameters); + } + + if (_state.ContainsEvaluatable) + { + _state = State.CreateContainsEvaluatable( + typeof(LambdaExpression), + [_state.Path! with { PathFromParent = static e => Property(e, nameof(Expression<T>.Body)) }]); + } + + _inLambda = oldInLambda; + + return lambda; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitMember(MemberExpression member) + { + // Static member access - notably required for EF.Functions, but also for various translations (DateTime.Now). + if (member.Expression is null) + { + _state = IsGenerallyEvaluatable(member) + ? State.CreateEvaluatable(typeof(MemberExpression), containsCapturedVariable: false) + : State.NoEvaluatability; + return member; + } + + var expression = Visit(member.Expression, out _state); + + if (_state.IsEvaluatable) + { + // If the query contains a captured variable that's a nested IQueryable, inline it into the main query. + // Otherwise, evaluation of a terminating operator up the call chain will cause us to execute the query and do another + // roundtrip. + // Note that we only do this when the MemberExpression is typed as IQueryable/IOrderedQueryable; this notably excludes + // DbSet captured variables integrated directly into the query, as that also evaluates e.g. context.Order in + // context.Order.FromSqlInterpolated(), which fails. + if (member.Type.IsConstructedGenericType + && member.Type.GetGenericTypeDefinition() is var genericTypeDefinition + && (genericTypeDefinition == typeof(IQueryable<>) || genericTypeDefinition == typeof(IOrderedQueryable<>)) + && Evaluate(member) is IQueryable queryable) + { + return Visit(queryable.Expression); + } + + if (IsGenerallyEvaluatable(member)) + { + _state = State.CreateEvaluatable(typeof(MemberExpression), _state.ContainsCapturedVariable); + return member.Update(expression); + } + + expression = ProcessEvaluatableRoot(expression, ref _state); + } + + if (_state.ContainsEvaluatable && _calculatingPath) + { + _state = State.CreateContainsEvaluatable( + typeof(MemberExpression), + [_state.Path! with { PathFromParent = static e => Property(e, nameof(MemberExpression.Expression)) }]); + } + + return member.Update(expression); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitMethodCall(MethodCallExpression methodCall) + { + var method = methodCall.Method; + + // Handle some special, well-known functions + // If this is a call to EF.Constant(), or EF.Parameter(), then examine the operand; it it's isn't evaluatable (i.e. contains a + // reference to a database table), throw immediately. Otherwise, evaluate the operand (either as a constant or as a parameter) and + // return that. + if (method.DeclaringType == typeof(EF)) + { + switch (method.Name) + { + case nameof(EF.Constant): + { + if (_calculatingPath) + { + throw new InvalidOperationException("EF.Constant is not supported when using precompiled queries"); + } + + var argument = Visit(methodCall.Arguments[0], out var argumentState); + + if (!argumentState.IsEvaluatable) + { + throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluatableArgument); + } + + argumentState = argumentState with + { + StateType = StateType.EvaluatableWithoutCapturedVariable, ForceConstantization = true + }; + var evaluatedArgument = ProcessEvaluatableRoot(argument, ref argumentState); + _state = argumentState; + return evaluatedArgument; + } + + case nameof(EF.Parameter): + { + var argument = Visit(methodCall.Arguments[0], out var argumentState); + + if (!argumentState.IsEvaluatable) + { + throw new InvalidOperationException(CoreStrings.EFParameterWithNonEvaluatableArgument); + } + + argumentState = argumentState with { StateType = StateType.EvaluatableWithCapturedVariable }; + var evaluatedArgument = ProcessEvaluatableRoot(argument, ref argumentState); + _state = argumentState; + return evaluatedArgument; + } + } + } + + // Regular/arbitrary method handling from here on + + // First, visit the object and all arguments, saving states as well + var @object = Visit(methodCall.Object, out var objectState); + var state = objectState.StateType; + var arguments = Visit(methodCall.Arguments, ref state, out var argumentStates); + + // The following identifies Select(), and its lambda parameters in a special list which allows us to evaluate them. + if (method.DeclaringType == typeof(Enumerable) + && method.Name == nameof(Enumerable.Select) + && argumentStates[0].IsEvaluatable + && methodCall.Arguments[1] is LambdaExpression lambda) + { + foreach (var parameter in lambda.Parameters) + { + _evaluatableParameters.Add(parameter); + } + + // Revisit with the updated _evaluatableParameters. + state = objectState.StateType; + arguments = Visit(methodCall.Arguments, ref state, out argumentStates); + } + + // We've visited everything and know all the states. + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(methodCall)) + { + _state = State.CreateEvaluatable(typeof(MethodCallExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + List<PathNode>? children = null; + + if (objectState.IsEvaluatable) + { + @object = ProcessEvaluatableRoot(@object, ref objectState); + } + + if (objectState.ContainsEvaluatable && _calculatingPath) + { + children = [objectState.Path! with { PathFromParent = static e => Property(e, nameof(MethodCallExpression.Object)) }]; + } + + // To support [NotParameterized] and indexer method arguments - which force evaluation as constant - go over the parameters + // and modify the states as needed + ParameterInfo[]? parameterInfos = null; + for (var i = 0; i < methodCall.Arguments.Count; i++) + { + var argumentState = argumentStates[i]; + + if (argumentState.IsEvaluatable) + { + parameterInfos ??= methodCall.Method.GetParameters(); + if (parameterInfos[i].GetCustomAttribute<NotParameterizedAttribute>() is not null + || _model.IsIndexerMethod(methodCall.Method)) + { + argumentStates[i] = argumentState with + { + StateType = StateType.EvaluatableWithoutCapturedVariable, ForceConstantization = true + }; + } + } + } + + arguments = EvaluateList( + ((IReadOnlyList<Expression>?)arguments) ?? methodCall.Arguments, + argumentStates, + ref children, + static i => e => + Call( + Property(e, nameof(MethodCallExpression.Arguments)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(MethodCallExpression), children); + break; + + default: + throw new UnreachableException(); + } + + return methodCall.Update(@object, ((IReadOnlyList<Expression>?)arguments) ?? methodCall.Arguments); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitNewArray(NewArrayExpression newArray) + { + StateType state = default; + var expressions = Visit(newArray.Expressions, ref state, out var expressionStates, poolExpressionStates: false); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + { + if (IsGenerallyEvaluatable(newArray)) + { + // Avoid allocating for the notEvaluatableAsRootHandler closure below unless we actually end up in the evaluatable case + var (newArray2, expressions2, expressionStates2) = (newArray, expressions, expressionStates); + _state = State.CreateEvaluatable( + typeof(NewExpression), + state is StateType.EvaluatableWithCapturedVariable, + // See note below on EvaluateChildren + notEvaluatableAsRootHandler: () => EvaluateChildren(newArray2, expressions2, expressionStates2)); + break; + } + + goto case StateType.ContainsEvaluatable; + } + + case StateType.ContainsEvaluatable: + return EvaluateChildren(newArray, expressions, expressionStates); + + default: + throw new UnreachableException(); + } + + return newArray.Update(((IReadOnlyList<Expression>?)expressions) ?? newArray.Expressions); + + // We don't parameterize NewArrayExpression when its an evaluatable root, since we want to allow translating new[] { x, y } to + // e.g. IN (x, y) rather than parameterizing the whole thing. But bubble up the evaluatable state so it may get evaluated at a + // higher level. + // To support that, when the NewArrayExpression is evaluatable, we include a nonEvaluatableAsRootHandler lambda in the returned + // state, which gets invoked up the stack, calling this method. This evaluates the NewArrayExpression's children, but not the + // NewArrayExpression. + NewArrayExpression EvaluateChildren(NewArrayExpression newArray, Expression[]? expressions, State[] expressionStates) + { + List<PathNode>? children = null; + + expressions = EvaluateList( + ((IReadOnlyList<Expression>?)expressions) ?? newArray.Expressions, + expressionStates, + ref children, + i => e => Call( + Property(e, nameof(NewArrayExpression.Expressions)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(NewArrayExpression), children); + + return newArray.Update(((IReadOnlyList<Expression>?)expressions) ?? newArray.Expressions); + } + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitNew(NewExpression @new) + { + StateType state = default; + var arguments = Visit(@new.Arguments, ref state, out var argumentStates, poolExpressionStates: false); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + { + if (IsGenerallyEvaluatable(@new)) + { + // Avoid allocating for the notEvaluatableAsRootHandler closure below unless we actually end up in the evaluatable case + var (new2, arguments2, argumentStates2) = (@new, arguments, argumentStates); + _state = State.CreateEvaluatable( + typeof(NewExpression), + state is StateType.EvaluatableWithCapturedVariable, + // See note below on EvaluateChildren + notEvaluatableAsRootHandler: () => EvaluateChildren(new2, arguments2, argumentStates2)); + break; + } + + goto case StateType.ContainsEvaluatable; + } + + case StateType.ContainsEvaluatable: + return EvaluateChildren(@new, arguments, argumentStates); + + default: + throw new UnreachableException(); + } + + return @new.Update(((IReadOnlyList<Expression>?)arguments) ?? @new.Arguments); + + // Although we allow NewExpression to be evaluated within larger tree fragments, we don't constantize them when they're the + // evaluatable root, since that would embed arbitrary user type instances in our shaper. + // To support that, when the NewExpression is evaluatable, we include a nonEvaluatableAsRootHandler lambda in the returned state, + // which gets invoked up the stack, calling this method. This evaluates the NewExpression's children, but not the NewExpression. + NewExpression EvaluateChildren(NewExpression @new, Expression[]? arguments, State[] argumentStates) + { + List<PathNode>? children = null; + + arguments = EvaluateList( + ((IReadOnlyList<Expression>?)arguments) ?? @new.Arguments, + argumentStates, + ref children, + i => e => Call( + Property(e, nameof(NewExpression.Arguments)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(NewExpression), children); + + return @new.Update(((IReadOnlyList<Expression>?)arguments) ?? @new.Arguments); + } + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitParameter(ParameterExpression parameterExpression) + { + // ParameterExpressions are lambda parameters, which we cannot evaluate. + // However, _allowedParameters is a mechanism to allow evaluating Select(), see VisitMethodCall. + _state = _evaluatableParameters.Contains(parameterExpression) + ? State.CreateEvaluatable(typeof(ParameterExpression), containsCapturedVariable: false) + : State.NoEvaluatability; + + return parameterExpression; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinary) + { + var expression = Visit(typeBinary.Expression, out _state); + + if (_state.IsEvaluatable) + { + if (IsGenerallyEvaluatable(typeBinary)) + { + _state = State.CreateEvaluatable(typeof(TypeBinaryExpression), _state.ContainsCapturedVariable); + return typeBinary.Update(expression); + } + + expression = ProcessEvaluatableRoot(expression, ref _state); + } + + if (_state.ContainsEvaluatable && _calculatingPath) + { + _state = State.CreateContainsEvaluatable( + typeof(TypeBinaryExpression), + [_state.Path! with { PathFromParent = static e => Property(e, nameof(TypeBinaryExpression.Expression)) }]); + } + + return typeBinary.Update(expression); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitMemberInit(MemberInitExpression memberInit) + { + var @new = (NewExpression)Visit(memberInit.NewExpression, out var newState); + var state = newState.StateType; + var bindings = Visit(memberInit.Bindings, VisitMemberBinding, ref state, out var bindingStates, poolExpressionStates: false); + + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + { + if (IsGenerallyEvaluatable(memberInit)) + { + // Avoid allocating for the notEvaluatableAsRootHandler closure below unless we actually end up in the evaluatable case + var (memberInit2, new2, newState2, bindings2, bindingStates2) = (memberInit, @new, newState, bindings, bindingStates); + _state = State.CreateEvaluatable( + typeof(InvocationExpression), + state is StateType.EvaluatableWithCapturedVariable, + notEvaluatableAsRootHandler: () => EvaluateChildren(memberInit2, new2, newState2, bindings2, bindingStates2)); + break; + } + + goto case StateType.ContainsEvaluatable; + } + + case StateType.ContainsEvaluatable: + return EvaluateChildren(memberInit, @new, newState, bindings, bindingStates); + + default: + throw new UnreachableException(); + } + + return memberInit.Update(@new, ((IReadOnlyList<MemberBinding>?)bindings) ?? memberInit.Bindings); + + // Although we allow MemberInitExpression to be evaluated within larger tree fragments, we don't constantize them when they're the + // evaluatable root, since that would embed arbitrary user type instances in our shaper. + // To support that, when the MemberInitExpression is evaluatable, we include a nonEvaluatableAsRootHandler lambda in the returned + // state, which gets invoked up the stack, calling this method. This evaluates the MemberInitExpression's children, but not the + // MemberInitExpression. + MemberInitExpression EvaluateChildren( + MemberInitExpression memberInit, + NewExpression @new, + State newState, + MemberBinding[]? bindings, + State[] bindingStates) + { + // If the NewExpression is evaluatable but one of the bindings isn't, we can't evaluate only the NewExpression + // (MemberInitExpression requires a NewExpression and doesn't accept ParameterException). However, we may still need to + // evaluate constructor arguments in the NewExpression. + if (newState.IsEvaluatable) + { + @new = (NewExpression)newState.NotEvaluatableAsRootHandler!(); + } + + List<PathNode>? children = null; + + if (newState.ContainsEvaluatable && _calculatingPath) + { + children = + [ + newState.Path! with { PathFromParent = static e => Property(e, nameof(MemberInitExpression.NewExpression)) } + ]; + } + + for (var i = 0; i < memberInit.Bindings.Count; i++) + { + var bindingState = bindingStates[i]; + + if (bindingState.IsEvaluatable) + { + bindings ??= memberInit.Bindings.ToArray(); + var binding = (MemberAssignment)bindings[i]; + bindings[i] = binding.Update(ProcessEvaluatableRoot(binding.Expression, ref bindingState)); + bindingStates[i] = bindingState; + } + + if (bindingState.ContainsEvaluatable && _calculatingPath) + { + children ??= []; + var index = i; // i gets mutated so make a copy for capturing below + children.Add( + bindingState.Path! with + { + PathFromParent = e => + Property( + Convert( + Call( + Property(e, nameof(MemberInitExpression.Bindings)), + ReadOnlyMemberBindingCollectionIndexerGetter, + arguments: [Constant(index)]), typeof(MemberAssignment)), + MemberAssignmentExpressionProperty) + }); + } + } + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(MemberInitExpression), children); + + return memberInit.Update(@new, ((IReadOnlyList<MemberBinding>?)bindings) ?? memberInit.Bindings); + } + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitListInit(ListInitExpression listInit) + { + // First, visit the NewExpression and all initializers, saving states as well + var @new = (NewExpression)Visit(listInit.NewExpression, out var newState); + var state = newState.StateType; + var initializers = listInit.Initializers; + var initializerArgumentStates = new State[listInit.Initializers.Count][]; + + IReadOnlyList<Expression>[]? visitedInitializersArguments = null; + + for (var i = 0; i < initializers.Count; i++) + { + var initializer = initializers[i]; + + var visitedArguments = Visit(initializer.Arguments, ref state, out var argumentStates); + if (visitedArguments is not null) + { + if (visitedInitializersArguments is null) + { + visitedInitializersArguments = new IReadOnlyList<Expression>[initializers.Count]; + for (var j = 0; j < i; j++) + { + visitedInitializersArguments[j] = initializers[j].Arguments; + } + } + } + + if (visitedInitializersArguments is not null) + { + visitedInitializersArguments[i] = (IReadOnlyList<Expression>?)visitedArguments ?? initializer.Arguments; + } + + initializerArgumentStates[i] = argumentStates; + } + + // We've visited everything and have both our aggregate state, and the states of all initializer expressions. + switch (state) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + if (IsGenerallyEvaluatable(listInit)) + { + _state = State.CreateEvaluatable(typeof(ListInitExpression), state is StateType.EvaluatableWithCapturedVariable); + break; + } + + goto case StateType.ContainsEvaluatable; + + case StateType.ContainsEvaluatable: + // If the NewExpression is evaluatable but one of the bindings isn't, we can't evaluate only the NewExpression + // (ListInitExpression requires a NewExpression and doesn't accept ParameterException). However, we may still need to + // evaluate constructor arguments in the NewExpression. + if (newState.IsEvaluatable) + { + @new = (NewExpression)newState.NotEvaluatableAsRootHandler!(); + } + + List<PathNode>? children = null; + + if (newState.ContainsEvaluatable) + { + children = + [ + newState.Path! with { PathFromParent = static e => Property(e, nameof(MethodCallExpression.Object)) } + ]; + } + + for (var i = 0; i < initializers.Count; i++) + { + var initializer = initializers[i]; + + var visitedArguments = EvaluateList( + visitedInitializersArguments is null + ? initializer.Arguments + : visitedInitializersArguments[i], + initializerArgumentStates[i], + ref children, + static i => e => + Call( + Property(e, nameof(MethodCallExpression.Arguments)), + ReadOnlyCollectionIndexerGetter, + arguments: [Constant(i)])); + + if (visitedArguments is not null && visitedInitializersArguments is null) + { + visitedInitializersArguments = new IReadOnlyList<Expression>[initializers.Count]; + for (var j = 0; j < i; j++) + { + visitedInitializersArguments[j] = initializers[j].Arguments; + } + } + + if (visitedInitializersArguments is not null) + { + visitedInitializersArguments[i] = (IReadOnlyList<Expression>?)visitedArguments ?? initializer.Arguments; + } + } + + _state = children is null + ? State.NoEvaluatability + : State.CreateContainsEvaluatable(typeof(ListInitExpression), children); + break; + + default: + throw new UnreachableException(); + } + + foreach (var argumentState in initializerArgumentStates) + { + StateArrayPool.Return(argumentState); + } + + if (visitedInitializersArguments is null) + { + return listInit.Update(@new, listInit.Initializers); + } + + var visitedInitializers = new ElementInit[initializers.Count]; + for (var i = 0; i < visitedInitializersArguments.Length; i++) + { + visitedInitializers[i] = initializers[i].Update(visitedInitializersArguments[i]); + } + + return listInit.Update(@new, visitedInitializers); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitUnary(UnaryExpression unary) + { + var operand = Visit(unary.Operand, out var operandState); + + switch (operandState.StateType) + { + case StateType.NoEvaluatability: + _state = State.NoEvaluatability; + break; + + case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown: + { + if (IsGenerallyEvaluatable(unary)) + { + // Avoid allocating for the notEvaluatableAsRootHandler closure below unless we actually end up in the evaluatable case + var (unary2, operand2, operandState2) = (unary, operand, operandState); + _state = State.CreateEvaluatable( + typeof(UnaryExpression), + _state.ContainsCapturedVariable, + // See note below on EvaluateChildren + notEvaluatableAsRootHandler: () => EvaluateOperand(unary2, operand2, operandState2)); + break; + } + + goto case StateType.ContainsEvaluatable; + } + + case StateType.ContainsEvaluatable: + return EvaluateOperand(unary, operand, operandState); + + default: + throw new UnreachableException(); + } + + return unary.Update(operand); + + // There are some cases of Convert nodes which we shouldn't evaluate when they're at the top of an evaluatable root (but can + // evaluate when they're part of a larger fragment). + // To support that, when the UnaryExpression is evaluatable, we include a nonEvaluatableAsRootHandler lambda in the returned state, + // which gets invoked up the stack, calling this method. This evaluates the UnaryExpression's operand, but not the UnaryExpression. + UnaryExpression EvaluateOperand(UnaryExpression unary, Expression operand, State operandState) + { + if (operandState.IsEvaluatable) + { + operand = ProcessEvaluatableRoot(operand, ref operandState); + } + + if (_state.ContainsEvaluatable) + { + _state = _calculatingPath + ? State.CreateContainsEvaluatable( + typeof(UnaryExpression), + [_state.Path! with { PathFromParent = static e => Property(e, nameof(UnaryExpression.Operand)) }]) + : State.NoEvaluatability; + } + + return unary.Update(operand); + } + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override ElementInit VisitElementInit(ElementInit node) + => throw new UnreachableException(); // Handled in VisitListInit + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override MemberListBinding VisitMemberListBinding(MemberListBinding node) + => throw new InvalidOperationException(CoreStrings.MemberListBindingNotSupported); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) + => throw new InvalidOperationException(CoreStrings.MemberMemberBindingNotSupported); + + #endregion Visitation implementations + + #region Unsupported node types + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitBlock(BlockExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override CatchBlock VisitCatchBlock(CatchBlock node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitDebugInfo(DebugInfoExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitDynamic(DynamicExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitGoto(GotoExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override LabelTarget VisitLabelTarget(LabelTarget? node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitLabel(LabelExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitLoop(LoopExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitSwitch(SwitchExpression node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override SwitchCase VisitSwitchCase(SwitchCase node) + => throw new NotSupportedException(); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + protected override Expression VisitTry(TryExpression node) + => throw new NotSupportedException(); + + #endregion Unsupported node types + + private static StateType CombineStateTypes(StateType stateType1, StateType stateType2) + => (stateType1, stateType2) switch + { + (StateType.Unknown, var s) => s, + (var s, StateType.Unknown) => s, + + (StateType.NoEvaluatability, StateType.NoEvaluatability) => StateType.NoEvaluatability, + + (StateType.EvaluatableWithoutCapturedVariable, StateType.EvaluatableWithoutCapturedVariable) + => StateType.EvaluatableWithoutCapturedVariable, + + (StateType.EvaluatableWithCapturedVariable, + StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable) + or + (StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable, + StateType.EvaluatableWithCapturedVariable) + => StateType.EvaluatableWithCapturedVariable, + + _ => StateType.ContainsEvaluatable + }; + + private Expression[]? Visit( + ReadOnlyCollection<Expression> expressions, + ref StateType aggregateStateType, + out State[] expressionStates, + bool poolExpressionStates = true) + => Visit(expressions, Visit, ref aggregateStateType, out expressionStates, poolExpressionStates); + + // This follows the ExpressionVisitor.Visit(ReadOnlyCollection<T>) pattern. + private T[]? Visit<T>( + ReadOnlyCollection<T> expressions, + Func<T, T> elementVisitor, + ref StateType aggregateStateType, + out State[] expressionStates, + bool poolExpressionStates = true) + { + if (expressions.Count == 0) + { + aggregateStateType = CombineStateTypes(aggregateStateType, StateType.EvaluatableWithoutCapturedVariable); + expressionStates = []; + return null; + } + + // In the normal case, the array for containing the expression states is pooled - we allocate it here and return it in the calling + // function at the end of processing. + // However, we have cases where a node is evaluatable, but not as an evaluatable root (e.g. NewExpression, NewArrayExpression - see + // e.g. VisitNewExpression for more details). In these cases we return Evaluatable state, but with a "NotEvaluatableAsRootHandler" + // that allows evaluating the node's children up the stack in case it's the root. The state array must continue living for that case + // even once VisitNew returns, as the callback may be called later and needs to access the states. But the callback may also never + // be called (if the NewExpression isn't a root, but rather part of a larger evaluatable fragment). + // So we lack an easy place to return the array to the pool, and refrain from pooling it for that case (at least for now). + expressionStates = poolExpressionStates ? StateArrayPool.Rent(expressions.Count) : new State[expressions.Count]; + + T[]? newExpressions = null; + for (var i = 0; i < expressions.Count; i++) + { + var oldExpression = expressions[i]; + var newExpression = elementVisitor(oldExpression); + var expressionState = _state; + + if (!ReferenceEquals(newExpression, oldExpression) && newExpressions is null) + { + newExpressions = new T[expressions.Count]; + for (var j = 0; j < i; j++) + { + newExpressions[j] = expressions[j]; + } + } + + if (newExpressions is not null) + { + newExpressions[i] = newExpression; + } + + expressionStates[i] = expressionState; + + aggregateStateType = CombineStateTypes(aggregateStateType, expressionState.StateType); + } + + return newExpressions; + } + + private Expression[]? EvaluateList( + IReadOnlyList<Expression> expressions, + State[] expressionStates, + ref List<PathNode>? children, + Func<int, Func<Expression, Expression>> pathFromParentGenerator) + { + // This allows us to make in-place changes in the expression array when the previous visitation pass made modifications (and so + // returned a mutable array). This removes an additional copy that would be needed. + var visitedExpressions = expressions as Expression[]; + + for (var i = 0; i < expressions.Count; i++) + { + var argumentState = expressionStates[i]; + if (argumentState.IsEvaluatable) + { + if (visitedExpressions is null) + { + visitedExpressions = new Expression[expressions.Count]; + for (var j = 0; j < i; j++) + { + visitedExpressions[j] = expressions[j]; + } + } + + visitedExpressions[i] = ProcessEvaluatableRoot(expressions[i], ref argumentState); + expressionStates[i] = argumentState; + } + else if (visitedExpressions is not null) + { + visitedExpressions[i] = expressions[i]; + } + + if (argumentState.ContainsEvaluatable && _calculatingPath) + { + children ??= []; + children.Add(argumentState.Path! with { PathFromParent = pathFromParentGenerator(i) }); + } + } + + return visitedExpressions; + } + + [return: NotNullIfNotNull(nameof(evaluatableRoot))] + private Expression? ProcessEvaluatableRoot(Expression? evaluatableRoot, ref State state) + { + if (evaluatableRoot is null) + { + return null; + } + + var evaluateAsParameter = + // In some cases, constantization is forced by the context ([NotParameterized], EF.Constant) + !state.ForceConstantization + && _parameterize + && ( + // If the nodes contains a captured variable somewhere within it, we evaluate as a parameter. + state.ContainsCapturedVariable + // We don't evaluate as constant if we're not inside a lambda, i.e. in a top-level operator. This is to make sure that + // non-lambda arguments to e.g. Skip/Take are parameterized rather than evaluated as constant, since that would produce + // different SQLs for each value. + || !_inLambda + || (evaluatableRoot is MemberExpression member + && (member.Expression is not null || member.Member is not FieldInfo { IsInitOnly: true }))); + + // We have some cases where a node is evaluatable, but only as part of a larger subtree, and should not be evaluated as a tree root. + // For these cases, the node's state has a notEvaluatableAsRootHandler lambda, which we can invoke to make evaluate the node's + // children (as needed), but not itself. + if (TryHandleNonEvaluatableAsRoot(evaluatableRoot, state, evaluateAsParameter, out var result)) + { + return result; + } + + var value = Evaluate(evaluatableRoot, out var parameterName, out var isContextAccessor); + + switch (value) + { + // If the query contains a nested IQueryable, e.g. Where(b => context.Blogs.Count()...), the context.Blogs parts gets + // evaluated as a parameter; visit its expression tree instead. + case IQueryable { Expression: var innerExpression }: + return Visit(innerExpression); + + case Expression innerExpression when !isContextAccessor: + return Visit(innerExpression); + } + + if (isContextAccessor) + { + // Context accessors (query filters accessing the context) never get constantized + evaluateAsParameter = true; + } + + if (evaluateAsParameter) + { + if (_parameterizedValues.TryGetValue(evaluatableRoot, out var cachedParameter)) + { + // We're here when the same captured variable (or other fragment) is referenced more than once in the query; we want to + // use the same query parameter rather than sending it twice. + // Note that in path calculation (precompiled query), we don't have to do anything, as the path only needs to be returned + // once. + state = State.NoEvaluatability; + return cachedParameter; + } + + if (_calculatingPath) + { + state = new() + { + StateType = StateType.ContainsEvaluatable, + Path = new() + { + ExpressionType = state.ExpressionType!, + ParameterName = parameterName, + Children = Array.Empty<PathNode>() + } + }; + + // We still maintain _parameterValues since later parameter names are generated based on already-populated names. + _parameterValues.AddParameter(parameterName, null); + + return evaluatableRoot; + } + + // Regular parameter extraction mode; client-evaluate the subtree and replace it with a query parameter. + state = State.NoEvaluatability; + + _parameterValues.AddParameter(parameterName, value); + + return _parameterizedValues[evaluatableRoot] = Parameter(evaluatableRoot.Type, parameterName); + } + + // Evaluate as constant + state = State.NoEvaluatability; + + // In precompilation mode, we don't care about constant evaluation since the expression tree itself isn't going to get used. + // We only care about generating code for extracting captured variables, so ignore. + if (_calculatingPath) + { + // TODO: EF.Constant is probably incompatible with precompilation, may need to throw (but not here, only from EF.Constant) + return evaluatableRoot; + } + + var returnType = evaluatableRoot.Type; + var constantExpression = Constant(value, value?.GetType() ?? returnType); + + return constantExpression.Type != returnType + ? Convert(constantExpression, returnType) + : constantExpression; + + bool TryHandleNonEvaluatableAsRoot(Expression root, State state, bool asParameter, [NotNullWhen(true)] out Expression? result) + { + switch (root) + { + // We don't parameterize NewArrayExpression when its an evaluatable root, since we want to allow translating new[] { x, y } + // to e.g. IN (x, y) rather than parameterizing the whole thing. But bubble up the evaluatable state so it may get evaluated + // at a higher level. + case NewArrayExpression when asParameter: + // We don't constantize NewExpression/MemberInitExpression since that would embed arbitrary user type instances in our + // shaper. + case NewExpression or MemberInitExpression when !asParameter: + // There are some cases of Convert nodes which we shouldn't evaluate when they're at the top of an evaluatable root (but can + // evaluate when they're part of a larger fragment). + case UnaryExpression unary when PreserveConvertNode(unary): + result = state.NotEvaluatableAsRootHandler!(); + return true; + + default: + result = null; + return false; + } + + bool PreserveConvertNode(Expression expression) + { + if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression) + { + if (unaryExpression.Type == typeof(object) + || unaryExpression.Type == typeof(Enum) + || unaryExpression.Operand.Type.UnwrapNullableType().IsEnum) + { + return true; + } + + var innerType = unaryExpression.Operand.Type.UnwrapNullableType(); + if (unaryExpression.Type.UnwrapNullableType() == typeof(int) + && (innerType == typeof(byte) + || innerType == typeof(sbyte) + || innerType == typeof(char) + || innerType == typeof(short) + || innerType == typeof(ushort))) + { + return true; + } + + return PreserveConvertNode(unaryExpression.Operand); + } + + return false; + } + } + } + + private object? Evaluate(Expression? expression) + => Evaluate(expression, out _, out _); + + private object? Evaluate(Expression? expression, out string parameterName, out bool isContextAccessor) + { + var value = EvaluateCore(expression, out var tempParameterName, out isContextAccessor); + parameterName = tempParameterName ?? "p"; + + var compilerPrefixIndex = parameterName.LastIndexOf('>'); + if (compilerPrefixIndex != -1) + { + parameterName = parameterName[(compilerPrefixIndex + 1)..]; + } + + parameterName = $"{QueryCompilationContext.QueryParameterPrefix}{parameterName}_{_parameterValues.ParameterValues.Count}"; + + return value; + + object? EvaluateCore(Expression? expression, out string? parameterName, out bool isContextAccessor) + { + parameterName = null; + isContextAccessor = false; + + if (expression == null) + { + return null; + } + + if (_generateContextAccessors) + { + var visited = _contextParameterReplacer.Visit(expression); + + if (visited != expression) + { + parameterName = QueryFilterPrefix + + (RemoveConvert(expression) is MemberExpression { Member.Name: var memberName } ? ("__" + memberName) : "__p"); + isContextAccessor = true; + + return Lambda(visited, _contextParameterReplacer.ContextParameterExpression); + } + + static Expression RemoveConvert(Expression expression) + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression + ? RemoveConvert(unaryExpression.Operand) + : expression; + } + + switch (expression) + { + case MemberExpression memberExpression: + var instanceValue = EvaluateCore(memberExpression.Expression, out parameterName, out isContextAccessor); + try + { + switch (memberExpression.Member) + { + case FieldInfo fieldInfo: + parameterName = parameterName is null ? fieldInfo.Name : $"{parameterName}_{fieldInfo.Name}"; + return fieldInfo.GetValue(instanceValue); + + case PropertyInfo propertyInfo: + parameterName = parameterName is null ? propertyInfo.Name : $"{parameterName}_{propertyInfo.Name}"; + return propertyInfo.GetValue(instanceValue); + } + } + catch + { + // Try again when we compile the delegate + } + + break; + + case ConstantExpression constantExpression: + return constantExpression.Value; + + case MethodCallExpression methodCallExpression: + parameterName = methodCallExpression.Method.Name; + break; + + case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression + when (unaryExpression.Type.UnwrapNullableType() == unaryExpression.Operand.Type): + return EvaluateCore(unaryExpression.Operand, out parameterName, out isContextAccessor); + } + + try + { + return Lambda<Func<object>>( + Convert(expression, typeof(object))) + .Compile(preferInterpretation: true) + .Invoke(); + } + catch (Exception exception) + { + throw new InvalidOperationException( + _logger.ShouldLogSensitiveData() + ? CoreStrings.ExpressionParameterizationExceptionSensitive(expression) + : CoreStrings.ExpressionParameterizationException, + exception); + } + } + } + + private bool IsGenerallyEvaluatable(Expression expression) + => _evaluatableExpressionFilter.IsEvaluatableExpression(expression, _model) + && (_parameterize + // Don't evaluate QueryableMethods if in compiled query + || !(expression is MethodCallExpression { Method: var method } && method.DeclaringType == typeof(Queryable))); + + private enum StateType + { + /// <summary> + /// A temporary initial state, before any children have been examined. + /// </summary> + Unknown, + + /// <summary> + /// Means that the current node is neither evaluatable, nor does it contains an evaluatable node. + /// </summary> + NoEvaluatability, + + /// <summary> + /// Whether the current node is evaluatable, i.e. contains no references to server-side resources, and does not contain any + /// captured variables. Such nodes can be evaluated and the result integrated as constants in the tree. + /// </summary> + EvaluatableWithoutCapturedVariable, + + /// <summary> + /// Whether the current node is evaluatable, i.e. contains no references to server-side resources, but contains captured + /// variables. Such nodes can be parameterized. + /// </summary> + EvaluatableWithCapturedVariable, + + /// <summary> + /// Whether the current node contains (parameterizable) evaluatable nodes anywhere within its children. + /// </summary> + ContainsEvaluatable + } + + private readonly record struct State + { + public static State CreateEvaluatable( + Type expressionType, + bool containsCapturedVariable, + Func<Expression>? notEvaluatableAsRootHandler = null) + => new() + { + StateType = containsCapturedVariable + ? StateType.EvaluatableWithCapturedVariable + : StateType.EvaluatableWithoutCapturedVariable, + ExpressionType = expressionType, + NotEvaluatableAsRootHandler = notEvaluatableAsRootHandler + }; + + public static State CreateContainsEvaluatable(Type expressionType, IReadOnlyList<PathNode> children) + => new() + { + StateType = StateType.ContainsEvaluatable, + Path = new() { ExpressionType = expressionType, Children = children } + }; + + /// <summary> + /// Means that we're neither within an evaluatable subtree, nor on a node which contains one (and therefore needs to track the + /// path to it). + /// </summary> + public static readonly State NoEvaluatability = new() { StateType = StateType.NoEvaluatability }; + + public StateType StateType { get; init; } + + public Type? ExpressionType { get; init; } + + /// <summary> + /// A tree containing information on reaching all evaluatable nodes contained within this node. + /// </summary> + public PathNode? Path { get; init; } + + public bool ForceConstantization { get; init; } + + public Func<Expression>? NotEvaluatableAsRootHandler { get; init; } + + public bool IsEvaluatable + => StateType is StateType.EvaluatableWithoutCapturedVariable or StateType.EvaluatableWithCapturedVariable or StateType.Unknown; + + public bool ContainsCapturedVariable + => StateType is StateType.EvaluatableWithCapturedVariable; + + public bool ContainsEvaluatable + => StateType is StateType.ContainsEvaluatable; + + public override string ToString() + => StateType switch + { + StateType.NoEvaluatability => "No evaluatability", + StateType.EvaluatableWithoutCapturedVariable => "Evaluatable, no captured vars", + StateType.EvaluatableWithCapturedVariable => "Evaluatable, captured vars", + StateType.ContainsEvaluatable => "Contains evaluatable", + + _ => throw new UnreachableException() + }; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + [EntityFrameworkInternal] + public sealed record PathNode + { + /// <summary> + /// The type of the expression represented by this <see cref="PathNode" />. + /// </summary> + public required Type ExpressionType { get; init; } + + /// <summary> + /// Children of this node which contain parameterizable fragments. + /// </summary> + public required IReadOnlyList<PathNode>? Children { get; init; } + + /// <summary> + /// A function that accepts the parent node, and returns an expression representing the path to this node from that parent + /// node. The returned expression can then be used to generate C# code that traverses the expression tree. + /// </summary> + public Func<Expression, Expression>? PathFromParent { get; init; } + + /// <summary> + /// For nodes representing parameterizable roots, contains the preferred parameter name, generated based on the expression + /// node type/contents. + /// </summary> + public string? ParameterName { get; init; } + } + + private sealed class ContextParameterReplacer(Type contextType) : ExpressionVisitor + { + public ParameterExpression ContextParameterExpression { get; } = Parameter(contextType, "context"); + + [return: NotNullIfNotNull("expression")] + public override Expression? Visit(Expression? expression) + => expression?.Type != typeof(object) + && expression?.Type.IsAssignableFrom(contextType) == true + ? ContextParameterExpression + : base.Visit(expression); + } + + private sealed class DummyParameterValues : IParameterValues + { + private readonly Dictionary<string, object?> _parameterValues = new(); + + public IReadOnlyDictionary<string, object?> ParameterValues + => _parameterValues; + + public void AddParameter(string name, object? value) + => _parameterValues.Add(name, value); + } +} diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs index a78e3682f79..07b5982255b 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs @@ -49,7 +49,7 @@ private static readonly PropertyInfo QueryContextContextPropertyInfo private readonly EntityReferenceOptionalMarkingExpressionVisitor _entityReferenceOptionalMarkingExpressionVisitor; private readonly RemoveRedundantNavigationComparisonExpressionVisitor _removeRedundantNavigationComparisonExpressionVisitor; private readonly HashSet<string> _parameterNames = []; - private readonly ParameterExtractingExpressionVisitor _parameterExtractingExpressionVisitor; + private readonly ExpressionTreeFuncletizer _funcletizer; private readonly INavigationExpansionExtensibilityHelper _extensibilityHelper; private readonly HashSet<IEntityType> _nonCyclicAutoIncludeEntityTypes; @@ -80,14 +80,12 @@ public NavigationExpandingExpressionVisitor( _entityReferenceOptionalMarkingExpressionVisitor = new EntityReferenceOptionalMarkingExpressionVisitor(); _removeRedundantNavigationComparisonExpressionVisitor = new RemoveRedundantNavigationComparisonExpressionVisitor( queryCompilationContext.Logger); - _parameterExtractingExpressionVisitor = new ParameterExtractingExpressionVisitor( + _funcletizer = new ExpressionTreeFuncletizer( + _queryCompilationContext.Model, evaluatableExpressionFilter, - _parameters, _queryCompilationContext.ContextType, - _queryCompilationContext.Model, - _queryCompilationContext.Logger, - parameterize: false, - generateContextAccessors: true); + generateContextAccessors: true, + _queryCompilationContext.Logger); _nonCyclicAutoIncludeEntityTypes = !_queryCompilationContext.IgnoreAutoIncludes ? [] : null!; } @@ -210,8 +208,8 @@ protected override Expression VisitExtension(Expression extensionExpression) // Apply defining query only when it is not custom query root && entityQueryRootExpression.GetType() == typeof(EntityQueryRootExpression)) { - var processedDefiningQueryBody = - _parameterExtractingExpressionVisitor.ExtractParameters(definingQuery.Body, clearEvaluatedValues: false); + var processedDefiningQueryBody = _funcletizer.ExtractParameters( + definingQuery.Body, _parameters, parameterize: false, clearParameterizedValues: false); processedDefiningQueryBody = _queryTranslationPreprocessor.NormalizeQueryableMethod(processedDefiningQueryBody); processedDefiningQueryBody = _nullCheckRemovingExpressionVisitor.Visit(processedDefiningQueryBody); processedDefiningQueryBody = @@ -1754,8 +1752,8 @@ private Expression ApplyQueryFilter(IEntityType entityType, NavigationExpansionE if (!_parameterizedQueryFilterPredicateCache.TryGetValue(rootEntityType, out var filterPredicate)) { filterPredicate = queryFilter; - filterPredicate = (LambdaExpression)_parameterExtractingExpressionVisitor.ExtractParameters( - filterPredicate, clearEvaluatedValues: false); + filterPredicate = (LambdaExpression)_funcletizer.ExtractParameters( + filterPredicate, _parameters, parameterize: false, clearParameterizedValues: false); filterPredicate = (LambdaExpression)_queryTranslationPreprocessor.NormalizeQueryableMethod(filterPredicate); // We need to do entity equality, but that requires a full method call on a query root to properly flow the diff --git a/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs b/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs deleted file mode 100644 index d3057838ead..00000000000 --- a/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs +++ /dev/null @@ -1,728 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; - -namespace Microsoft.EntityFrameworkCore.Query.Internal; - -/// <summary> -/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to -/// the same compatibility standards as public APIs. It may be changed or removed without notice in -/// any release. You should only use it directly in your code with extreme caution and knowing that -/// doing so can result in application failures when updating to a new Entity Framework Core release. -/// </summary> -public class ParameterExtractingExpressionVisitor : ExpressionVisitor -{ - private const string QueryFilterPrefix = "ef_filter"; - - private readonly IParameterValues _parameterValues; - private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger; - private readonly bool _parameterize; - private readonly bool _generateContextAccessors; - private readonly EvaluatableExpressionFindingExpressionVisitor _evaluatableExpressionFindingExpressionVisitor; - private readonly ContextParameterReplacingExpressionVisitor _contextParameterReplacingExpressionVisitor; - - private readonly Dictionary<Expression, EvaluatedValues> _evaluatedValues = new(ExpressionEqualityComparer.Instance); - - private IDictionary<Expression, bool> _evaluatableExpressions; - private IQueryProvider? _currentQueryProvider; - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - public ParameterExtractingExpressionVisitor( - IEvaluatableExpressionFilter evaluatableExpressionFilter, - IParameterValues parameterValues, - Type contextType, - IModel model, - IDiagnosticsLogger<DbLoggerCategory.Query> logger, - bool parameterize, - bool generateContextAccessors) - { - _evaluatableExpressionFindingExpressionVisitor - = new EvaluatableExpressionFindingExpressionVisitor(evaluatableExpressionFilter, model, parameterize); - _parameterValues = parameterValues; - _logger = logger; - _parameterize = parameterize; - _generateContextAccessors = generateContextAccessors; - // The entry method will take care of populating this field always. So accesses should be safe. - _evaluatableExpressions = null!; - _contextParameterReplacingExpressionVisitor = _generateContextAccessors - ? new ContextParameterReplacingExpressionVisitor(contextType) - : null!; - } - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - public virtual Expression ExtractParameters(Expression expression) - => ExtractParameters(expression, clearEvaluatedValues: true); - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - public virtual Expression ExtractParameters(Expression expression, bool clearEvaluatedValues) - { - var oldEvaluatableExpressions = _evaluatableExpressions; - _evaluatableExpressions = _evaluatableExpressionFindingExpressionVisitor.Find(expression); - - try - { - return Visit(expression); - } - finally - { - _evaluatableExpressions = oldEvaluatableExpressions; - if (clearEvaluatedValues) - { - _evaluatedValues.Clear(); - } - } - } - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - [return: NotNullIfNotNull("expression")] - public override Expression? Visit(Expression? expression) - { - if (expression == null) - { - return null; - } - - if (_evaluatableExpressions.TryGetValue(expression, out var generateParameter) - && !PreserveInitializationConstant(expression, generateParameter) - && !PreserveConvertNode(expression)) - { - return Evaluate(expression, _parameterize && generateParameter); - } - - return base.Visit(expression); - } - - private static bool PreserveInitializationConstant(Expression expression, bool generateParameter) - => !generateParameter && expression is NewExpression or MemberInitExpression; - - private bool PreserveConvertNode(Expression expression) - { - if (expression is UnaryExpression unaryExpression - && (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked)) - { - if (unaryExpression.Type == typeof(object) - || unaryExpression.Type == typeof(Enum) - || unaryExpression.Operand.Type.UnwrapNullableType().IsEnum) - { - return true; - } - - var innerType = unaryExpression.Operand.Type.UnwrapNullableType(); - if (unaryExpression.Type.UnwrapNullableType() == typeof(int) - && (innerType == typeof(byte) - || innerType == typeof(sbyte) - || innerType == typeof(char) - || innerType == typeof(short) - || innerType == typeof(ushort))) - { - return true; - } - - return PreserveConvertNode(unaryExpression.Operand); - } - - return false; - } - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - protected override Expression VisitConditional(ConditionalExpression conditionalExpression) - { - var newTestExpression = TryGetConstantValue(conditionalExpression.Test) ?? Visit(conditionalExpression.Test); - - if (newTestExpression is ConstantExpression { Value: bool constantTestValue }) - { - return constantTestValue - ? Visit(conditionalExpression.IfTrue) - : Visit(conditionalExpression.IfFalse); - } - - return conditionalExpression.Update( - newTestExpression, - Visit(conditionalExpression.IfTrue), - Visit(conditionalExpression.IfFalse)); - } - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) - { - // If this is a call to EF.Constant(), or EF.Parameter(), then examine the operand; it it's isn't evaluatable (i.e. contains a - // reference to a database table), throw immediately. Otherwise, evaluate the operand (either as a constant or as a parameter) and - // return that. - if (methodCallExpression.Method.DeclaringType == typeof(EF)) - { - switch (methodCallExpression.Method.Name) - { - case nameof(EF.Constant): - { - var operand = methodCallExpression.Arguments[0]; - if (!_evaluatableExpressions.TryGetValue(operand, out _)) - { - throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument); - } - - return Evaluate(operand, generateParameter: false); - } - - case nameof(EF.Parameter): - { - var operand = methodCallExpression.Arguments[0]; - if (!_evaluatableExpressions.TryGetValue(operand, out _)) - { - throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument); - } - - return Evaluate(operand, generateParameter: true); - } - } - } - - return base.VisitMethodCall(methodCallExpression); - } - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - protected override Expression VisitBinary(BinaryExpression binaryExpression) - { - switch (binaryExpression.NodeType) - { - case ExpressionType.Coalesce: - { - var newLeftExpression = TryGetConstantValue(binaryExpression.Left) ?? Visit(binaryExpression.Left); - if (newLeftExpression is ConstantExpression constantLeftExpression) - { - return constantLeftExpression.Value == null - ? Visit(binaryExpression.Right) - : newLeftExpression; - } - - return binaryExpression.Update( - newLeftExpression, - binaryExpression.Conversion, - Visit(binaryExpression.Right)); - } - - case ExpressionType.AndAlso: - case ExpressionType.OrElse: - { - var newLeftExpression = TryGetConstantValue(binaryExpression.Left) ?? Visit(binaryExpression.Left); - if (ShortCircuitLogicalExpression(newLeftExpression, binaryExpression.NodeType)) - { - return newLeftExpression; - } - - var newRightExpression = TryGetConstantValue(binaryExpression.Right) ?? Visit(binaryExpression.Right); - return ShortCircuitLogicalExpression(newRightExpression, binaryExpression.NodeType) - ? newRightExpression - : binaryExpression.Update(newLeftExpression, binaryExpression.Conversion, newRightExpression); - } - - default: - return base.VisitBinary(binaryExpression); - } - } - - private Expression? TryGetConstantValue(Expression expression) - { - if (_evaluatableExpressions.ContainsKey(expression)) - { - var value = GetValue(expression, out _); - - if (value is bool) - { - return Expression.Constant(value, typeof(bool)); - } - } - - return null; - } - - private static bool ShortCircuitLogicalExpression(Expression expression, ExpressionType nodeType) - => expression is ConstantExpression { Value: bool constantValue } - && ((constantValue && nodeType == ExpressionType.OrElse) - || (!constantValue && nodeType == ExpressionType.AndAlso)); - - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - protected override Expression VisitExtension(Expression extensionExpression) - { - if (extensionExpression is QueryRootExpression queryRootExpression) - { - var queryProvider = queryRootExpression.QueryProvider; - if (_currentQueryProvider == null) - { - _currentQueryProvider = queryProvider; - } - else if (!ReferenceEquals(queryProvider, _currentQueryProvider)) - { - throw new InvalidOperationException(CoreStrings.ErrorInvalidQueryable); - } - - // Visit after detaching query provider since custom query roots can have additional components - extensionExpression = queryRootExpression.DetachQueryProvider(); - } - - return base.VisitExtension(extensionExpression); - } - - private static Expression GenerateConstantExpression(object? value, Type returnType) - { - var constantExpression = Expression.Constant(value, value?.GetType() ?? returnType); - - return constantExpression.Type != returnType - ? Expression.Convert(constantExpression, returnType) - : constantExpression; - } - - private Expression Evaluate(Expression expression, bool generateParameter) - { - object? parameterValue; - string? parameterName; - if (_evaluatedValues.TryGetValue(expression, out var cachedValue)) - { - // The _generateContextAccessors condition allows us to reuse parameter expressions evaluated in query filters. - // In principle, _generateContextAccessors is orthogonal to query filters, but in practice it is only used in the - // nav expansion query filters (and defining query). If this changes in future, they would need to be decoupled. - var existingExpression = generateParameter || _generateContextAccessors - ? cachedValue.Parameter - : cachedValue.Constant; - - if (existingExpression != null) - { - return existingExpression; - } - - parameterValue = cachedValue.Value; - parameterName = cachedValue.CandidateParameterName; - } - else - { - parameterValue = GetValue(expression, out parameterName); - cachedValue = new EvaluatedValues { CandidateParameterName = parameterName, Value = parameterValue }; - _evaluatedValues[expression] = cachedValue; - } - - if (parameterValue is IQueryable innerQueryable) - { - return ExtractParameters(innerQueryable.Expression, clearEvaluatedValues: false); - } - - if (parameterName?.StartsWith(QueryFilterPrefix, StringComparison.Ordinal) != true) - { - if (parameterValue is Expression innerExpression) - { - return ExtractParameters(innerExpression, clearEvaluatedValues: false); - } - - if (!generateParameter) - { - var constantValue = GenerateConstantExpression(parameterValue, expression.Type); - - cachedValue.Constant = constantValue; - - return constantValue; - } - } - - parameterName ??= "p"; - - if (string.Equals(QueryFilterPrefix, parameterName, StringComparison.Ordinal)) - { - parameterName = QueryFilterPrefix + "__p"; - } - - var compilerPrefixIndex - = parameterName.LastIndexOf(">", StringComparison.Ordinal); - - if (compilerPrefixIndex != -1) - { - parameterName = parameterName[(compilerPrefixIndex + 1)..]; - } - - parameterName - = QueryCompilationContext.QueryParameterPrefix - + parameterName - + "_" - + _parameterValues.ParameterValues.Count; - - _parameterValues.AddParameter(parameterName, parameterValue); - - var parameter = Expression.Parameter(expression.Type, parameterName); - - cachedValue.Parameter = parameter; - - return parameter; - } - - private sealed class ContextParameterReplacingExpressionVisitor : ExpressionVisitor - { - private readonly Type _contextType; - - public ContextParameterReplacingExpressionVisitor(Type contextType) - { - ContextParameterExpression = Expression.Parameter(contextType, "context"); - _contextType = contextType; - } - - public ParameterExpression ContextParameterExpression { get; } - - [return: NotNullIfNotNull("expression")] - public override Expression? Visit(Expression? expression) - => expression?.Type != typeof(object) - && expression?.Type.IsAssignableFrom(_contextType) == true - ? ContextParameterExpression - : base.Visit(expression); - } - - private static Expression RemoveConvert(Expression expression) - { - if (expression is UnaryExpression unaryExpression - && expression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked) - { - return RemoveConvert(unaryExpression.Operand); - } - - return expression; - } - - private object? GetValue(Expression? expression, out string? parameterName) - { - parameterName = null; - - if (expression == null) - { - return null; - } - - if (_generateContextAccessors) - { - var newExpression = _contextParameterReplacingExpressionVisitor.Visit(expression); - - if (newExpression != expression) - { - if (newExpression.Type is IQueryable) - { - return newExpression; - } - - parameterName = QueryFilterPrefix - + (RemoveConvert(expression) is MemberExpression memberExpression - ? ("__" + memberExpression.Member.Name) - : ""); - - return Expression.Lambda( - newExpression, - _contextParameterReplacingExpressionVisitor.ContextParameterExpression); - } - } - - switch (expression) - { - case MemberExpression memberExpression: - var instanceValue = GetValue(memberExpression.Expression, out parameterName); - try - { - switch (memberExpression.Member) - { - case FieldInfo fieldInfo: - parameterName = (parameterName != null ? parameterName + "_" : "") + fieldInfo.Name; - return fieldInfo.GetValue(instanceValue); - - case PropertyInfo propertyInfo: - parameterName = (parameterName != null ? parameterName + "_" : "") + propertyInfo.Name; - return propertyInfo.GetValue(instanceValue); - } - } - catch - { - // Try again when we compile the delegate - } - - break; - - case ConstantExpression constantExpression: - return constantExpression.Value; - - case MethodCallExpression methodCallExpression: - parameterName = methodCallExpression.Method.Name; - break; - - case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression - when (unaryExpression.Type.UnwrapNullableType() == unaryExpression.Operand.Type): - return GetValue(unaryExpression.Operand, out parameterName); - } - - try - { - return Expression.Lambda<Func<object>>( - Expression.Convert(expression, typeof(object))) - .Compile(preferInterpretation: true) - .Invoke(); - } - catch (Exception exception) - { - throw new InvalidOperationException( - _logger.ShouldLogSensitiveData() - ? CoreStrings.ExpressionParameterizationExceptionSensitive(expression) - : CoreStrings.ExpressionParameterizationException, - exception); - } - } - - private sealed class EvaluatableExpressionFindingExpressionVisitor : ExpressionVisitor - { - private readonly IEvaluatableExpressionFilter _evaluatableExpressionFilter; - private readonly ISet<ParameterExpression> _allowedParameters = new HashSet<ParameterExpression>(); - private readonly IModel _model; - private readonly bool _parameterize; - - private bool _evaluatable; - private bool _containsClosure; - private bool _inLambda; - private IDictionary<Expression, bool> _evaluatableExpressions; - - public EvaluatableExpressionFindingExpressionVisitor( - IEvaluatableExpressionFilter evaluatableExpressionFilter, - IModel model, - bool parameterize) - { - _evaluatableExpressionFilter = evaluatableExpressionFilter; - _model = model; - _parameterize = parameterize; - // The entry method will take care of populating this field always. So accesses should be safe. - _evaluatableExpressions = null!; - } - - public IDictionary<Expression, bool> Find(Expression expression) - { - _evaluatable = true; - _containsClosure = false; - _inLambda = false; - _evaluatableExpressions = new Dictionary<Expression, bool>(); - _allowedParameters.Clear(); - - Visit(expression); - - return _evaluatableExpressions; - } - - [return: NotNullIfNotNull("expression")] - public override Expression? Visit(Expression? expression) - { - if (expression == null) - { - return base.Visit(expression); - } - - var parentEvaluatable = _evaluatable; - var parentContainsClosure = _containsClosure; - - _evaluatable = IsEvaluatableNodeType(expression, out var preferNoEvaluation) - // Extension point to disable funcletization - && _evaluatableExpressionFilter.IsEvaluatableExpression(expression, _model) - // Don't evaluate QueryableMethods if in compiled query - && (_parameterize || !IsQueryableMethod(expression)); - _containsClosure = false; - - base.Visit(expression); - - if (_evaluatable && !preferNoEvaluation) - { - // Force parameterization when not in lambda - _evaluatableExpressions[expression] = _containsClosure || !_inLambda; - } - - _evaluatable = parentEvaluatable && _evaluatable; - _containsClosure = parentContainsClosure || _containsClosure; - - return expression; - } - - protected override Expression VisitLambda<T>(Expression<T> lambdaExpression) - { - var oldInLambda = _inLambda; - _inLambda = true; - - // Note: Don't skip visiting parameter here. - // SelectMany does not use parameter in lambda but we should still block it from evaluating - base.VisitLambda(lambdaExpression); - - _inLambda = oldInLambda; - return lambdaExpression; - } - - protected override Expression VisitMemberInit(MemberInitExpression memberInitExpression) - { - Visit(memberInitExpression.Bindings, VisitMemberBinding); - - // Cannot make parameter for NewExpression if Bindings cannot be evaluated - // but we still need to visit inside of it. - var bindingsEvaluatable = _evaluatable; - Visit(memberInitExpression.NewExpression); - - if (!bindingsEvaluatable) - { - _evaluatableExpressions.Remove(memberInitExpression.NewExpression); - } - - return memberInitExpression; - } - - protected override Expression VisitListInit(ListInitExpression listInitExpression) - { - Visit(listInitExpression.Initializers, VisitElementInit); - - // Cannot make parameter for NewExpression if Initializers cannot be evaluated - // but we still need to visit inside of it. - var initializersEvaluatable = _evaluatable; - Visit(listInitExpression.NewExpression); - - if (!initializersEvaluatable) - { - _evaluatableExpressions.Remove(listInitExpression.NewExpression); - } - - return listInitExpression; - } - - protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) - { - Visit(methodCallExpression.Object); - var parameterInfos = methodCallExpression.Method.GetParameters(); - for (var i = 0; i < methodCallExpression.Arguments.Count; i++) - { - if (i == 1 - && _evaluatableExpressions.ContainsKey(methodCallExpression.Arguments[0]) - && methodCallExpression.Method.DeclaringType == typeof(Enumerable) - && methodCallExpression.Method.Name == nameof(Enumerable.Select) - && methodCallExpression.Arguments[1] is LambdaExpression lambdaExpression) - { - // Allow evaluation Enumerable.Select operation - foreach (var parameter in lambdaExpression.Parameters) - { - _allowedParameters.Add(parameter); - } - } - - Visit(methodCallExpression.Arguments[i]); - - if (_evaluatableExpressions.ContainsKey(methodCallExpression.Arguments[i]) - && (parameterInfos[i].GetCustomAttribute<NotParameterizedAttribute>() != null - || _model.IsIndexerMethod(methodCallExpression.Method))) - { - _evaluatableExpressions[methodCallExpression.Arguments[i]] = false; - } - } - - return methodCallExpression; - } - - protected override Expression VisitMember(MemberExpression memberExpression) - { - _containsClosure = memberExpression.Expression != null - || !(memberExpression.Member is FieldInfo { IsInitOnly: true }); - return base.VisitMember(memberExpression); - } - - protected override Expression VisitParameter(ParameterExpression parameterExpression) - { - _evaluatable = _allowedParameters.Contains(parameterExpression); - - return base.VisitParameter(parameterExpression); - } - - protected override Expression VisitConstant(ConstantExpression constantExpression) - { - _evaluatable = !(constantExpression.Value is IQueryable); - -#pragma warning disable RCS1096 // Use bitwise operation instead of calling 'HasFlag'. - _containsClosure - = (constantExpression.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate) - && Attribute.IsDefined(constantExpression.Type, typeof(CompilerGeneratedAttribute), inherit: true)) // Closure - || constantExpression.Type == typeof(ValueBuffer); // Find method -#pragma warning restore RCS1096 // Use bitwise operation instead of calling 'HasFlag'. - - return base.VisitConstant(constantExpression); - } - - private static bool IsEvaluatableNodeType(Expression expression, out bool preferNoEvaluation) - { - switch (expression.NodeType) - { - case ExpressionType.NewArrayInit: - preferNoEvaluation = true; - return true; - - case ExpressionType.Extension: - preferNoEvaluation = false; - return expression.CanReduce && IsEvaluatableNodeType(expression.ReduceAndCheck(), out preferNoEvaluation); - - // Identify a call to EF.Constant(), and flag that as non-evaluable. - // This is important to prevent a larger subtree containing EF.Constant from being evaluated, i.e. to make sure that - // the EF.Function argument is present in the tree as its own, constant node. - case ExpressionType.Call - when expression is MethodCallExpression { Method: var method } - && method.DeclaringType == typeof(EF) - && method.Name is nameof(EF.Constant) or nameof(EF.Parameter): - preferNoEvaluation = true; - return false; - - default: - preferNoEvaluation = false; - return true; - } - } - - private static bool IsQueryableMethod(Expression expression) - => expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.DeclaringType == typeof(Queryable); - } - - private sealed class EvaluatedValues - { - public string? CandidateParameterName { get; init; } - public object? Value { get; init; } - public Expression? Constant { get; set; } - public Expression? Parameter { get; set; } - } -} diff --git a/src/EFCore/Query/Internal/QueryCompiler.cs b/src/EFCore/Query/Internal/QueryCompiler.cs index 441f0fd88fc..a0536aff1bb 100644 --- a/src/EFCore/Query/Internal/QueryCompiler.cs +++ b/src/EFCore/Query/Internal/QueryCompiler.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.CompilerServices; + namespace Microsoft.EntityFrameworkCore.Query.Internal; /// <summary> @@ -54,33 +56,36 @@ public QueryCompiler( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual TResult Execute<TResult>(Expression query) + => ExecuteCore<TResult>(query, async: false, CancellationToken.None); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual TResult ExecuteAsync<TResult>(Expression query, CancellationToken cancellationToken = default) + => ExecuteCore<TResult>(query, async: true, cancellationToken); + + private TResult ExecuteCore<TResult>(Expression query, bool async, CancellationToken cancellationToken) { var queryContext = _queryContextFactory.Create(); - query = ExtractParameters(query, queryContext, _logger); + queryContext.CancellationToken = cancellationToken; + + var queryAfterExtraction = ExtractParameters(query, queryContext, _logger); var compiledQuery = _compiledQueryCache .GetOrAddQuery( - _compiledQueryCacheKeyGenerator.GenerateCacheKey(query, async: false), - () => CompileQueryCore<TResult>(_database, query, _model, false)); + _compiledQueryCacheKeyGenerator.GenerateCacheKey(queryAfterExtraction, async), + () => RuntimeFeature.IsDynamicCodeSupported + ? CompileQueryCore<TResult>(_database, queryAfterExtraction, _model, async) + : throw new InvalidOperationException("Query wasn't precompiled and dynamic code isn't supported (NativeAOT)")); return compiledQuery(queryContext); } - /// <summary> - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// </summary> - public virtual Func<QueryContext, TResult> CompileQueryCore<TResult>( - IDatabase database, - Expression query, - IModel model, - bool async) - => database.CompileQuery<TResult>(query, async); - /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -89,9 +94,9 @@ public virtual Func<QueryContext, TResult> CompileQueryCore<TResult>( /// </summary> public virtual Func<QueryContext, TResult> CreateCompiledQuery<TResult>(Expression query) { - query = ExtractParameters(query, _queryContextFactory.Create(), _logger, parameterize: false); + var queryAfterExtraction = ExtractParameters(query, _queryContextFactory.Create(), _logger, compiledQuery: true); - return CompileQueryCore<TResult>(_database, query, _model, false); + return CompileQueryCore<TResult>(_database, queryAfterExtraction, _model, false); } /// <summary> @@ -100,21 +105,11 @@ public virtual Func<QueryContext, TResult> CreateCompiledQuery<TResult>(Expressi /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual TResult ExecuteAsync<TResult>(Expression query, CancellationToken cancellationToken = default) + public virtual Func<QueryContext, TResult> CreateCompiledAsyncQuery<TResult>(Expression query) { - var queryContext = _queryContextFactory.Create(); - - queryContext.CancellationToken = cancellationToken; + var queryAfterExtraction = ExtractParameters(query, _queryContextFactory.Create(), _logger, compiledQuery: true); - query = ExtractParameters(query, queryContext, _logger); - - var compiledQuery - = _compiledQueryCache - .GetOrAddQuery( - _compiledQueryCacheKeyGenerator.GenerateCacheKey(query, async: true), - () => CompileQueryCore<TResult>(_database, query, _model, true)); - - return compiledQuery(queryContext); + return CompileQueryCore<TResult>(_database, queryAfterExtraction, _model, true); } /// <summary> @@ -123,12 +118,12 @@ var compiledQuery /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual Func<QueryContext, TResult> CreateCompiledAsyncQuery<TResult>(Expression query) - { - query = ExtractParameters(query, _queryContextFactory.Create(), _logger, parameterize: false); - - return CompileQueryCore<TResult>(_database, query, _model, true); - } + public virtual Func<QueryContext, TResult> CompileQueryCore<TResult>( + IDatabase database, + Expression query, + IModel model, + bool async) + => database.CompileQuery<TResult>(query, async); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -140,18 +135,8 @@ public virtual Expression ExtractParameters( Expression query, IParameterValues parameterValues, IDiagnosticsLogger<DbLoggerCategory.Query> logger, - bool parameterize = true, + bool compiledQuery = false, bool generateContextAccessors = false) - { - var visitor = new ParameterExtractingExpressionVisitor( - _evaluatableExpressionFilter, - parameterValues, - _contextType, - _model, - logger, - parameterize, - generateContextAccessors); - - return visitor.ExtractParameters(query); - } + => new ExpressionTreeFuncletizer(_model, _evaluatableExpressionFilter, _contextType, generateContextAccessors: false, logger) + .ExtractParameters(query, parameterValues, parameterize: !compiledQuery, clearParameterizedValues: true); }
diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs index 91f66c225f4..6fdef18e57c 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs @@ -3713,11 +3713,11 @@ public override async Task Entity_equality_with_null_coalesce_client_side(bool a AssertSql( """ -@__entity_equality_p_0_CustomerID='ALFKI' +@__entity_equality_a_0_CustomerID='ALFKI' SELECT c FROM root c -WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_p_0_CustomerID)) +WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_a_0_CustomerID)) """); } @@ -4148,9 +4148,7 @@ public override async Task Ternary_should_not_evaluate_both_sides(bool async) AssertSql( """ -@__p_0='none' - -SELECT VALUE {"CustomerID" : c["CustomerID"], "Data1" : @__p_0} +SELECT VALUE {"CustomerID" : c["CustomerID"], "Data1" : "none"} FROM root c WHERE (c["Discriminator"] = "Customer") """); @@ -4527,6 +4525,9 @@ public override void Can_cast_CreateQuery_result_to_IQueryable_T_bug_1730() AssertSql(); } + public override Task IQueryable_captured_variable() + => AssertTranslationFailed(() => base.IQueryable_captured_variable()); + public override async Task Multiple_context_instances(bool async) { await base.Multiple_context_instances(async); @@ -4676,11 +4677,11 @@ public override async Task Contains_over_concatenated_column_and_parameter(bool AssertSql( """ -@__someVariable_1='SomeVariable' +@__someVariable_0='SomeVariable' SELECT c FROM root c -WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] || @__someVariable_1) IN ("ALFKISomeVariable", "ANATRSomeVariable", "ALFKIX")) +WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] || @__someVariable_0) IN ("ALFKISomeVariable", "ANATRSomeVariable", "ALFKIX")) """); } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs index 6545ff7fae8..959bc977eae 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs @@ -1685,7 +1685,19 @@ FROM root c """ SELECT c FROM root c -WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = "ALFKI") AND true)) +WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) +""", + // + """ +SELECT c +FROM root c +WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) +""", + // + """ +SELECT c +FROM root c +WHERE (c["Discriminator"] = "Customer") """); } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs index e884932bdfd..7c3561f5e35 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs @@ -505,6 +505,9 @@ FROM root c """); } + public override Task Preserve_includes_when_applying_skip_take_after_anonymous_type_select(bool async) => + AssertTranslationFailed(() => base.Preserve_includes_when_applying_skip_take_after_anonymous_type_select(async)); + private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs b/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs index 74d60093205..304de28685e 100644 --- a/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs @@ -77,7 +77,7 @@ public virtual Task GroupBy_is_optimized_when_projecting_conditional_expression_ [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task GroupBy_is_optimized_when_filerting_and_projecting_anonymous_type_with_group_key_and_function_aggregate( + public virtual Task GroupBy_is_optimized_when_filtering_and_projecting_anonymous_type_with_group_key_and_function_aggregate( bool async) => AssertQuery( async, diff --git a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs index ec3fb71e405..1eb9030b952 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs @@ -2855,6 +2855,16 @@ public virtual void Can_cast_CreateQuery_result_to_IQueryable_T_bug_1730() products = (IQueryable<Product>)products.Provider.CreateQuery(products.Expression); } + [ConditionalFact] + public virtual async Task IQueryable_captured_variable() + { + await using var context = CreateContext(); + + IQueryable<Order> nestedOrdersQuery = context.Orders; + + _ = await context.Customers.CountAsync(c => nestedOrdersQuery.Count() == 2); + } + [ConditionalTheory] [MemberData(nameof(IsAsyncData))] public virtual Task Select_Subquery_Single(bool async) diff --git a/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs index 02583323e23..3364813cc05 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs @@ -1211,11 +1211,19 @@ await AssertQuery( ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI" && boolean), assertEmpty: true); + await AssertQuery( + async, + ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI" || boolean)); + boolean = true; await AssertQuery( async, ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI" && boolean)); + + await AssertQuery( + async, + ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI" || boolean)); } [ConditionalTheory] @@ -2391,7 +2399,7 @@ public virtual async Task EF_Constant_with_non_evaluatable_argument_throws(bool async, ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Constant(c.CustomerID)))); - Assert.Equal(CoreStrings.EFConstantWithNonEvaluableArgument, exception.Message); + Assert.Equal(CoreStrings.EFConstantWithNonEvaluatableArgument, exception.Message); } [ConditionalTheory] @@ -2438,7 +2446,7 @@ public virtual async Task EF_Parameter_with_non_evaluatable_argument_throws(bool async, ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Parameter(c.CustomerID)))); - Assert.Equal(CoreStrings.EFConstantWithNonEvaluableArgument, exception.Message); + Assert.Equal(CoreStrings.EFParameterWithNonEvaluatableArgument, exception.Message); } private class EntityWithImplicitCast(int value) diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/Ef6GroupBySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/Ef6GroupBySqlServerTest.cs index 9aa64119a51..6df6a492fc6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/Ef6GroupBySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/Ef6GroupBySqlServerTest.cs @@ -159,12 +159,10 @@ public override async Task GroupBy_is_optimized_when_projecting_conditional_expr AssertSql( """ -@__p_0='False' - SELECT CASE WHEN [a].[FirstName] IS NULL THEN N'is null' ELSE N'not null' -END AS [keyIsNull], @__p_0 AS [logicExpression] +END AS [keyIsNull], CAST(0 AS bit) AS [logicExpression] FROM [ArubaOwner] AS [a] GROUP BY [a].[FirstName] """); @@ -180,10 +178,10 @@ GROUP BY [a].[FirstName] // ) AS [Distinct1]"; } - public override async Task GroupBy_is_optimized_when_filerting_and_projecting_anonymous_type_with_group_key_and_function_aggregate( + public override async Task GroupBy_is_optimized_when_filtering_and_projecting_anonymous_type_with_group_key_and_function_aggregate( bool async) { - await base.GroupBy_is_optimized_when_filerting_and_projecting_anonymous_type_with_group_key_and_function_aggregate(async); + await base.GroupBy_is_optimized_when_filtering_and_projecting_anonymous_type_with_group_key_and_function_aggregate(async); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs index 13d6165a6b7..beb1680481e 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs @@ -10374,40 +10374,40 @@ public override async Task Nested_contains_with_enum(bool async) AssertSql( """ -@__ranks_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ranks_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE CASE WHEN [g].[Rank] IN ( SELECT [r].[value] - FROM OPENJSON(@__ranks_1) WITH ([value] int '$') AS [r] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ranks_0) WITH ([value] int '$') AS [r] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """, // """ -@__ammoTypes_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ammoTypes_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE CASE WHEN [w].[AmmunitionType] IN ( SELECT [a].[value] - FROM OPENJSON(@__ammoTypes_1) WITH ([value] int '$') AS [a] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ammoTypes_0) WITH ([value] int '$') AS [a] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServerTest.cs index 2f44080e1c5..b21830a08fa 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServerTest.cs @@ -986,17 +986,17 @@ await AssertCount( AssertSql( """ -@__dateTime_0='1919-12-12T10:20:15.0000000' (DbType = DateTime) -@__dateTime_Month_2='12' -@__dateTime_Day_3='12' -@__dateTime_Hour_4='10' -@__dateTime_Minute_5='20' -@__dateTime_Second_6='15' -@__dateTime_Millisecond_7='0' +@__dateTime_7='1919-12-12T10:20:15.0000000' (DbType = DateTime) +@__dateTime_Month_1='12' +@__dateTime_Day_2='12' +@__dateTime_Hour_3='10' +@__dateTime_Minute_4='20' +@__dateTime_Second_5='15' +@__dateTime_Millisecond_6='0' SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__dateTime_0 > DATETIMEFROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_2, @__dateTime_Day_3, @__dateTime_Hour_4, @__dateTime_Minute_5, @__dateTime_Second_6, @__dateTime_Millisecond_7) +WHERE @__dateTime_7 > DATETIMEFROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_1, @__dateTime_Day_2, @__dateTime_Hour_3, @__dateTime_Minute_4, @__dateTime_Second_5, @__dateTime_Millisecond_6) """); } @@ -1052,13 +1052,13 @@ await AssertCount( AssertSql( """ -@__date_0='1919-12-12T00:00:00.0000000' (DbType = Date) -@__date_Month_2='12' -@__date_Day_3='12' +@__date_3='1919-12-12T00:00:00.0000000' (DbType = Date) +@__date_Month_1='12' +@__date_Day_2='12' SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__date_0 > DATEFROMPARTS(DATEPART(year, GETDATE()), @__date_Month_2, @__date_Day_3) +WHERE @__date_3 > DATEFROMPARTS(DATEPART(year, GETDATE()), @__date_Month_1, @__date_Day_2) """); } @@ -1120,17 +1120,17 @@ public virtual void DateTime2FromParts_compare_with_local_variable() AssertSql( """ -@__dateTime_0='1919-12-12T10:20:15.0000000' -@__dateTime_Month_2='12' -@__dateTime_Day_3='12' -@__dateTime_Hour_4='10' -@__dateTime_Minute_5='20' -@__dateTime_Second_6='15' -@__fractions_7='9999999' +@__dateTime_7='1919-12-12T10:20:15.0000000' +@__dateTime_Month_1='12' +@__dateTime_Day_2='12' +@__dateTime_Hour_3='10' +@__dateTime_Minute_4='20' +@__dateTime_Second_5='15' +@__fractions_6='9999999' SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__dateTime_0 > DATETIME2FROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_2, @__dateTime_Day_3, @__dateTime_Hour_4, @__dateTime_Minute_5, @__dateTime_Second_6, @__fractions_7, 7) +WHERE @__dateTime_7 > DATETIME2FROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_1, @__dateTime_Day_2, @__dateTime_Hour_3, @__dateTime_Minute_4, @__dateTime_Second_5, @__fractions_6, 7) """); } } @@ -1195,19 +1195,19 @@ public virtual void DateTimeOffsetFromParts_compare_with_local_variable() AssertSql( """ -@__dateTimeOffset_0='1919-12-12T10:20:15.0000000+01:30' -@__dateTimeOffset_Month_2='12' -@__dateTimeOffset_Day_3='12' -@__dateTimeOffset_Hour_4='10' -@__dateTimeOffset_Minute_5='20' -@__dateTimeOffset_Second_6='15' -@__fractions_7='5' -@__hourOffset_8='1' -@__minuteOffset_9='30' +@__dateTimeOffset_9='1919-12-12T10:20:15.0000000+01:30' +@__dateTimeOffset_Month_1='12' +@__dateTimeOffset_Day_2='12' +@__dateTimeOffset_Hour_3='10' +@__dateTimeOffset_Minute_4='20' +@__dateTimeOffset_Second_5='15' +@__fractions_6='5' +@__hourOffset_7='1' +@__minuteOffset_8='30' SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__dateTimeOffset_0 > DATETIMEOFFSETFROMPARTS(DATEPART(year, GETDATE()), @__dateTimeOffset_Month_2, @__dateTimeOffset_Day_3, @__dateTimeOffset_Hour_4, @__dateTimeOffset_Minute_5, @__dateTimeOffset_Second_6, @__fractions_7, @__hourOffset_8, @__minuteOffset_9, 7) +WHERE @__dateTimeOffset_9 > DATETIMEOFFSETFROMPARTS(DATEPART(year, GETDATE()), @__dateTimeOffset_Month_1, @__dateTimeOffset_Day_2, @__dateTimeOffset_Hour_3, @__dateTimeOffset_Minute_4, @__dateTimeOffset_Second_5, @__fractions_6, @__hourOffset_7, @__minuteOffset_8, 7) """); } } @@ -1265,15 +1265,15 @@ await AssertCount( AssertSql( """ -@__dateTime_0='1919-12-12T23:20:00.0000000' (DbType = DateTime) -@__dateTime_Month_2='12' -@__dateTime_Day_3='12' -@__dateTime_Hour_4='23' -@__dateTime_Minute_5='20' +@__dateTime_5='1919-12-12T23:20:00.0000000' (DbType = DateTime) +@__dateTime_Month_1='12' +@__dateTime_Day_2='12' +@__dateTime_Hour_3='23' +@__dateTime_Minute_4='20' SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__dateTime_0 > SMALLDATETIMEFROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_2, @__dateTime_Day_3, @__dateTime_Hour_4, @__dateTime_Minute_5) +WHERE @__dateTime_5 > SMALLDATETIMEFROMPARTS(DATEPART(year, GETDATE()), @__dateTime_Month_1, @__dateTime_Day_2, @__dateTime_Hour_3, @__dateTime_Minute_4) """); } @@ -1354,21 +1354,21 @@ FROM [Orders] AS [o] [ConditionalFact] public virtual void DataLength_compare_with_local_variable() { - int? lenght = 100; + int? length = 100; using (var context = CreateContext()) { var count = context.Orders - .Count(c => lenght < EF.Functions.DataLength(c.OrderDate)); + .Count(c => length < EF.Functions.DataLength(c.OrderDate)); Assert.Equal(0, count); AssertSql( """ -@__lenght_0='100' (Nullable = true) +@__length_1='100' (Nullable = true) SELECT COUNT(*) FROM [Orders] AS [o] -WHERE @__lenght_0 < DATALENGTH([o].[OrderDate]) +WHERE @__length_1 < DATALENGTH([o].[OrderDate]) """); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs index f8d5bccc73d..b1476c07a6b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs @@ -1174,11 +1174,7 @@ public override async Task Ternary_should_not_evaluate_both_sides(bool async) AssertSql( """ -@__p_0='none' (Size = 4000) -@__p_1='none' (Size = 4000) -@__p_2='none' (Size = 4000) - -SELECT [c].[CustomerID], @__p_0 AS [Data1], @__p_1 AS [Data2], @__p_2 AS [Data3] +SELECT [c].[CustomerID], N'none' AS [Data1] FROM [Customers] AS [c] """); } @@ -2801,9 +2797,7 @@ public override async Task Null_Coalesce_Short_Circuit(bool async) AssertSql( """ -@__p_0='False' - -SELECT [c0].[CustomerID], [c0].[Address], [c0].[City], [c0].[CompanyName], [c0].[ContactName], [c0].[ContactTitle], [c0].[Country], [c0].[Fax], [c0].[Phone], [c0].[PostalCode], [c0].[Region], @__p_0 AS [Test] +SELECT [c0].[CustomerID], [c0].[Address], [c0].[City], [c0].[CompanyName], [c0].[ContactName], [c0].[ContactTitle], [c0].[Country], [c0].[Fax], [c0].[Phone], [c0].[PostalCode], [c0].[Region], CAST(0 AS bit) AS [Test] FROM ( SELECT DISTINCT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] @@ -5626,11 +5620,11 @@ public override async Task Entity_equality_with_null_coalesce_client_side(bool a AssertSql( """ -@__entity_equality_p_0_CustomerID='ALFKI' (Size = 5) (DbType = StringFixedLength) +@__entity_equality_a_0_CustomerID='ALFKI' (Size = 5) (DbType = StringFixedLength) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] -WHERE [c].[CustomerID] = @__entity_equality_p_0_CustomerID +WHERE [c].[CustomerID] = @__entity_equality_a_0_CustomerID """); } @@ -7131,6 +7125,20 @@ public override void Can_cast_CreateQuery_result_to_IQueryable_T_bug_1730() AssertSql(); } + public override async Task IQueryable_captured_variable() + { + await base.IQueryable_captured_variable(); + + AssertSql( + """ +SELECT COUNT(*) +FROM [Customers] AS [c] +WHERE ( + SELECT COUNT(*) + FROM [Orders] AS [o]) = 2 +"""); + } + public override async Task Multiple_context_instances(bool async) { await base.Multiple_context_instances(async); @@ -7407,14 +7415,14 @@ public override async Task Contains_over_concatenated_column_and_parameter(bool AssertSql( """ -@__someVariable_1='SomeVariable' (Size = 4000) -@__data_0='["ALFKISomeVariable","ANATRSomeVariable","ALFKIX"]' (Size = 4000) +@__someVariable_0='SomeVariable' (Size = 4000) +@__data_1='["ALFKISomeVariable","ANATRSomeVariable","ALFKIX"]' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] -WHERE [c].[CustomerID] + @__someVariable_1 IN ( +WHERE [c].[CustomerID] + @__someVariable_0 IN ( SELECT [d].[value] - FROM OPENJSON(@__data_0) WITH ([value] nvarchar(max) '$') AS [d] + FROM OPENJSON(@__data_1) WITH ([value] nvarchar(max) '$') AS [d] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindWhereQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindWhereQuerySqlServerTest.cs index 7efc8aa0923..86cccb978c6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindWhereQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindWhereQuerySqlServerTest.cs @@ -3129,6 +3129,17 @@ FROM [Customers] AS [c] SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] = N'ALFKI' +""", + // + """ +SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] +FROM [Customers] AS [c] +WHERE [c].[CustomerID] = N'ALFKI' +""", + // + """ +SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] +FROM [Customers] AS [c] """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs index db080f82a63..b9970df7564 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs @@ -503,27 +503,24 @@ public override async Task Preserve_includes_when_applying_skip_take_after_anony AssertSql( """ -SELECT COUNT(*) -FROM [OwnedPerson] AS [o] -""", - // - """ -@__p_1='0' -@__p_2='100' +@__p_0='0' +@__p_1='100' -SELECT [o2].[Id], [o2].[Discriminator], [o2].[Name], [s].[ClientId], [s].[Id], [s].[OrderDate], [s].[OrderClientId], [s].[OrderId], [s].[Id0], [s].[Detail], [o2].[PersonAddress_AddressLine], [o2].[PersonAddress_PlaceType], [o2].[PersonAddress_ZipCode], [o2].[PersonAddress_Country_Name], [o2].[PersonAddress_Country_PlanetId], [o2].[BranchAddress_BranchName], [o2].[BranchAddress_PlaceType], [o2].[BranchAddress_Country_Name], [o2].[BranchAddress_Country_PlanetId], [o2].[LeafBAddress_LeafBType], [o2].[LeafBAddress_PlaceType], [o2].[LeafBAddress_Country_Name], [o2].[LeafBAddress_Country_PlanetId], [o2].[LeafAAddress_LeafType], [o2].[LeafAAddress_PlaceType], [o2].[LeafAAddress_Country_Name], [o2].[LeafAAddress_Country_PlanetId] +SELECT [o3].[Id], [o3].[Discriminator], [o3].[Name], [s].[ClientId], [s].[Id], [s].[OrderDate], [s].[OrderClientId], [s].[OrderId], [s].[Id0], [s].[Detail], [o3].[PersonAddress_AddressLine], [o3].[PersonAddress_PlaceType], [o3].[PersonAddress_ZipCode], [o3].[PersonAddress_Country_Name], [o3].[PersonAddress_Country_PlanetId], [o3].[BranchAddress_BranchName], [o3].[BranchAddress_PlaceType], [o3].[BranchAddress_Country_Name], [o3].[BranchAddress_Country_PlanetId], [o3].[LeafBAddress_LeafBType], [o3].[LeafBAddress_PlaceType], [o3].[LeafBAddress_Country_Name], [o3].[LeafBAddress_Country_PlanetId], [o3].[LeafAAddress_LeafType], [o3].[LeafAAddress_PlaceType], [o3].[LeafAAddress_Country_Name], [o3].[LeafAAddress_Country_PlanetId], [o3].[c] FROM ( - SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] + SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId], ( + SELECT COUNT(*) + FROM [OwnedPerson] AS [o2]) AS [c] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] - OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY -) AS [o2] + OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY +) AS [o3] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON [o0].[ClientId] = [o1].[OrderClientId] AND [o0].[Id] = [o1].[OrderId] -) AS [s] ON [o2].[Id] = [s].[ClientId] -ORDER BY [o2].[Id], [s].[ClientId], [s].[Id], [s].[OrderClientId], [s].[OrderId] +) AS [s] ON [o3].[Id] = [s].[ClientId] +ORDER BY [o3].[Id], [s].[ClientId], [s].[Id], [s].[OrderClientId], [s].[OrderId] """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs index 5e204386f5d..e7fe2079c22 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs @@ -1478,20 +1478,20 @@ public override async Task Nested_contains_with_Lists_and_no_inferred_type_mappi AssertSql( """ -@__ints_1='[1,2,3]' (Size = 4000) -@__strings_0='["one","two","three"]' (Size = 4000) +@__ints_0='[1,2,3]' (Size = 4000) +@__strings_1='["one","two","three"]' (Size = 4000) SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[String], [p].[Strings] FROM [PrimitiveCollectionsEntity] AS [p] WHERE CASE WHEN [p].[Int] IN ( SELECT [i].[value] - FROM OPENJSON(@__ints_1) WITH ([value] int '$') AS [i] + FROM OPENJSON(@__ints_0) WITH ([value] int '$') AS [i] ) THEN N'one' ELSE N'two' END IN ( SELECT [s].[value] - FROM OPENJSON(@__strings_0) WITH ([value] nvarchar(max) '$') AS [s] + FROM OPENJSON(@__strings_1) WITH ([value] nvarchar(max) '$') AS [s] ) """); } @@ -1502,20 +1502,20 @@ public override async Task Nested_contains_with_arrays_and_no_inferred_type_mapp AssertSql( """ -@__ints_1='[1,2,3]' (Size = 4000) -@__strings_0='["one","two","three"]' (Size = 4000) +@__ints_0='[1,2,3]' (Size = 4000) +@__strings_1='["one","two","three"]' (Size = 4000) SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[String], [p].[Strings] FROM [PrimitiveCollectionsEntity] AS [p] WHERE CASE WHEN [p].[Int] IN ( SELECT [i].[value] - FROM OPENJSON(@__ints_1) WITH ([value] int '$') AS [i] + FROM OPENJSON(@__ints_0) WITH ([value] int '$') AS [i] ) THEN N'one' ELSE N'two' END IN ( SELECT [s].[value] - FROM OPENJSON(@__strings_0) WITH ([value] nvarchar(max) '$') AS [s] + FROM OPENJSON(@__strings_1) WITH ([value] nvarchar(max) '$') AS [s] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/QueryFilterFuncletizationSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/QueryFilterFuncletizationSqlServerTest.cs index f31ad32c55e..eb1b12e52e1 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/QueryFilterFuncletizationSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/QueryFilterFuncletizationSqlServerTest.cs @@ -225,29 +225,29 @@ public override void DbContext_property_based_filter_does_not_short_circuit() AssertSql( """ -@__ef_filter__p_0='False' -@__ef_filter__IsModerated_1='True' (Nullable = true) +@__ef_filter__p_1='False' +@__ef_filter__IsModerated_0='True' (Nullable = true) SELECT [s].[Id], [s].[IsDeleted], [s].[IsModerated] FROM [ShortCircuitFilter] AS [s] -WHERE [s].[IsDeleted] = CAST(0 AS bit) AND (@__ef_filter__p_0 = CAST(1 AS bit) OR @__ef_filter__IsModerated_1 = [s].[IsModerated]) +WHERE [s].[IsDeleted] = CAST(0 AS bit) AND (@__ef_filter__p_1 = CAST(1 AS bit) OR @__ef_filter__IsModerated_0 = [s].[IsModerated]) """, // """ -@__ef_filter__p_0='False' -@__ef_filter__IsModerated_1='False' (Nullable = true) +@__ef_filter__p_1='False' +@__ef_filter__IsModerated_0='False' (Nullable = true) SELECT [s].[Id], [s].[IsDeleted], [s].[IsModerated] FROM [ShortCircuitFilter] AS [s] -WHERE [s].[IsDeleted] = CAST(0 AS bit) AND (@__ef_filter__p_0 = CAST(1 AS bit) OR @__ef_filter__IsModerated_1 = [s].[IsModerated]) +WHERE [s].[IsDeleted] = CAST(0 AS bit) AND (@__ef_filter__p_1 = CAST(1 AS bit) OR @__ef_filter__IsModerated_0 = [s].[IsModerated]) """, // """ -@__ef_filter__p_0='True' +@__ef_filter__p_1='True' SELECT [s].[Id], [s].[IsDeleted], [s].[IsModerated] FROM [ShortCircuitFilter] AS [s] -WHERE [s].[IsDeleted] = CAST(0 AS bit) AND @__ef_filter__p_0 = CAST(1 AS bit) +WHERE [s].[IsDeleted] = CAST(0 AS bit) AND @__ef_filter__p_1 = CAST(1 AS bit) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPCGearsOfWarQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPCGearsOfWarQuerySqlServerTest.cs index 143c3932380..0fc343b9afc 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPCGearsOfWarQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPCGearsOfWarQuerySqlServerTest.cs @@ -13692,9 +13692,9 @@ public override async Task Nested_contains_with_enum(bool async) AssertSql( """ -@__ranks_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ranks_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [u].[Nickname], [u].[SquadId], [u].[AssignedCityName], [u].[CityOfBirthName], [u].[FullName], [u].[HasSoulPatch], [u].[LeaderNickname], [u].[LeaderSquadId], [u].[Rank], [u].[Discriminator] FROM ( @@ -13707,31 +13707,31 @@ FROM [Officers] AS [o] WHERE CASE WHEN [u].[Rank] IN ( SELECT [r].[value] - FROM OPENJSON(@__ranks_1) WITH ([value] int '$') AS [r] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ranks_0) WITH ([value] int '$') AS [r] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """, // """ -@__ammoTypes_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ammoTypes_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE CASE WHEN [w].[AmmunitionType] IN ( SELECT [a].[value] - FROM OPENJSON(@__ammoTypes_1) WITH ([value] int '$') AS [a] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ammoTypes_0) WITH ([value] int '$') AS [a] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPTGearsOfWarQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPTGearsOfWarQuerySqlServerTest.cs index 348554a72a3..9c15dc1582b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPTGearsOfWarQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPTGearsOfWarQuerySqlServerTest.cs @@ -11696,9 +11696,9 @@ public override async Task Nested_contains_with_enum(bool async) AssertSql( """ -@__ranks_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ranks_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], CASE WHEN [o].[Nickname] IS NOT NULL THEN N'Officer' @@ -11708,31 +11708,31 @@ FROM [Gears] AS [g] WHERE CASE WHEN [g].[Rank] IN ( SELECT [r].[value] - FROM OPENJSON(@__ranks_1) WITH ([value] int '$') AS [r] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ranks_0) WITH ([value] int '$') AS [r] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """, // """ -@__ammoTypes_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ammoTypes_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE CASE WHEN [w].[AmmunitionType] IN ( SELECT [a].[value] - FROM OPENJSON(@__ammoTypes_1) WITH ([value] int '$') AS [a] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ammoTypes_0) WITH ([value] int '$') AS [a] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerTest.cs index 00d0d6aeb89..f80589b4848 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerTest.cs @@ -10265,40 +10265,40 @@ public override async Task Nested_contains_with_enum(bool async) AssertSql( """ -@__ranks_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ranks_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[PeriodEnd], [g].[PeriodStart], [g].[Rank] FROM [Gears] FOR SYSTEM_TIME AS OF '2010-01-01T00:00:00.0000000' AS [g] WHERE CASE WHEN [g].[Rank] IN ( SELECT [r].[value] - FROM OPENJSON(@__ranks_1) WITH ([value] int '$') AS [r] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ranks_0) WITH ([value] int '$') AS [r] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """, // """ -@__ammoTypes_1='[1]' (Size = 4000) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) +@__ammoTypes_0='[1]' (Size = 4000) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0a47bcb7-a1cb-4345-8944-c58f82d6aac7","5f221fb9-66f4-442a-92c9-d97ed5989cc7"]' (Size = 4000) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[PeriodEnd], [w].[PeriodStart], [w].[SynergyWithId] FROM [Weapons] FOR SYSTEM_TIME AS OF '2010-01-01T00:00:00.0000000' AS [w] WHERE CASE WHEN [w].[AmmunitionType] IN ( SELECT [a].[value] - FROM OPENJSON(@__ammoTypes_1) WITH ([value] int '$') AS [a] - ) THEN @__key_2 - ELSE @__key_2 + FROM OPENJSON(@__ammoTypes_0) WITH ([value] int '$') AS [a] + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT [k].[value] - FROM OPENJSON(@__keys_0) WITH ([value] uniqueidentifier '$') AS [k] + FROM OPENJSON(@__keys_2) WITH ([value] uniqueidentifier '$') AS [k] ) """); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs b/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs index 01b6599f783..6086f0132d3 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs @@ -206,12 +206,12 @@ public override void Scalar_Function_Let_Nested_Static() AssertSql( """ -@__starCount_0='3' -@__customerId_1='1' +@__starCount_1='3' +@__customerId_0='1' -SELECT TOP(2) [c].[LastName], [dbo].[StarValue](@__starCount_0, [dbo].[CustomerOrderCount](@__customerId_1)) AS [OrderCount] +SELECT TOP(2) [c].[LastName], [dbo].[StarValue](@__starCount_1, [dbo].[CustomerOrderCount](@__customerId_0)) AS [OrderCount] FROM [Customers] AS [c] -WHERE [c].[Id] = @__customerId_1 +WHERE [c].[Id] = @__customerId_0 """); } @@ -546,12 +546,12 @@ public override void Scalar_Function_Let_Nested_Instance() AssertSql( """ -@__starCount_1='3' -@__customerId_2='1' +@__starCount_2='3' +@__customerId_1='1' -SELECT TOP(2) [c].[LastName], [dbo].[StarValue](@__starCount_1, [dbo].[CustomerOrderCount](@__customerId_2)) AS [OrderCount] +SELECT TOP(2) [c].[LastName], [dbo].[StarValue](@__starCount_2, [dbo].[CustomerOrderCount](@__customerId_1)) AS [OrderCount] FROM [Customers] AS [c] -WHERE [c].[Id] = @__customerId_2 +WHERE [c].[Id] = @__customerId_1 """); } diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs index 251f4eafa97..c4c8ab796ee 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs @@ -9735,40 +9735,40 @@ public override async Task Nested_contains_with_enum(bool async) AssertSql( """ -@__ranks_1='[1]' (Size = 3) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0A47BCB7-A1CB-4345-8944-C58F82D6AAC7","5F221FB9-66F4-442A-92C9-D97ED5989CC7"]' (Size = 79) +@__ranks_0='[1]' (Size = 3) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0A47BCB7-A1CB-4345-8944-C58F82D6AAC7","5F221FB9-66F4-442A-92C9-D97ED5989CC7"]' (Size = 79) SELECT "g"."Nickname", "g"."SquadId", "g"."AssignedCityName", "g"."CityOfBirthName", "g"."Discriminator", "g"."FullName", "g"."HasSoulPatch", "g"."LeaderNickname", "g"."LeaderSquadId", "g"."Rank" FROM "Gears" AS "g" WHERE CASE WHEN "g"."Rank" IN ( SELECT "r"."value" - FROM json_each(@__ranks_1) AS "r" - ) THEN @__key_2 - ELSE @__key_2 + FROM json_each(@__ranks_0) AS "r" + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT "k"."value" - FROM json_each(@__keys_0) AS "k" + FROM json_each(@__keys_2) AS "k" ) """, // """ -@__ammoTypes_1='[1]' (Size = 3) -@__key_2='5f221fb9-66f4-442a-92c9-d97ed5989cc7' -@__keys_0='["0A47BCB7-A1CB-4345-8944-C58F82D6AAC7","5F221FB9-66F4-442A-92C9-D97ED5989CC7"]' (Size = 79) +@__ammoTypes_0='[1]' (Size = 3) +@__key_1='5f221fb9-66f4-442a-92c9-d97ed5989cc7' +@__keys_2='["0A47BCB7-A1CB-4345-8944-C58F82D6AAC7","5F221FB9-66F4-442A-92C9-D97ED5989CC7"]' (Size = 79) SELECT "w"."Id", "w"."AmmunitionType", "w"."IsAutomatic", "w"."Name", "w"."OwnerFullName", "w"."SynergyWithId" FROM "Weapons" AS "w" WHERE CASE WHEN "w"."AmmunitionType" IN ( SELECT "a"."value" - FROM json_each(@__ammoTypes_1) AS "a" - ) THEN @__key_2 - ELSE @__key_2 + FROM json_each(@__ammoTypes_0) AS "a" + ) THEN @__key_1 + ELSE @__key_1 END IN ( SELECT "k"."value" - FROM json_each(@__keys_0) AS "k" + FROM json_each(@__keys_2) AS "k" ) """); } diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs index 4542ee4027f..6309949b328 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs @@ -1343,20 +1343,20 @@ public override async Task Nested_contains_with_Lists_and_no_inferred_type_mappi AssertSql( """ -@__ints_1='[1,2,3]' (Size = 7) -@__strings_0='["one","two","three"]' (Size = 21) +@__ints_0='[1,2,3]' (Size = 7) +@__strings_1='["one","two","three"]' (Size = 21) SELECT "p"."Id", "p"."Bool", "p"."Bools", "p"."DateTime", "p"."DateTimes", "p"."Enum", "p"."Enums", "p"."Int", "p"."Ints", "p"."NullableInt", "p"."NullableInts", "p"."NullableString", "p"."NullableStrings", "p"."String", "p"."Strings" FROM "PrimitiveCollectionsEntity" AS "p" WHERE CASE WHEN "p"."Int" IN ( SELECT "i"."value" - FROM json_each(@__ints_1) AS "i" + FROM json_each(@__ints_0) AS "i" ) THEN 'one' ELSE 'two' END IN ( SELECT "s"."value" - FROM json_each(@__strings_0) AS "s" + FROM json_each(@__strings_1) AS "s" ) """); } @@ -1367,22 +1367,22 @@ public override async Task Nested_contains_with_arrays_and_no_inferred_type_mapp AssertSql( """ - @__ints_1='[1,2,3]' (Size = 7) - @__strings_0='["one","two","three"]' (Size = 21) +@__ints_0='[1,2,3]' (Size = 7) +@__strings_1='["one","two","three"]' (Size = 21) - SELECT "p"."Id", "p"."Bool", "p"."Bools", "p"."DateTime", "p"."DateTimes", "p"."Enum", "p"."Enums", "p"."Int", "p"."Ints", "p"."NullableInt", "p"."NullableInts", "p"."NullableString", "p"."NullableStrings", "p"."String", "p"."Strings" - FROM "PrimitiveCollectionsEntity" AS "p" - WHERE CASE - WHEN "p"."Int" IN ( - SELECT "i"."value" - FROM json_each(@__ints_1) AS "i" - ) THEN 'one' - ELSE 'two' - END IN ( - SELECT "s"."value" - FROM json_each(@__strings_0) AS "s" - ) - """); +SELECT "p"."Id", "p"."Bool", "p"."Bools", "p"."DateTime", "p"."DateTimes", "p"."Enum", "p"."Enums", "p"."Int", "p"."Ints", "p"."NullableInt", "p"."NullableInts", "p"."NullableString", "p"."NullableStrings", "p"."String", "p"."Strings" +FROM "PrimitiveCollectionsEntity" AS "p" +WHERE CASE + WHEN "p"."Int" IN ( + SELECT "i"."value" + FROM json_each(@__ints_0) AS "i" + ) THEN 'one' + ELSE 'two' +END IN ( + SELECT "s"."value" + FROM json_each(@__strings_1) AS "s" +) +"""); } [ConditionalTheory]
`Select` projection with an (uncorrelated) subquery produces two separate SQL queries A `Select` projection with an (uncorrelated) subquery seems to produce two separate SQL queries, which is not what I expect as a developer. For example: ```csharp IQueryable<Employee> allEmployees = context .Employees .Where(x => x.Department == "Engineering"); Employee[] result = allEmployees .Where(x => x.Salary > 1000) .Select(e => new { Employee = e, TotalCount = allEmployees.Count() }) .Skip(2).Take(10) .ToArray(); ``` produces: ```sql info: Executed DbCommand (16ms) [...] SELECT COUNT(*) FROM [Employees] AS [e] WHERE [e].[Department] = N'Engineering' info: Executed DbCommand (26ms) [...] SELECT [e].[Id], [e].[Department], [e].[Manager], [e].[Name], [e].[Salary], @__Count_0 AS [TotalCount] FROM [Employees] AS [e] WHERE [e].[Department] = N'Engineering' AND [e].[Salary] > 1000.0 ORDER BY (SELECT 1) OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY ``` Can I somehow force EF to combine these two queries into one (which is what I expect as a developer when I write the above query): ```sql SELECT [e].[Id], [e].[Department], [e].[Manager], [e].[Name], [e].[Salary], ( SELECT COUNT(*) FROM [Employees] AS [e] WHERE [e].[Department] = N'Engineering') AS [TotalCount] FROM [Employees] AS [e] WHERE [e].[Department] = N'Engineering' AND [e].[Salary] > 1000.0 ORDER BY (SELECT 1) OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY ``` In my real application the query is quite complex (with filters and DISTINCTs) and it is measurable faster to combine the two (I guess because SQL Server can reuse quite some intermediate query results). But there might also be other reasons, why developers want to combine the two queries, for example if there are hard consistency requirements. Here is a [.NET Fiddle](https://dotnetfiddle.net/rVnLzy) with full repro.
null
2024-02-15T15:59:53Z
0.1
['Microsoft.EntityFrameworkCore.Query.NorthwindMiscellaneousQueryCosmosTest.Select_take_long_count']
[]
dotnet/efcore
dotnet__efcore-32613
b01ea2fa816afba9834229b3b12bfceacde2f15c
diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs index bbeb7ff3724..49dc290f878 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs @@ -320,7 +320,7 @@ private IEnumerable<sqlite3_stmt> GetStatements() ? PrepareAndEnumerateStatements() : _preparedStatements) { - var boundParams = _parameters?.Bind(stmt) ?? 0; + var boundParams = _parameters?.Bind(stmt, Connection!.Handle!) ?? 0; if (expectedParams != boundParams) { diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs index e71073b8300..113d490ef6c 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs @@ -203,7 +203,7 @@ public virtual void ResetSqliteType() _sqliteType = null; } - internal bool Bind(sqlite3_stmt stmt) + internal bool Bind(sqlite3_stmt stmt, sqlite3 handle) { if (string.IsNullOrEmpty(ParameterName)) { @@ -222,7 +222,7 @@ internal bool Bind(sqlite3_stmt stmt) throw new InvalidOperationException(Resources.RequiresSet(nameof(Value))); } - new SqliteParameterBinder(stmt, index, _value, _size, _sqliteType).Bind(); + new SqliteParameterBinder(stmt, handle, index, _value, _size, _sqliteType).Bind(); return true; } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs index ffbaefafcef..214bdb3e3cc 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs @@ -10,13 +10,15 @@ namespace Microsoft.Data.Sqlite internal class SqliteParameterBinder : SqliteValueBinder { private readonly sqlite3_stmt _stmt; + private readonly sqlite3 _handle; private readonly int _index; private readonly int? _size; - public SqliteParameterBinder(sqlite3_stmt stmt, int index, object value, int? size, SqliteType? sqliteType) + public SqliteParameterBinder(sqlite3_stmt stmt, sqlite3 handle, int index, object value, int? size, SqliteType? sqliteType) : base(value, sqliteType) { _stmt = stmt; + _handle = handle; _index = index; _size = size; } @@ -30,26 +32,43 @@ protected override void BindBlob(byte[] value) Array.Copy(value, blob, _size.Value); } - sqlite3_bind_blob(_stmt, _index, blob); + var rc = sqlite3_bind_blob(_stmt, _index, blob); + SqliteException.ThrowExceptionForRC(rc, _handle); } protected override void BindDoubleCore(double value) - => sqlite3_bind_double(_stmt, _index, value); + { + var rc = sqlite3_bind_double(_stmt, _index, value); + + SqliteException.ThrowExceptionForRC(rc, _handle); + } protected override void BindInt64(long value) - => sqlite3_bind_int64(_stmt, _index, value); + { + var rc = sqlite3_bind_int64(_stmt, _index, value); + + SqliteException.ThrowExceptionForRC(rc, _handle); + } protected override void BindNull() - => sqlite3_bind_null(_stmt, _index); + { + var rc = sqlite3_bind_null(_stmt, _index); + + SqliteException.ThrowExceptionForRC(rc, _handle); + } protected override void BindText(string value) - => sqlite3_bind_text( + { + var rc = sqlite3_bind_text( _stmt, _index, ShouldTruncate(value.Length) ? value.Substring(0, _size!.Value) : value); + SqliteException.ThrowExceptionForRC(rc, _handle); + } + private bool ShouldTruncate(int length) => _size.HasValue && length > _size.Value diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs index 6ec9439a7a3..5688af4f6d0 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs @@ -325,12 +325,12 @@ protected override void SetParameter(int index, DbParameter value) protected override void SetParameter(string parameterName, DbParameter value) => SetParameter(IndexOfChecked(parameterName), value); - internal int Bind(sqlite3_stmt stmt) + internal int Bind(sqlite3_stmt stmt, sqlite3 handle) { var bound = 0; foreach (var parameter in _parameters) { - if (parameter.Bind(stmt)) + if (parameter.Bind(stmt, handle)) { bound++; }
diff --git a/test/Microsoft.Data.Sqlite.Tests/SqliteCommandTest.cs b/test/Microsoft.Data.Sqlite.Tests/SqliteCommandTest.cs index 02a7951defe..aab6d37a187 100644 --- a/test/Microsoft.Data.Sqlite.Tests/SqliteCommandTest.cs +++ b/test/Microsoft.Data.Sqlite.Tests/SqliteCommandTest.cs @@ -15,6 +15,62 @@ namespace Microsoft.Data.Sqlite; public class SqliteCommandTest { + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Correct_error_code_is_returned_when_parameter_is_too_long(bool async) // Issue #27597 + { + using var connection = new SqliteConnection("Data Source=:memory:"); + + if (async) + { + await connection.OpenAsync(); + } + else + { + connection.Open(); + } + + using var command = connection.CreateCommand(); + command.CommandText = """ +CREATE TABLE "Products" ( + "Id" INTEGER NOT NULL CONSTRAINT "PK_Products" PRIMARY KEY AUTOINCREMENT, + "Name" TEXT NOT NULL + ); +"""; + _ = async ? await command.ExecuteNonQueryAsync() : command.ExecuteNonQuery(); + + sqlite3_limit(connection.Handle!, 0, 10); + + command.CommandText = @"INSERT INTO ""Products"" (""Name"") VALUES (@p0);"; + command.Parameters.Add("@p0", SqliteType.Text); + command.Parameters[0].Value = new string('A', 15); + + try + { + _ = async ? await command.ExecuteReaderAsync() : command.ExecuteReader(); + } + catch (SqliteException ex) + { + Assert.Equal(18, ex.SqliteErrorCode); + } + finally + { +#if NET5_0_OR_GREATER + if (async) + { + await connection.CloseAsync(); + } + else + { + connection.Close(); + } +#else + connection.Close(); +#endif + } + } + [Fact] public void Ctor_sets_values() {
Wrong ErrorCode reported by SqliteException When using `sqlite3_limit` to limit length of string or blob (`SQLITE_LIMIT_LENGTH` from https://www.sqlite.org/c3ref/c_limit_attached.html) and running an insert statement with value larger than the limit, the `SqliteException` has wrong `SqliteErrorCode` and `SqliteExtendedErrorCode` ### Include your code ```csharp var connection = new SqliteConnection("Data Source=sqlite_test.db;"); connection.Open(); var command = connection.CreateCommand(); command.CommandText = @"CREATE TABLE ""Products"" ( ""Id"" INTEGER NOT NULL CONSTRAINT ""PK_Products"" PRIMARY KEY AUTOINCREMENT, ""Name"" TEXT NOT NULL );"; command.ExecuteNonQuery(); var limit = SetLimit(connection.Handle, 0, 10); command.CommandText = @"INSERT INTO ""Products"" (""Name"") VALUES (@p0);"; command.Parameters.Add("@p0", SqliteType.Text); command.Parameters[0].Value = new string('A', 15); try { command.ExecuteReader(); } catch (SqliteException ex) { Console.WriteLine($"Sqlite error: {ex.SqliteErrorCode} {ex.SqliteExtendedErrorCode}"); } finally { connection.Close(); } [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_limit")] static extern int SetLimit(sqlite3 db, int id, int newVal); ``` This prints 19 and 1299 (`SQLITE_CONSTRAINT` and `SQLITE_CONSTRAINT_NOTNULL` respectively) instead of printing 18 and 18 (`SQLITE_TOOBIG`) If I put the value directly in the SQL statement the correct error code is reported: `command.CommandText = @"INSERT INTO ""Products"" (""Name"") VALUES ('AAAAAAAAAAAAAAA');";` Also, when using EF Core and SQLite together the behavior in EF Core 3.1.1 and Microsoft.Data.SQLite was that the insert statement was failing with the correct error code (`SQLITE_TOOBIG`). I have a unit test that verifies that behavior: https://github.com/Giorgi/EntityFramework.Exceptions/blob/main/EntityFramework.Exceptions.Tests/SqliteTests.cs#L24 but the test fails when I upgrade to EF Core 6. Did the interaction between EF Core and SQLite provider change so drasticly between these versions that result in the new behavior? For example, did the EF Core 3 not use parameterized insert statements or is there a change in the way parameters are passed to the SQLite driver? Finally, the SQLite shell works as expected: ![image](https://user-images.githubusercontent.com/580749/157325636-b8d3f5a8-b611-40d7-9bd9-bf19320bbcc3.png) ### Version information Microsoft.Data.Sqlite version: 6.0.3 Target framework: .Net 6 Operating system: Windows
Also, if I explicitly set the parameter size to zero I get the `SQLITE_TOOBIG` error: ```csharp command.CommandText = @"INSERT INTO ""Products"" (""Name"") VALUES (@p0);"; command.Parameters.Add("@p0", SqliteType.Text, 0); command.Parameters[0].Value = new string('A', 15); ``` The error code is `SQLITE_CONSTRAINT` and `SQLITE_CONSTRAINT_NOTNULL` in 3.1.3 version of the provider but when using EF Core, the error code is `SQLITE_TOOBIG` so something must have changed in the way EF Core and Microsoft.Data.SQLite interact. @Giorgi Are you using the same version of the native SQLite library and the PCLraw package in both cases? Or are these also changing with EF version? @ajcvickers I use the version that the Microsoft.Data.SQLite pulls as a dependency but I'm pretty sure that this isn't caused by SQLite because when I tried to reproduce it with plain ADO.NET with the version of `Microsoft.Data.SQLite` that is used by my test I couldn't get it to throw SqliteException with ErrorCode equal to `SQLITE_TOOBIG`. The only case when I can make SQLite throw `SQLITE_TOOBIG` is when I set the parameter size to zero in the second comment. To summarize, the behavior does not change when using plain ADO.NET between the old version and new version of Microsoft.Data.SQLite. The behavior only changes depending how I set parameter or when I upgrade between EF Core versions I tried doing running the same ado.net code with [System.Data.SQLite.Core](https://www.nuget.org/packages/System.Data.SQLite.Core/) and I get `string or blob too big` error even if I do not set the parameter size explicitly: ```cs var connection = new SQLiteConnection("Data Source=sqlite_test.db;"); connection.Open(); var command = connection.CreateCommand(); command.CommandText = @"CREATE TABLE ""Products"" ( ""Id"" INTEGER NOT NULL CONSTRAINT ""PK_Products"" PRIMARY KEY AUTOINCREMENT, ""Name"" TEXT NOT NULL );"; command.ExecuteNonQuery(); connection.SetLimitOption(SQLiteLimitOpsEnum.SQLITE_LIMIT_LENGTH, 10); command.CommandText = @"INSERT INTO ""Products"" (""Name"") VALUES (@p0);"; command.Parameters.Add("@p0", DbType.String); command.Parameters[0].Value = new string('A', 15); try { command.ExecuteReader(); } catch (SQLiteException ex) { Console.WriteLine($"Sqlite error: {ex.ErrorCode} "); } finally { connection.Close(); } ``` This results in **SQLite error: 18** If I do the same with [Microsoft.Data.Sqlite.Core](https://www.nuget.org/packages/Microsoft.Data.Sqlite.Core/) I get `SQLITE_CONSTRAINT` and `SQLITE_CONSTRAINT_NOTNULL` @bricelam Any update on this bug? I haven't looked into it yet. I'm focusing on my 7.0 enhancements right now. Will shift my focus to bugs closer to the end of the release.
2023-12-14T11:39:24Z
0.1
['Microsoft.Data.Sqlite.SqliteCommandTest.Correct_error_code_is_returned_when_parameter_is_too_long']
['Microsoft.Data.Sqlite.SqliteCommandTest.Prepare_throws_when_command_text_contains_dependent_commands', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_connection_closed', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteNonQuery_throws_when_busy_with_returning', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_DBNull_when_null', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_processes_dependent_commands', 'Microsoft.Data.Sqlite.SqliteCommandTest.Cancel_does_nothing', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandTimeout_defaults_to_30', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_on_error', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_long_when_multiple_rows', 'Microsoft.Data.Sqlite.SqliteCommandTest.Parameters_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_null_when_empty', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_busy_with_returning_while_draining', 'Microsoft.Data.Sqlite.SqliteCommandTest.Prepare_throws_when_connection_closed', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_long_when_integer', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_supports_CloseConnection', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_throws_when_busy_with_returning', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_on_EXPLAIN', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_long_when_multiple_columns', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandTimeout_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_skips_DML_statements', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_retries_when_locked', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_when_no_command_text', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandText_defaults_to_empty', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteNonQuery_works_when_no_command_text', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandText_throws_when_set_when_open_reader', 'Microsoft.Data.Sqlite.SqliteCommandTest.Ctor_sets_values', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_null_when_non_query', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandType_text_by_default', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteNonQuery_throws_when_connection_closed', 'Microsoft.Data.Sqlite.SqliteCommandTest.Prepare_throws_when_no_connection', 'Microsoft.Data.Sqlite.SqliteCommandTest.Connection_can_be_unset', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_string_when_text', 'Microsoft.Data.Sqlite.SqliteCommandTest.CreateParameter_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_parameter_unset', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteNonQuery_throws_when_no_connection', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_supports_SingleRow', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_busy_with_returning', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_transaction_required', 'Microsoft.Data.Sqlite.SqliteCommandTest.Can_get_results_from_nonreadonly_statements', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_supports_SequentialAccess', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_when_subsequent_DML', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_throws_when_no_command_text', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandTimeout_defaults_to_connection_string', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_throws_when_no_connection', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_long_when_batching', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_reader_open', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_when_comments', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_when_trailing_comments', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_retries_when_busy', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_transaction_mismatched', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteNonQuery_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_honors_CommandTimeout', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_byte_array_when_blob', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_works_after_failure', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_throws_when_connection_closed', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteScalar_returns_double_when_real', 'Microsoft.Data.Sqlite.SqliteCommandTest.Multiple_command_executes_works', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandTimeout_defaults_to_connection', 'Microsoft.Data.Sqlite.SqliteCommandTest.Prepare_works_when_no_command_text', 'Microsoft.Data.Sqlite.SqliteCommandTest.Connection_throws_when_set_when_open_reader', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_binds_parameters', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandType_validates_value', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_supports_SingleResult', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_transaction_completed_externally', 'Microsoft.Data.Sqlite.SqliteCommandTest.CommandText_coalesces_to_empty', 'Microsoft.Data.Sqlite.SqliteCommandTest.ExecuteReader_throws_when_no_connection']
dotnet/efcore
dotnet__efcore-27291
8a8105d31879d435271848a595d5b7ec31ef6ce5
diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs index 265634b0100..e71073b8300 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs @@ -200,7 +200,7 @@ public override void ResetDbType() public virtual void ResetSqliteType() { DbType = DbType.String; - SqliteType = SqliteType.Text; + _sqliteType = null; } internal bool Bind(sqlite3_stmt stmt) diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs index 3e7ac998b8a..137a50fe080 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs @@ -246,6 +246,10 @@ public virtual void Bind() { typeof(char), SqliteType.Text }, { typeof(DateTime), SqliteType.Text }, { typeof(DateTimeOffset), SqliteType.Text }, +#if NET6_0_OR_GREATER + { typeof(DateOnly), SqliteType.Text }, + { typeof(TimeOnly), SqliteType.Text }, +#endif { typeof(DBNull), SqliteType.Text }, { typeof(decimal), SqliteType.Text }, { typeof(double), SqliteType.Real }, @@ -255,7 +259,7 @@ public virtual void Bind() { typeof(long), SqliteType.Integer }, { typeof(sbyte), SqliteType.Integer }, { typeof(short), SqliteType.Integer }, - { typeof(string), SqliteType.Integer }, + { typeof(string), SqliteType.Text }, { typeof(TimeSpan), SqliteType.Text }, { typeof(uint), SqliteType.Integer }, { typeof(ulong), SqliteType.Integer },
diff --git a/test/Microsoft.Data.Sqlite.Tests/SqliteParameterTest.cs b/test/Microsoft.Data.Sqlite.Tests/SqliteParameterTest.cs index 1779cad3e0b..e7758f21dac 100644 --- a/test/Microsoft.Data.Sqlite.Tests/SqliteParameterTest.cs +++ b/test/Microsoft.Data.Sqlite.Tests/SqliteParameterTest.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Collections.Generic; using System.Data; using System.Data.Common; using Microsoft.Data.Sqlite.Properties; @@ -93,6 +94,21 @@ public void SqliteType_defaults_to_text() Assert.Equal(SqliteType.Text, new SqliteParameter().SqliteType); } + [Theory] + [MemberData(nameof(TypesData))] + public void SqliteType_is_inferred_from_value(object value, SqliteType expectedType) + { + var parameter = new SqliteParameter { Value = value }; + Assert.Equal(expectedType, parameter.SqliteType); + } + + [Fact] + public void SqliteType_overrides_inferred_value() + { + var parameter = new SqliteParameter { Value = 'A', SqliteType = SqliteType.Integer }; + Assert.Equal(SqliteType.Integer, parameter.SqliteType); + } + [Fact] public void Direction_input_by_default() { @@ -128,6 +144,16 @@ public void ResetSqliteType_works() Assert.Equal(SqliteType.Text, parameter.SqliteType); } + [Fact] + public void ResetSqliteType_works_when_value() + { + var parameter = new SqliteParameter { Value = new byte[0], SqliteType = SqliteType.Text }; + + parameter.ResetSqliteType(); + + Assert.Equal(SqliteType.Blob, parameter.SqliteType); + } + [Fact] public void Bind_requires_set_name() { @@ -557,6 +583,36 @@ public void Add_range_of_parameters_using_DbCommand_base_class() } } + public static IEnumerable<object[]> TypesData + => new List<object[]> + { + new object[] { default(DateTime), SqliteType.Text }, + new object[] { default(DateTimeOffset), SqliteType.Text }, + new object[] { DBNull.Value, SqliteType.Text }, + new object[] { 0m, SqliteType.Text }, + new object[] { default(Guid), SqliteType.Text }, + new object[] { default(TimeSpan), SqliteType.Text }, + new object[] { default(TimeSpan), SqliteType.Text }, +#if NET6_0_OR_GREATER + new object[] { default(DateOnly), SqliteType.Text }, + new object[] { default(TimeOnly), SqliteType.Text }, +#endif + new object[] { 'A', SqliteType.Text }, + new object[] { "", SqliteType.Text }, + new object[] { false, SqliteType.Integer }, + new object[] { (byte)0, SqliteType.Integer }, + new object[] { 0, SqliteType.Integer }, + new object[] { 0L, SqliteType.Integer }, + new object[] { (sbyte)0, SqliteType.Integer }, + new object[] { (short)0, SqliteType.Integer }, + new object[] { 0u, SqliteType.Integer }, + new object[] { 0ul, SqliteType.Integer }, + new object[] { (ushort)0, SqliteType.Integer }, + new object[] { 0.0, SqliteType.Real }, + new object[] { 0f, SqliteType.Real }, + new object[] { new byte[0], SqliteType.Blob }, + }; + private enum MyEnum { One = 1
Correct SqliteType inference from string, DateOnly, TimeOnly Microsoft.Data.Sqlite 6.0.1 TargetFramework net6.0-windows 当我创建一个字符串类型的SqliteParameter时,我查询它的类型,得到的类型信息是 “SqliteType.Integer” ```C# var p = new Microsoft.Data.Sqlite.SqliteParameter("Name","123"); ``` 后来我在源码中定位到了以下位置,这就有点不合适了吧 https://github.com/dotnet/efcore/blob/8144d50ec0d15b87c35a9a3a425b1faadafb87f1/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs#L240-L263
Google Translate: ``` When I create a SqliteParameter of type string, I query its type, and the type info I get is "SqliteType.Integer" ... Later, I located the following location in the source code, which is a bit inappropriate. ``` /cc @bricelam
2022-01-26T23:05:50Z
0.2
['Microsoft.Data.Sqlite.SqliteParameterTest.SqliteType_is_inferred_from_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.SqliteType_overrides_inferred_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.ResetSqliteType_works_when_value']
['Microsoft.Data.Sqlite.SqliteParameterTest.Add_range_of_parameters_using_DbCommand_base_class', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_Guid_with_SqliteType_Blob', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateOnly', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_does_not_require_prefix', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_with_restricted_size_works_on_blob_values', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DBNull', 'Microsoft.Data.Sqlite.SqliteParameterTest.ParameterName_coalesces_to_empty', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_byte_array', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_is_noop_on_unknown_parameter', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_throws_for_ambiguous_parameters', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateTime', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_with_sentinel_size_works_on_blob_values', 'Microsoft.Data.Sqlite.SqliteParameterTest.Direction_input_by_default', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_TimeOnly_with_milliseconds', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateOnly_with_SqliteType_Real', 'Microsoft.Data.Sqlite.SqliteParameterTest.SqliteType_defaults_to_text', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_throws_for_nan', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_decimal', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_Nullable', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_throws_when_unknown', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_binds_string_values_without_embedded_nulls', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateTimeOffset', 'Microsoft.Data.Sqlite.SqliteParameterTest.ResetSqliteType_works', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_TimeSpan_with_SqliteType_Real', 'Microsoft.Data.Sqlite.SqliteParameterTest.Size_validates_argument', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_TimeOnly_with_SqliteType_Real', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_Enum', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_requires_set_name', 'Microsoft.Data.Sqlite.SqliteParameterTest.DbType_defaults_to_string', 'Microsoft.Data.Sqlite.SqliteParameterTest.ParameterName_defaults_to_empty', 'Microsoft.Data.Sqlite.SqliteParameterTest.SourceColumn_defaults_to_empty', 'Microsoft.Data.Sqlite.SqliteParameterTest.Ctor_sets_other_values', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_Guid', 'Microsoft.Data.Sqlite.SqliteParameterTest.Ctor_sets_name_and_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_DateTime_with_Arabic_Culture', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateTime_with_SqliteType_Real', 'Microsoft.Data.Sqlite.SqliteParameterTest.SourceColumn_coalesces_to_empty', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_TimeSpan', 'Microsoft.Data.Sqlite.SqliteParameterTest.ResetDbType_works', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_with_prefixed_names', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_TimeOnly', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_DateTimeOffset_with_SqliteType_Real', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_with_sentinel_size_works_on_string_values', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_with_restricted_size_works_on_string_values', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_works_when_decimal_with_integral_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_requires_set_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.Direction_validates_value', 'Microsoft.Data.Sqlite.SqliteParameterTest.Bind_DateTimeOffset_with_Arabic_Culture']
dotnet/efcore
dotnet__efcore-27210
cf46ae0ed95c5564676ea25f7083d710552bae55
diff --git a/src/EFCore.Abstractions/IndexAttribute.cs b/src/EFCore.Abstractions/IndexAttribute.cs index c60caefcb14..4b93178c115 100644 --- a/src/EFCore.Abstractions/IndexAttribute.cs +++ b/src/EFCore.Abstractions/IndexAttribute.cs @@ -15,8 +15,9 @@ namespace Microsoft.EntityFrameworkCore; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class IndexAttribute : Attribute { - private bool? _isUnique; private string? _name; + private bool? _isUnique; + private bool[]? _isDescending; /// <summary> /// Initializes a new instance of the <see cref="IndexAttribute" /> class. @@ -54,6 +55,24 @@ public bool IsUnique set => _isUnique = value; } + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + public bool[]? IsDescending + { + get => _isDescending; + set + { + if (value is not null && value.Length != PropertyNames.Count) + { + throw new ArgumentException( + AbstractionsStrings.InvalidNumberOfIndexSortOrderValues(value.Length, PropertyNames.Count), nameof(IsDescending)); + } + + _isDescending = value; + } + } + /// <summary> /// Checks whether <see cref="IsUnique" /> has been explicitly set to a value. /// </summary> diff --git a/src/EFCore.Abstractions/Properties/AbstractionsStrings.Designer.cs b/src/EFCore.Abstractions/Properties/AbstractionsStrings.Designer.cs index 9c2fdfcc201..059dddee5cf 100644 --- a/src/EFCore.Abstractions/Properties/AbstractionsStrings.Designer.cs +++ b/src/EFCore.Abstractions/Properties/AbstractionsStrings.Designer.cs @@ -52,6 +52,14 @@ public static string CollectionArgumentIsEmpty(object? argumentName) GetString("CollectionArgumentIsEmpty", nameof(argumentName)), argumentName); + /// <summary> + /// Invalid number of index sort order values: {numValues} values were provided, but the index has {numProperties} properties. + /// </summary> + public static string InvalidNumberOfIndexSortOrderValues(object? numValues, object? numProperties) + => string.Format( + GetString("CollectionArgumentIsEmpty", nameof(numValues), nameof(numProperties)), + numValues, numProperties); + private static string GetString(string name, params string[] formatterNames) { var value = _resourceManager.GetString(name)!; diff --git a/src/EFCore.Abstractions/Properties/AbstractionsStrings.resx b/src/EFCore.Abstractions/Properties/AbstractionsStrings.resx index 7bdf6f59663..568f47d97cd 100644 --- a/src/EFCore.Abstractions/Properties/AbstractionsStrings.resx +++ b/src/EFCore.Abstractions/Properties/AbstractionsStrings.resx @@ -129,4 +129,7 @@ <data name="CollectionArgumentIsEmpty" xml:space="preserve"> <value>The collection argument '{argumentName}' must contain at least one element.</value> </data> + <data name="InvalidNumberOfIndexSortOrderValues" xml:space="preserve"> + <value>Invalid number of index sort order values: {numValues} values were provided, but the index has {numProperties} properties.</value> + </data> </root> \ No newline at end of file diff --git a/src/EFCore.Design/Migrations/Design/CSharpMigrationOperationGenerator.cs b/src/EFCore.Design/Migrations/Design/CSharpMigrationOperationGenerator.cs index 15380528cbb..b8aa23b7459 100644 --- a/src/EFCore.Design/Migrations/Design/CSharpMigrationOperationGenerator.cs +++ b/src/EFCore.Design/Migrations/Design/CSharpMigrationOperationGenerator.cs @@ -911,6 +911,14 @@ protected virtual void Generate(CreateIndexOperation operation, IndentedStringBu .Append("unique: true"); } + if (operation.IsDescending is not null) + { + builder + .AppendLine(",") + .Append("descending: ") + .Append(Code.Literal(operation.IsDescending)); + } + if (operation.Filter != null) { builder diff --git a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs index 981cffe17a9..533cb70ebf9 100644 --- a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs +++ b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs @@ -634,6 +634,15 @@ protected virtual void GenerateIndex( .Append(".IsUnique()"); } + if (index.IsDescending is not null) + { + stringBuilder + .AppendLine() + .Append(".IsDescending(") + .Append(string.Join(", ", index.IsDescending.Select(Code.Literal))) + .Append(')'); + } + GenerateIndexAnnotations(indexBuilderName, index, stringBuilder); } diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs index cd186897fe9..78e4ff45d77 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs @@ -567,6 +567,11 @@ private void GenerateIndex(IIndex index) lines.Add($".{nameof(IndexBuilder.IsUnique)}()"); } + if (index.IsDescending is not null) + { + lines.Add($".{nameof(IndexBuilder.IsDescending)}({string.Join(", ", index.IsDescending.Select(d => _code.Literal(d)))})"); + } + GenerateAnnotations(index, annotations, lines); AppendMultiLineFluentApi(index.DeclaringEntityType, lines); diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.cs index be657806d10..bade36e8011 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.cs +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.cs @@ -212,6 +212,11 @@ private void GenerateIndexAttributes(IEntityType entityType) indexAttribute.AddParameter($"{nameof(IndexAttribute.IsUnique)} = {_code.Literal(index.IsUnique)}"); } + if (index.IsDescending is not null) + { + indexAttribute.AddParameter($"{nameof(IndexAttribute.IsDescending)} = {_code.UnknownLiteral(index.IsDescending)}"); + } + _sb.AppendLine(indexAttribute.ToString()); } } diff --git a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs index fc26a105b1d..839dfbcf7c4 100644 --- a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs +++ b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs @@ -627,9 +627,14 @@ protected virtual EntityTypeBuilder VisitIndexes(EntityTypeBuilder builder, ICol indexBuilder = indexBuilder.IsUnique(index.IsUnique); + if (index.IsDescending.Any(desc => desc)) + { + indexBuilder = indexBuilder.IsDescending(index.IsDescending.ToArray()); + } + if (index.Filter != null) { - indexBuilder.HasFilter(index.Filter); + indexBuilder = indexBuilder.HasFilter(index.Filter); } indexBuilder.Metadata.AddAnnotations(index.GetAnnotations()); diff --git a/src/EFCore.Relational/Metadata/ITableIndex.cs b/src/EFCore.Relational/Metadata/ITableIndex.cs index 93608beeadf..86ab50b304b 100644 --- a/src/EFCore.Relational/Metadata/ITableIndex.cs +++ b/src/EFCore.Relational/Metadata/ITableIndex.cs @@ -39,6 +39,11 @@ public interface ITableIndex : IAnnotatable /// </summary> bool IsUnique { get; } + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + IReadOnlyList<bool>? IsDescending { get; } + /// <summary> /// Gets the expression used as the index filter. /// </summary> @@ -70,8 +75,21 @@ string ToDebugString(MetadataDebugStringOptions options = MetadataDebugStringOpt builder .Append(Name) - .Append(' ') - .Append(ColumnBase.Format(Columns)); + .Append(" {") + .AppendJoin( + ", ", + Enumerable.Range(0, Columns.Count) + .Select( + i => + $@"'{Columns[i].Name}'{( + MappedIndexes.First() is not RuntimeIndex + && IsDescending is not null + && i < IsDescending.Count + && IsDescending[i] + ? " Desc" + : "" + )}")) + .Append('}'); if (IsUnique) { diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalIndexExtensions.cs b/src/EFCore.Relational/Metadata/Internal/RelationalIndexExtensions.cs index fdf330b8323..2dd404a4500 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalIndexExtensions.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalIndexExtensions.cs @@ -32,9 +32,9 @@ public static bool AreCompatible( { throw new InvalidOperationException( RelationalStrings.DuplicateIndexTableMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.GetDatabaseName(storeObject), index.DeclaringEntityType.GetSchemaQualifiedTableName(), @@ -50,9 +50,9 @@ public static bool AreCompatible( { throw new InvalidOperationException( RelationalStrings.DuplicateIndexColumnMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject), @@ -69,9 +69,29 @@ public static bool AreCompatible( { throw new InvalidOperationException( RelationalStrings.DuplicateIndexUniquenessMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), + duplicateIndex.DeclaringEntityType.DisplayName(), + index.DeclaringEntityType.GetSchemaQualifiedTableName(), + index.GetDatabaseName(storeObject))); + } + + return false; + } + + if (index.IsDescending is null != duplicateIndex.IsDescending is null + || (index.IsDescending is not null + && duplicateIndex.IsDescending is not null + && !index.IsDescending.SequenceEqual(duplicateIndex.IsDescending))) + { + if (shouldThrow) + { + throw new InvalidOperationException( + RelationalStrings.DuplicateIndexSortOrdersMismatch( + index.DisplayName(), + index.DeclaringEntityType.DisplayName(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); @@ -82,16 +102,21 @@ public static bool AreCompatible( if (index.GetFilter(storeObject) != duplicateIndex.GetFilter(storeObject)) { - throw new InvalidOperationException( - RelationalStrings.DuplicateIndexFiltersMismatch( - index.Properties.Format(), - index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), - duplicateIndex.DeclaringEntityType.DisplayName(), - index.DeclaringEntityType.GetSchemaQualifiedTableName(), - index.GetDatabaseName(storeObject), - index.GetFilter(), - duplicateIndex.GetFilter())); + if (shouldThrow) + { + throw new InvalidOperationException( + RelationalStrings.DuplicateIndexFiltersMismatch( + index.DisplayName(), + index.DeclaringEntityType.DisplayName(), + duplicateIndex.DisplayName(), + duplicateIndex.DeclaringEntityType.DisplayName(), + index.DeclaringEntityType.GetSchemaQualifiedTableName(), + index.GetDatabaseName(storeObject), + index.GetFilter(), + duplicateIndex.GetFilter())); + } + + return false; } return true; diff --git a/src/EFCore.Relational/Metadata/Internal/TableIndex.cs b/src/EFCore.Relational/Metadata/Internal/TableIndex.cs index a23021c34bb..318a1c97453 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableIndex.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableIndex.cs @@ -68,6 +68,10 @@ public override bool IsReadOnly /// <inheritdoc /> public virtual bool IsUnique { get; } + /// <inheritdoc /> + public virtual IReadOnlyList<bool>? IsDescending + => MappedIndexes.First().IsDescending; + /// <inheritdoc /> public virtual string? Filter => MappedIndexes.First().GetFilter(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs index 5fae40d6d3f..cba40a8ebbd 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs @@ -1393,6 +1393,10 @@ protected virtual IEnumerable<MigrationOperation> Diff( private bool IndexStructureEquals(ITableIndex source, ITableIndex target, DiffContext diffContext) => source.IsUnique == target.IsUnique + && ((source.IsDescending is null && target.IsDescending is null) + || (source.IsDescending is not null + && target.IsDescending is not null + && source.IsDescending.SequenceEqual(target.IsDescending))) && source.Filter == target.Filter && !HasDifferences(source.GetAnnotations(), target.GetAnnotations()) && source.Columns.Select(p => p.Name).SequenceEqual( diff --git a/src/EFCore.Relational/Migrations/MigrationBuilder.cs b/src/EFCore.Relational/Migrations/MigrationBuilder.cs index fb6fb2f1b8f..d5c37ae52d2 100644 --- a/src/EFCore.Relational/Migrations/MigrationBuilder.cs +++ b/src/EFCore.Relational/Migrations/MigrationBuilder.cs @@ -601,6 +601,10 @@ public virtual AlterOperationBuilder<AlterTableOperation> AlterTable( /// <param name="schema">The schema that contains the table, or <see langword="null" /> to use the default schema.</param> /// <param name="unique">Indicates whether or not the index enforces uniqueness.</param> /// <param name="filter">The filter to apply to the index, or <see langword="null" /> for no filter.</param> + /// <param name="descending"> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// If <see langword="null" />, all columns will have ascending order. + /// </param> /// <returns>A builder to allow annotations to be added to the operation.</returns> public virtual OperationBuilder<CreateIndexOperation> CreateIndex( string name, @@ -608,14 +612,16 @@ public virtual OperationBuilder<CreateIndexOperation> CreateIndex( string column, string? schema = null, bool unique = false, - string? filter = null) + string? filter = null, + bool[]? descending = null) => CreateIndex( name, table, new[] { Check.NotEmpty(column, nameof(column)) }, schema, unique, - filter); + filter, + descending); /// <summary> /// Builds a <see cref="CreateIndexOperation" /> to create a new composite (multi-column) index. @@ -629,6 +635,10 @@ public virtual OperationBuilder<CreateIndexOperation> CreateIndex( /// <param name="schema">The schema that contains the table, or <see langword="null" /> to use the default schema.</param> /// <param name="unique">Indicates whether or not the index enforces uniqueness.</param> /// <param name="filter">The filter to apply to the index, or <see langword="null" /> for no filter.</param> + /// <param name="descending"> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// If <see langword="null" />, all columns will have ascending order. + /// </param> /// <returns>A builder to allow annotations to be added to the operation.</returns> public virtual OperationBuilder<CreateIndexOperation> CreateIndex( string name, @@ -636,7 +646,8 @@ public virtual OperationBuilder<CreateIndexOperation> CreateIndex( string[] columns, string? schema = null, bool unique = false, - string? filter = null) + string? filter = null, + bool[]? descending = null) { Check.NotEmpty(name, nameof(name)); Check.NotEmpty(table, nameof(table)); @@ -649,8 +660,10 @@ public virtual OperationBuilder<CreateIndexOperation> CreateIndex( Name = name, Columns = columns, IsUnique = unique, + IsDescending = descending, Filter = filter }; + Operations.Add(operation); return new OperationBuilder<CreateIndexOperation>(operation); diff --git a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs index f08c9c69118..5528830b693 100644 --- a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs +++ b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs @@ -428,9 +428,11 @@ protected virtual void Generate( .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)) .Append(" ON ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) - .Append(" (") - .Append(ColumnList(operation.Columns)) - .Append(")"); + .Append(" ("); + + GenerateIndexColumnList(operation, model, builder); + + builder.Append(")"); IndexOptions(operation, model, builder); @@ -1659,23 +1661,41 @@ protected virtual void CheckConstraint( /// <param name="operation">The operation.</param> /// <param name="model">The target model which may be <see langword="null" /> if the operations exist without a model.</param> /// <param name="builder">The command builder to use to add the SQL fragment.</param> - protected virtual void IndexTraits( - MigrationOperation operation, - IModel? model, - MigrationCommandListBuilder builder) + protected virtual void IndexTraits(MigrationOperation operation, IModel? model, MigrationCommandListBuilder builder) { } + /// <summary> + /// Returns a SQL fragment for the column list of an index from a <see cref="CreateIndexOperation" />. + /// </summary> + /// <param name="operation">The operation.</param> + /// <param name="model">The target model which may be <see langword="null" /> if the operations exist without a model.</param> + /// <param name="builder">The command builder to use to add the SQL fragment.</param> + protected virtual void GenerateIndexColumnList(CreateIndexOperation operation, IModel? model, MigrationCommandListBuilder builder) + { + for (var i = 0; i < operation.Columns.Length; i++) + { + if (i > 0) + { + builder.Append(", "); + } + + builder.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Columns[i])); + + if (operation.IsDescending is not null && i < operation.IsDescending.Length && operation.IsDescending[i]) + { + builder.Append(" DESC"); + } + } + } + /// <summary> /// Generates a SQL fragment for extras (filter, included columns, options) of an index from a <see cref="CreateIndexOperation" />. /// </summary> /// <param name="operation">The operation.</param> /// <param name="model">The target model which may be <see langword="null" /> if the operations exist without a model.</param> /// <param name="builder">The command builder to use to add the SQL fragment.</param> - protected virtual void IndexOptions( - CreateIndexOperation operation, - IModel? model, - MigrationCommandListBuilder builder) + protected virtual void IndexOptions(CreateIndexOperation operation, IModel? model, MigrationCommandListBuilder builder) { if (!string.IsNullOrEmpty(operation.Filter)) { diff --git a/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs b/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs index 4b136221509..a156281704e 100644 --- a/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs @@ -12,10 +12,8 @@ namespace Microsoft.EntityFrameworkCore.Migrations.Operations; [DebuggerDisplay("CREATE INDEX {Name} ON {Table}")] public class CreateIndexOperation : MigrationOperation, ITableMigrationOperation { - /// <summary> - /// Indicates whether or not the index should enforce uniqueness. - /// </summary> - public virtual bool IsUnique { get; set; } + private string[]? _columns; + private bool[]? _isDescending; /// <summary> /// The name of the index. @@ -35,7 +33,41 @@ public class CreateIndexOperation : MigrationOperation, ITableMigrationOperation /// <summary> /// The ordered list of column names for the column that make up the index. /// </summary> - public virtual string[] Columns { get; set; } = null!; + public virtual string[] Columns + { + get => _columns!; + set + { + if (_isDescending is not null && value.Length != _isDescending.Length) + { + throw new ArgumentException(RelationalStrings.CreateIndexOperationWithInvalidSortOrder(_isDescending.Length, value.Length)); + } + + _columns = value; + } + } + + /// <summary> + /// Indicates whether or not the index should enforce uniqueness. + /// </summary> + public virtual bool IsUnique { get; set; } + + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + public virtual bool[]? IsDescending + { + get => _isDescending; + set + { + if (value is not null && _columns is not null && value.Length != _columns.Length) + { + throw new ArgumentException(RelationalStrings.CreateIndexOperationWithInvalidSortOrder(value.Length, _columns.Length)); + } + + _isDescending = value; + } + } /// <summary> /// An expression to use as the index filter. @@ -53,11 +85,12 @@ public static CreateIndexOperation CreateFrom(ITableIndex index) var operation = new CreateIndexOperation { - IsUnique = index.IsUnique, Name = index.Name, Schema = index.Table.Schema, Table = index.Table.Name, Columns = index.Columns.Select(p => p.Name).ToArray(), + IsUnique = index.IsUnique, + IsDescending = index.IsDescending?.ToArray(), Filter = index.Filter }; operation.AddAnnotations(index.GetAnnotations()); diff --git a/src/EFCore.Relational/Properties/RelationalStrings.Designer.cs b/src/EFCore.Relational/Properties/RelationalStrings.Designer.cs index 7e7db5126aa..496cd075aaa 100644 --- a/src/EFCore.Relational/Properties/RelationalStrings.Designer.cs +++ b/src/EFCore.Relational/Properties/RelationalStrings.Designer.cs @@ -151,6 +151,14 @@ public static string ConflictingRowValuesSensitive(object? firstEntityType, obje GetString("ConflictingRowValuesSensitive", nameof(firstEntityType), nameof(secondEntityType), nameof(keyValue), nameof(firstConflictingValue), nameof(secondConflictingValue), nameof(column)), firstEntityType, secondEntityType, keyValue, firstConflictingValue, secondConflictingValue, column); + /// <summary> + /// {numSortOrderProperties} values were provided in CreateIndexOperations.IsDescending, but the operation has {numColumns} columns. + /// </summary> + public static string CreateIndexOperationWithInvalidSortOrder(object? numSortOrderProperties, object? numColumns) + => string.Format( + GetString("CreateIndexOperationWithInvalidSortOrder", nameof(numSortOrderProperties), nameof(numColumns)), + numSortOrderProperties, numColumns); + /// <summary> /// There is no property mapped to the column '{table}.{column}' which is used in a data operation. Either add a property mapped to this column, or specify the column types in the data operation. /// </summary> @@ -470,36 +478,44 @@ public static string DuplicateForeignKeyUniquenessMismatch(object? foreignKeyPro foreignKeyProperties1, entityType1, foreignKeyProperties2, entityType2, table, foreignKeyName); /// <summary> - /// The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different columns ({columnNames1} and {columnNames2}). + /// The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different columns ({columnNames1} and {columnNames2}). + /// </summary> + public static string DuplicateIndexColumnMismatch(object? index1, object? entityType1, object? index2, object? entityType2, object? table, object? indexName, object? columnNames1, object? columnNames2) + => string.Format( + GetString("DuplicateIndexColumnMismatch", nameof(index1), nameof(entityType1), nameof(index2), nameof(entityType2), nameof(table), nameof(indexName), nameof(columnNames1), nameof(columnNames2)), + index1, entityType1, index2, entityType2, table, indexName, columnNames1, columnNames2); + + /// <summary> + /// The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different filters ('{filter1}' and '{filter2}'). /// </summary> - public static string DuplicateIndexColumnMismatch(object? indexProperties1, object? entityType1, object? indexProperties2, object? entityType2, object? table, object? indexName, object? columnNames1, object? columnNames2) + public static string DuplicateIndexFiltersMismatch(object? index1, object? entityType1, object? index2, object? entityType2, object? table, object? indexName, object? filter1, object? filter2) => string.Format( - GetString("DuplicateIndexColumnMismatch", nameof(indexProperties1), nameof(entityType1), nameof(indexProperties2), nameof(entityType2), nameof(table), nameof(indexName), nameof(columnNames1), nameof(columnNames2)), - indexProperties1, entityType1, indexProperties2, entityType2, table, indexName, columnNames1, columnNames2); + GetString("DuplicateIndexFiltersMismatch", nameof(index1), nameof(entityType1), nameof(index2), nameof(entityType2), nameof(table), nameof(indexName), nameof(filter1), nameof(filter2)), + index1, entityType1, index2, entityType2, table, indexName, filter1, filter2); /// <summary> - /// The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different filters ('{filter1}' and '{filter2}'). + /// The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different sort orders. /// </summary> - public static string DuplicateIndexFiltersMismatch(object? indexProperties1, object? entityType1, object? indexProperties2, object? entityType2, object? table, object? indexName, object? filter1, object? filter2) + public static string DuplicateIndexSortOrdersMismatch(object? index1, object? entityType1, object? index2, object? entityType2, object? table, object? indexName) => string.Format( - GetString("DuplicateIndexFiltersMismatch", nameof(indexProperties1), nameof(entityType1), nameof(indexProperties2), nameof(entityType2), nameof(table), nameof(indexName), nameof(filter1), nameof(filter2)), - indexProperties1, entityType1, indexProperties2, entityType2, table, indexName, filter1, filter2); + GetString("DuplicateIndexSortOrdersMismatch", nameof(index1), nameof(entityType1), nameof(index2), nameof(entityType2), nameof(table), nameof(indexName)), + index1, entityType1, index2, entityType2, table, indexName); /// <summary> - /// The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{indexName}', but are declared on different tables ('{table1}' and '{table2}'). + /// The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{indexName}', but are declared on different tables ('{table1}' and '{table2}'). /// </summary> - public static string DuplicateIndexTableMismatch(object? indexProperties1, object? entityType1, object? indexProperties2, object? entityType2, object? indexName, object? table1, object? table2) + public static string DuplicateIndexTableMismatch(object? index1, object? entityType1, object? index2, object? entityType2, object? indexName, object? table1, object? table2) => string.Format( - GetString("DuplicateIndexTableMismatch", nameof(indexProperties1), nameof(entityType1), nameof(indexProperties2), nameof(entityType2), nameof(indexName), nameof(table1), nameof(table2)), - indexProperties1, entityType1, indexProperties2, entityType2, indexName, table1, table2); + GetString("DuplicateIndexTableMismatch", nameof(index1), nameof(entityType1), nameof(index2), nameof(entityType2), nameof(indexName), nameof(table1), nameof(table2)), + index1, entityType1, index2, entityType2, indexName, table1, table2); /// <summary> - /// The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different uniqueness configurations. + /// The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different uniqueness configurations. /// </summary> - public static string DuplicateIndexUniquenessMismatch(object? indexProperties1, object? entityType1, object? indexProperties2, object? entityType2, object? table, object? indexName) + public static string DuplicateIndexUniquenessMismatch(object? index1, object? entityType1, object? index2, object? entityType2, object? table, object? indexName) => string.Format( - GetString("DuplicateIndexUniquenessMismatch", nameof(indexProperties1), nameof(entityType1), nameof(indexProperties2), nameof(entityType2), nameof(table), nameof(indexName)), - indexProperties1, entityType1, indexProperties2, entityType2, table, indexName); + GetString("DuplicateIndexUniquenessMismatch", nameof(index1), nameof(entityType1), nameof(index2), nameof(entityType2), nameof(table), nameof(indexName)), + index1, entityType1, index2, entityType2, table, indexName); /// <summary> /// The keys {keyProperties1} on '{entityType1}' and {keyProperties2} on '{entityType2}' are both mapped to '{table}.{keyName}', but with different columns ({columnNames1} and {columnNames2}). diff --git a/src/EFCore.Relational/Properties/RelationalStrings.resx b/src/EFCore.Relational/Properties/RelationalStrings.resx index 366f1912ce3..19e96b800f6 100644 --- a/src/EFCore.Relational/Properties/RelationalStrings.resx +++ b/src/EFCore.Relational/Properties/RelationalStrings.resx @@ -169,6 +169,9 @@ <data name="ConflictingRowValuesSensitive" xml:space="preserve"> <value>Instances of entity types '{firstEntityType}' and '{secondEntityType}' are mapped to the same row with the key value '{keyValue}', but have different property values '{firstConflictingValue}' and '{secondConflictingValue}' for the column '{column}'.</value> </data> + <data name="CreateIndexOperationWithInvalidSortOrder" xml:space="preserve"> + <value>{numSortOrderProperties} values were provided in CreateIndexOperations.IsDescending, but the operation has {numColumns} columns.</value> + </data> <data name="DataOperationNoProperty" xml:space="preserve"> <value>There is no property mapped to the column '{table}.{column}' which is used in a data operation. Either add a property mapped to this column, or specify the column types in the data operation.</value> </data> @@ -290,16 +293,19 @@ <value>The foreign keys {foreignKeyProperties1} on '{entityType1}' and {foreignKeyProperties2} on '{entityType2}' are both mapped to '{table}.{foreignKeyName}', but with different uniqueness configurations.</value> </data> <data name="DuplicateIndexColumnMismatch" xml:space="preserve"> - <value>The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different columns ({columnNames1} and {columnNames2}).</value> + <value>The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different columns ({columnNames1} and {columnNames2}).</value> </data> <data name="DuplicateIndexFiltersMismatch" xml:space="preserve"> - <value>The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different filters ('{filter1}' and '{filter2}').</value> + <value>The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different filters ('{filter1}' and '{filter2}').</value> + </data> + <data name="DuplicateIndexSortOrdersMismatch" xml:space="preserve"> + <value>The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different sort orders.</value> </data> <data name="DuplicateIndexTableMismatch" xml:space="preserve"> - <value>The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{indexName}', but are declared on different tables ('{table1}' and '{table2}').</value> + <value>The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{indexName}', but are declared on different tables ('{table1}' and '{table2}').</value> </data> <data name="DuplicateIndexUniquenessMismatch" xml:space="preserve"> - <value>The indexes {indexProperties1} on '{entityType1}' and {indexProperties2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different uniqueness configurations.</value> + <value>The indexes {index1} on '{entityType1}' and {index2} on '{entityType2}' are both mapped to '{table}.{indexName}', but with different uniqueness configurations.</value> </data> <data name="DuplicateKeyColumnMismatch" xml:space="preserve"> <value>The keys {keyProperties1} on '{entityType1}' and {keyProperties2} on '{entityType2}' are both mapped to '{table}.{keyName}', but with different columns ({columnNames1} and {columnNames2}).</value> diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs index 92de823af64..57f19fcc024 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs @@ -28,10 +28,15 @@ public class DatabaseIndex : Annotatable public virtual IList<DatabaseColumn> Columns { get; } = new List<DatabaseColumn>(); /// <summary> - /// Indicates whether or not the index constrains uniqueness. + /// Indicates whether or not the index enforces uniqueness. /// </summary> public virtual bool IsUnique { get; set; } + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + public virtual IList<bool> IsDescending { get; set; } = new List<bool>(); + /// <summary> /// The filter expression, or <see langword="null" /> if the index has no filter. /// </summary> diff --git a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerModelValidator.cs b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerModelValidator.cs index d4e4f6dff32..3d066e9c478 100644 --- a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerModelValidator.cs +++ b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerModelValidator.cs @@ -163,7 +163,7 @@ protected virtual void ValidateIndexIncludeProperties( throw new InvalidOperationException( SqlServerStrings.IncludePropertyNotFound( notFound, - index.Name == null ? index.Properties.Format() : "'" + index.Name + "'", + index.DisplayName(), index.DeclaringEntityType.DisplayName())); } @@ -179,7 +179,7 @@ protected virtual void ValidateIndexIncludeProperties( SqlServerStrings.IncludePropertyDuplicated( index.DeclaringEntityType.DisplayName(), duplicateProperty, - index.Name == null ? index.Properties.Format() : "'" + index.Name + "'")); + index.DisplayName())); } var coveredProperty = includeProperties @@ -191,7 +191,7 @@ protected virtual void ValidateIndexIncludeProperties( SqlServerStrings.IncludePropertyInIndex( index.DeclaringEntityType.DisplayName(), coveredProperty, - index.Name == null ? index.Properties.Format() : "'" + index.Name + "'")); + index.DisplayName())); } } } diff --git a/src/EFCore.SqlServer/Metadata/Internal/SqlServerIndexExtensions.cs b/src/EFCore.SqlServer/Metadata/Internal/SqlServerIndexExtensions.cs index ed2791568b5..49f21891482 100644 --- a/src/EFCore.SqlServer/Metadata/Internal/SqlServerIndexExtensions.cs +++ b/src/EFCore.SqlServer/Metadata/Internal/SqlServerIndexExtensions.cs @@ -35,9 +35,9 @@ public static bool AreCompatibleForSqlServer( { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexIncludedMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject), @@ -55,9 +55,9 @@ public static bool AreCompatibleForSqlServer( { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexOnlineMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); @@ -72,9 +72,9 @@ public static bool AreCompatibleForSqlServer( { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexClusteredMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); @@ -89,9 +89,9 @@ public static bool AreCompatibleForSqlServer( { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexFillFactorMismatch( - index.Properties.Format(), + index.DisplayName(), index.DeclaringEntityType.DisplayName(), - duplicateIndex.Properties.Format(), + duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); diff --git a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs index 255e4fdc683..878e053f7cf 100644 --- a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs +++ b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs @@ -748,10 +748,9 @@ protected override void Generate( IndexTraits(operation, model, builder); - builder - .Append("(") - .Append(ColumnList(operation.Columns)) - .Append(")"); + builder.Append("("); + GenerateIndexColumnList(operation, model, builder); + builder.Append(")"); } else { diff --git a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs index 0c7d9b78c32..71c4e39fb73 100644 --- a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs +++ b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs @@ -932,6 +932,7 @@ private void GetIndexes(DbConnection connection, IReadOnlyList<DatabaseTable> ta [i].[filter_definition], [i].[fill_factor], COL_NAME([ic].[object_id], [ic].[column_id]) AS [column_name], + [ic].[is_descending_key], [ic].[is_included_column] FROM [sys].[indexes] AS [i] JOIN [sys].[tables] AS [t] ON [i].[object_id] = [t].[object_id] @@ -1137,6 +1138,8 @@ bool TryGetIndex( return false; } + index.IsDescending.Add(dataRecord.GetValueOrDefault<bool>("is_descending_key")); + index.Columns.Add(column); } diff --git a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs index fb527ae7c37..b2a50da6bbf 100644 --- a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs +++ b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs @@ -458,8 +458,9 @@ private void GetIndexes(DbConnection connection, DatabaseTable table) using (var command2 = connection.CreateCommand()) { command2.CommandText = new StringBuilder() - .AppendLine("SELECT \"name\"") - .AppendLine("FROM pragma_index_info(@index)") + .AppendLine("SELECT \"name\", \"desc\"") + .AppendLine("FROM pragma_index_xinfo(@index)") + .AppendLine("WHERE key = 1") .AppendLine("ORDER BY \"seqno\";") .ToString(); @@ -477,6 +478,7 @@ private void GetIndexes(DbConnection connection, DatabaseTable table) Check.DebugAssert(column != null, "column is null."); index.Columns.Add(column); + index.IsDescending.Add(reader2.GetBoolean(1)); } } diff --git a/src/EFCore/Metadata/Builders/IConventionIndexBuilder.cs b/src/EFCore/Metadata/Builders/IConventionIndexBuilder.cs index be420be010c..93d7dafa6f8 100644 --- a/src/EFCore/Metadata/Builders/IConventionIndexBuilder.cs +++ b/src/EFCore/Metadata/Builders/IConventionIndexBuilder.cs @@ -27,18 +27,30 @@ public interface IConventionIndexBuilder : IConventionAnnotatableBuilder /// </summary> /// <param name="unique">A value indicating whether the index is unique.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> - /// <returns> - /// The same builder instance if the uniqueness was configured, - /// <see langword="null" /> otherwise. - /// </returns> + /// <returns>The same builder instance if the uniqueness was configured, <see langword="null" /> otherwise.</returns> IConventionIndexBuilder? IsUnique(bool? unique, bool fromDataAnnotation = false); /// <summary> - /// Returns a value indicating whether this index uniqueness can be configured - /// from the current configuration source. + /// Returns a value indicating whether this index uniqueness can be configured from the current configuration source. /// </summary> /// <param name="unique">A value indicating whether the index is unique.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the index uniqueness can be configured.</returns> bool CanSetIsUnique(bool? unique, bool fromDataAnnotation = false); + + /// <summary> + /// Configures the sort order(s) for the columns of this index (ascending or descending). + /// </summary> + /// <param name="descending">A set of values indicating whether each corresponding index column has descending sort order.</param> + /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> + /// <returns>The same builder instance if the uniqueness was configured, <see langword="null" /> otherwise.</returns> + IConventionIndexBuilder? IsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation = false); + + /// <summary> + /// Returns a value indicating whether this index sort order can be configured from the current configuration source. + /// </summary> + /// <param name="descending">A set of values indicating whether each corresponding index column has descending sort order.</param> + /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> + /// <returns><see langword="true" /> if the index uniqueness can be configured.</returns> + bool CanSetIsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation = false); } diff --git a/src/EFCore/Metadata/Builders/IndexBuilder.cs b/src/EFCore/Metadata/Builders/IndexBuilder.cs index 9f3f1e899cc..71779f59636 100644 --- a/src/EFCore/Metadata/Builders/IndexBuilder.cs +++ b/src/EFCore/Metadata/Builders/IndexBuilder.cs @@ -77,6 +77,18 @@ public virtual IndexBuilder IsUnique(bool unique = true) return this; } + /// <summary> + /// Configures the sort order(s) for the columns of this index (ascending or descending). + /// </summary> + /// <param name="descending">A set of values indicating whether each corresponding index column has descending sort order.</param> + /// <returns>The same builder instance so that multiple configuration calls can be chained.</returns> + public virtual IndexBuilder IsDescending(params bool[] descending) + { + Builder.IsDescending(descending, ConfigurationSource.Explicit); + + return this; + } + #region Hidden System.Object members /// <summary> diff --git a/src/EFCore/Metadata/Builders/IndexBuilder`.cs b/src/EFCore/Metadata/Builders/IndexBuilder`.cs index 8bfc61e74b1..e8f36809e9e 100644 --- a/src/EFCore/Metadata/Builders/IndexBuilder`.cs +++ b/src/EFCore/Metadata/Builders/IndexBuilder`.cs @@ -49,4 +49,12 @@ public IndexBuilder(IMutableIndex index) /// <returns>The same builder instance so that multiple configuration calls can be chained.</returns> public new virtual IndexBuilder<T> IsUnique(bool unique = true) => (IndexBuilder<T>)base.IsUnique(unique); + + /// <summary> + /// Configures the sort order(s) for the columns of this index (ascending or descending). + /// </summary> + /// <param name="descending">A set of values indicating whether each corresponding index column has descending sort order.</param> + /// <returns>The same builder instance so that multiple configuration calls can be chained.</returns> + public new virtual IndexBuilder<T> IsDescending(params bool[] descending) + => (IndexBuilder<T>)base.IsDescending(descending); } diff --git a/src/EFCore/Metadata/Conventions/ConventionSet.cs b/src/EFCore/Metadata/Conventions/ConventionSet.cs index 3d168974fb8..54cc3869801 100644 --- a/src/EFCore/Metadata/Conventions/ConventionSet.cs +++ b/src/EFCore/Metadata/Conventions/ConventionSet.cs @@ -207,6 +207,12 @@ public class ConventionSet public virtual IList<IIndexUniquenessChangedConvention> IndexUniquenessChangedConventions { get; } = new List<IIndexUniquenessChangedConvention>(); + /// <summary> + /// Conventions to run when the sort order of an index is changed. + /// </summary> + public virtual IList<IIndexSortOrderChangedConvention> IndexSortOrderChangedConventions { get; } + = new List<IIndexSortOrderChangedConvention>(); + /// <summary> /// Conventions to run when an annotation is changed on an index. /// </summary> diff --git a/src/EFCore/Metadata/Conventions/IIndexSortOrderChangedConvention.cs b/src/EFCore/Metadata/Conventions/IIndexSortOrderChangedConvention.cs new file mode 100644 index 00000000000..b537fc71c71 --- /dev/null +++ b/src/EFCore/Metadata/Conventions/IIndexSortOrderChangedConvention.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.EntityFrameworkCore.Metadata.Conventions; + +/// <summary> +/// Represents an operation that should be performed when the sort order of an index is changed. +/// </summary> +/// <remarks> +/// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information and examples. +/// </remarks> +public interface IIndexSortOrderChangedConvention : IConvention +{ + /// <summary> + /// Called after the uniqueness for an index is changed. + /// </summary> + /// <param name="indexBuilder">The builder for the index.</param> + /// <param name="context">Additional information associated with convention execution.</param> + void ProcessIndexSortOrderChanged( + IConventionIndexBuilder indexBuilder, + IConventionContext<IReadOnlyList<bool>?> context); +} diff --git a/src/EFCore/Metadata/Conventions/IndexAttributeConvention.cs b/src/EFCore/Metadata/Conventions/IndexAttributeConvention.cs index 0f8f1cef2f6..52831af95ca 100644 --- a/src/EFCore/Metadata/Conventions/IndexAttributeConvention.cs +++ b/src/EFCore/Metadata/Conventions/IndexAttributeConvention.cs @@ -110,9 +110,17 @@ private static void CheckIndexAttributesAndEnsureIndex( { CheckIgnoredProperties(indexAttribute, entityType); } - else if (indexAttribute.IsUniqueHasValue) + else { - indexBuilder.IsUnique(indexAttribute.IsUnique, fromDataAnnotation: true); + if (indexAttribute.IsUniqueHasValue) + { + indexBuilder = indexBuilder.IsUnique(indexAttribute.IsUnique, fromDataAnnotation: true); + } + + if (indexBuilder is not null && indexAttribute.IsDescending is not null) + { + indexBuilder = indexBuilder.IsDescending(indexAttribute.IsDescending, fromDataAnnotation: true); + } } } } diff --git a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ConventionScope.cs b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ConventionScope.cs index 252512a3fea..6ea81d79fec 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ConventionScope.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ConventionScope.cs @@ -127,6 +127,8 @@ public int GetLeafCount() IConventionIndex index); public abstract bool? OnIndexUniquenessChanged(IConventionIndexBuilder indexBuilder); + public abstract IReadOnlyList<bool>? OnIndexSortOrderChanged(IConventionIndexBuilder indexBuilder); + public abstract IConventionKeyBuilder? OnKeyAdded(IConventionKeyBuilder keyBuilder); public abstract IConventionAnnotation? OnKeyAnnotationChanged( diff --git a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.DelayedConventionScope.cs b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.DelayedConventionScope.cs index e7945a2f2f5..8e471dba230 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.DelayedConventionScope.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.DelayedConventionScope.cs @@ -183,6 +183,12 @@ public override IConventionIndex OnIndexRemoved( return indexBuilder.Metadata.IsUnique; } + public override IReadOnlyList<bool>? OnIndexSortOrderChanged(IConventionIndexBuilder indexBuilder) + { + Add(new OnIndexSortOrderChangedNode(indexBuilder)); + return indexBuilder.Metadata.IsDescending; + } + public override IConventionAnnotation? OnIndexAnnotationChanged( IConventionIndexBuilder indexBuilder, string name, @@ -901,6 +907,19 @@ public override void Run(ConventionDispatcher dispatcher) => dispatcher._immediateConventionScope.OnIndexUniquenessChanged(IndexBuilder); } + private sealed class OnIndexSortOrderChangedNode : ConventionNode + { + public OnIndexSortOrderChangedNode(IConventionIndexBuilder indexBuilder) + { + IndexBuilder = indexBuilder; + } + + public IConventionIndexBuilder IndexBuilder { get; } + + public override void Run(ConventionDispatcher dispatcher) + => dispatcher._immediateConventionScope.OnIndexSortOrderChanged(IndexBuilder); + } + private sealed class OnIndexAnnotationChangedNode : ConventionNode { public OnIndexAnnotationChangedNode( diff --git a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs index 846d88247b1..68ec5094ed8 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs @@ -29,6 +29,7 @@ private sealed class ImmediateConventionScope : ConventionScope private readonly ConventionContext<string> _stringConventionContext; private readonly ConventionContext<FieldInfo> _fieldInfoConventionContext; private readonly ConventionContext<bool?> _boolConventionContext; + private readonly ConventionContext<IReadOnlyList<bool>?> _boolListConventionContext; public ImmediateConventionScope(ConventionSet conventionSet, ConventionDispatcher dispatcher) { @@ -54,6 +55,7 @@ public ImmediateConventionScope(ConventionSet conventionSet, ConventionDispatche _stringConventionContext = new ConventionContext<string>(dispatcher); _fieldInfoConventionContext = new ConventionContext<FieldInfo>(dispatcher); _boolConventionContext = new ConventionContext<bool?>(dispatcher); + _boolListConventionContext = new ConventionContext<IReadOnlyList<bool>?>(dispatcher); } public override void Run(ConventionDispatcher dispatcher) @@ -969,6 +971,29 @@ public IConventionModelBuilder OnModelInitialized(IConventionModelBuilder modelB return !indexBuilder.Metadata.IsInModel ? null : _boolConventionContext.Result; } + public override IReadOnlyList<bool>? OnIndexSortOrderChanged(IConventionIndexBuilder indexBuilder) + { + using (_dispatcher.DelayConventions()) + { + _boolListConventionContext.ResetState(indexBuilder.Metadata.IsDescending); + foreach (var indexConvention in _conventionSet.IndexSortOrderChangedConventions) + { + if (!indexBuilder.Metadata.IsInModel) + { + return null; + } + + indexConvention.ProcessIndexSortOrderChanged(indexBuilder, _boolListConventionContext); + if (_boolListConventionContext.ShouldStopProcessing()) + { + return _boolListConventionContext.Result; + } + } + } + + return !indexBuilder.Metadata.IsInModel ? null : _boolListConventionContext.Result; + } + public override IConventionAnnotation? OnIndexAnnotationChanged( IConventionIndexBuilder indexBuilder, string name, diff --git a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.cs b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.cs index 20f24d61469..69ef6bd3cd1 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.cs @@ -483,6 +483,15 @@ public virtual IConventionModelBuilder OnModelFinalizing(IConventionModelBuilder public virtual bool? OnIndexUniquenessChanged(IConventionIndexBuilder indexBuilder) => _scope.OnIndexUniquenessChanged(indexBuilder); + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual IReadOnlyList<bool>? OnIndexSortOrderChanged(IConventionIndexBuilder indexBuilder) + => _scope.OnIndexSortOrderChanged(indexBuilder); + /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore/Metadata/IConventionIndex.cs b/src/EFCore/Metadata/IConventionIndex.cs index ee2cfcdc9a2..ccad73d3b7e 100644 --- a/src/EFCore/Metadata/IConventionIndex.cs +++ b/src/EFCore/Metadata/IConventionIndex.cs @@ -54,4 +54,18 @@ public interface IConventionIndex : IReadOnlyIndex, IConventionAnnotatable /// </summary> /// <returns>The configuration source for <see cref="IReadOnlyIndex.IsUnique" />.</returns> ConfigurationSource? GetIsUniqueConfigurationSource(); + + /// <summary> + /// Sets the sort order(s) for this index (ascending or descending). + /// </summary> + /// <param name="descending">A set of values indicating whether each corresponding index column has descending sort order.</param> + /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> + /// <returns>The configured sort order(s).</returns> + IReadOnlyList<bool>? SetIsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation = false); + + /// <summary> + /// Returns the configuration source for <see cref="IReadOnlyIndex.IsDescending" />. + /// </summary> + /// <returns>The configuration source for <see cref="IReadOnlyIndex.IsDescending" />.</returns> + ConfigurationSource? GetIsDescendingConfigurationSource(); } diff --git a/src/EFCore/Metadata/IMutableIndex.cs b/src/EFCore/Metadata/IMutableIndex.cs index c1270b4995e..bd77f85679f 100644 --- a/src/EFCore/Metadata/IMutableIndex.cs +++ b/src/EFCore/Metadata/IMutableIndex.cs @@ -23,6 +23,11 @@ public interface IMutableIndex : IReadOnlyIndex, IMutableAnnotatable /// </summary> new bool IsUnique { get; set; } + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + new IReadOnlyList<bool>? IsDescending { get; set; } + /// <summary> /// Gets the properties that this index is defined on. /// </summary> diff --git a/src/EFCore/Metadata/IReadOnlyIndex.cs b/src/EFCore/Metadata/IReadOnlyIndex.cs index 6bcb12dbecf..f7ab17a9a4a 100644 --- a/src/EFCore/Metadata/IReadOnlyIndex.cs +++ b/src/EFCore/Metadata/IReadOnlyIndex.cs @@ -28,6 +28,11 @@ public interface IReadOnlyIndex : IReadOnlyAnnotatable /// </summary> bool IsUnique { get; } + /// <summary> + /// A set of values indicating whether each corresponding index column has descending sort order. + /// </summary> + IReadOnlyList<bool>? IsDescending { get; } + /// <summary> /// Gets the entity type the index is defined on. This may be different from the type that <see cref="Properties" /> /// are defined on when the index is defined a derived type in an inheritance hierarchy (since the properties @@ -35,6 +40,15 @@ public interface IReadOnlyIndex : IReadOnlyAnnotatable /// </summary> IReadOnlyEntityType DeclaringEntityType { get; } + /// <summary> + /// Gets the friendly display name for the given <see cref="IReadOnlyIndex" />, returning its <see cref="Name" /> if one is defined, + /// or a string representation of its <see cref="Properties" /> if this is an unnamed index. + /// </summary> + /// <returns>The display name.</returns> + [DebuggerStepThrough] + string DisplayName() + => Name is null ? Properties.Format() : $"'{Name}'"; + /// <summary> /// <para> /// Creates a human-readable representation of the given metadata. diff --git a/src/EFCore/Metadata/Internal/EntityType.cs b/src/EFCore/Metadata/Internal/EntityType.cs index 00e68d5f620..e74bbe1fcd6 100644 --- a/src/EFCore/Metadata/Internal/EntityType.cs +++ b/src/EFCore/Metadata/Internal/EntityType.cs @@ -2249,7 +2249,7 @@ public virtual IEnumerable<Index> FindIndexesInHierarchy(string name) if (!_unnamedIndexes.Remove(index.Properties)) { throw new InvalidOperationException( - CoreStrings.IndexWrongType(index.Properties.Format(), DisplayName(), index.DeclaringEntityType.DisplayName())); + CoreStrings.IndexWrongType(index.DisplayName(), DisplayName(), index.DeclaringEntityType.DisplayName())); } } else @@ -2618,7 +2618,7 @@ private void CheckPropertyNotInUse(Property property) throw new InvalidOperationException( CoreStrings.PropertyInUseIndex( property.Name, DisplayName(), - containingIndex.Properties.Format(), containingIndex.DeclaringEntityType.DisplayName())); + containingIndex.DisplayName(), containingIndex.DeclaringEntityType.DisplayName())); } } diff --git a/src/EFCore/Metadata/Internal/Index.cs b/src/EFCore/Metadata/Internal/Index.cs index f4a2bf54d69..43c887c43b4 100644 --- a/src/EFCore/Metadata/Internal/Index.cs +++ b/src/EFCore/Metadata/Internal/Index.cs @@ -15,10 +15,13 @@ namespace Microsoft.EntityFrameworkCore.Metadata.Internal; public class Index : ConventionAnnotatable, IMutableIndex, IConventionIndex, IIndex { private bool? _isUnique; + private IReadOnlyList<bool>? _isDescending; + private InternalIndexBuilder? _builder; private ConfigurationSource _configurationSource; private ConfigurationSource? _isUniqueConfigurationSource; + private ConfigurationSource? _isDescendingConfigurationSource; // Warning: Never access these fields directly as access needs to be thread-safe private object? _nullableValueFactory; @@ -178,8 +181,8 @@ public virtual bool IsUnique : oldIsUnique; } - private static bool DefaultIsUnique - => false; + private static readonly bool DefaultIsUnique + = false; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -193,6 +196,70 @@ private static bool DefaultIsUnique private void UpdateIsUniqueConfigurationSource(ConfigurationSource configurationSource) => _isUniqueConfigurationSource = configurationSource.Max(_isUniqueConfigurationSource); + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual IReadOnlyList<bool>? IsDescending + { + get => _isDescending ?? DefaultIsDescending; + set => SetIsDescending(value, ConfigurationSource.Explicit); + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual IReadOnlyList<bool>? SetIsDescending(IReadOnlyList<bool>? descending, ConfigurationSource configurationSource) + { + EnsureMutable(); + + if (descending is not null && descending.Count != Properties.Count) + { + throw new ArgumentException( + CoreStrings.InvalidNumberOfIndexSortOrderValues(DisplayName(), descending.Count, Properties.Count), nameof(descending)); + } + + var oldIsDescending = IsDescending; + var isChanging = + (_isDescending is null && descending is not null && descending.Any(desc => desc)) + || (descending is null && _isDescending is not null && _isDescending.Any(desc => desc)) + || (descending is not null && oldIsDescending is not null && !oldIsDescending.SequenceEqual(descending)); + _isDescending = descending; + + if (descending == null) + { + _isDescendingConfigurationSource = null; + } + else + { + UpdateIsDescendingConfigurationSource(configurationSource); + } + + return isChanging + ? DeclaringEntityType.Model.ConventionDispatcher.OnIndexSortOrderChanged(Builder) + : oldIsDescending; + } + + private static readonly bool[]? DefaultIsDescending + = null; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual ConfigurationSource? GetIsDescendingConfigurationSource() + => _isDescendingConfigurationSource; + + private void UpdateIsDescendingConfigurationSource(ConfigurationSource configurationSource) + => _isDescendingConfigurationSource = configurationSource.Max(_isDescendingConfigurationSource); + /// <summary> /// Runs the conventions when an annotation was set or removed. /// </summary> @@ -240,6 +307,16 @@ public virtual DebugView DebugView () => ((IIndex)this).ToDebugString(), () => ((IIndex)this).ToDebugString(MetadataDebugStringOptions.LongDefault)); + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + [DebuggerStepThrough] + public virtual string DisplayName() + => Name is null ? Properties.Format() : $"'{Name}'"; + /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -369,4 +446,15 @@ IEntityType IIndex.DeclaringEntityType [DebuggerStepThrough] bool? IConventionIndex.SetIsUnique(bool? unique, bool fromDataAnnotation) => SetIsUnique(unique, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + [DebuggerStepThrough] + IReadOnlyList<bool>? IConventionIndex.SetIsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation) + => SetIsDescending(descending, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + } diff --git a/src/EFCore/Metadata/Internal/InternalIndexBuilder.cs b/src/EFCore/Metadata/Internal/InternalIndexBuilder.cs index 55ff70cd7ac..f55646fa897 100644 --- a/src/EFCore/Metadata/Internal/InternalIndexBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalIndexBuilder.cs @@ -49,6 +49,34 @@ public virtual bool CanSetIsUnique(bool? unique, ConfigurationSource? configurat => Metadata.IsUnique == unique || configurationSource.Overrides(Metadata.GetIsUniqueConfigurationSource()); + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual InternalIndexBuilder? IsDescending(IReadOnlyList<bool>? descending, ConfigurationSource configurationSource) + { + if (!CanSetIsDescending(descending, configurationSource)) + { + return null; + } + + Metadata.SetIsDescending(descending, configurationSource); + return this; + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual bool CanSetIsDescending(IReadOnlyList<bool>? descending, ConfigurationSource? configurationSource) + => descending is null && Metadata.IsDescending is null + || descending is not null && Metadata.IsDescending is not null && Metadata.IsDescending.SequenceEqual(descending) + || configurationSource.Overrides(Metadata.GetIsDescendingConfigurationSource()); + /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -107,4 +135,26 @@ bool IConventionIndexBuilder.CanSetIsUnique(bool? unique, bool fromDataAnnotatio => CanSetIsUnique( unique, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + IConventionIndexBuilder? IConventionIndexBuilder.IsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation) + => IsDescending( + descending, + fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + bool IConventionIndexBuilder.CanSetIsDescending(IReadOnlyList<bool>? descending, bool fromDataAnnotation) + => CanSetIsDescending( + descending, + fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); } diff --git a/src/EFCore/Metadata/RuntimeIndex.cs b/src/EFCore/Metadata/RuntimeIndex.cs index 109d734f507..c5ecc2c41e3 100644 --- a/src/EFCore/Metadata/RuntimeIndex.cs +++ b/src/EFCore/Metadata/RuntimeIndex.cs @@ -55,6 +55,15 @@ public RuntimeIndex( /// </summary> public virtual RuntimeEntityType DeclaringEntityType { get; } + /// <summary> + /// Always returns an empty array for <see cref="RuntimeIndex" />. + /// </summary> + IReadOnlyList<bool> IReadOnlyIndex.IsDescending + { + [DebuggerStepThrough] + get => throw new InvalidOperationException(CoreStrings.RuntimeModelMissingData); + } + /// <summary> /// Returns a string that represents the current object. /// </summary> diff --git a/src/EFCore/Properties/CoreStrings.Designer.cs b/src/EFCore/Properties/CoreStrings.Designer.cs index ecebccc29e4..9e1024ec553 100644 --- a/src/EFCore/Properties/CoreStrings.Designer.cs +++ b/src/EFCore/Properties/CoreStrings.Designer.cs @@ -1118,12 +1118,12 @@ public static string IndexPropertiesWrongEntity(object? indexProperties, object? indexProperties, entityType); /// <summary> - /// The index {indexProperties} cannot be removed from the entity type '{entityType}' because it is defined on the entity type '{otherEntityType}'. + /// The index {index} cannot be removed from the entity type '{entityType}' because it is defined on the entity type '{otherEntityType}'. /// </summary> - public static string IndexWrongType(object? indexProperties, object? entityType, object? otherEntityType) + public static string IndexWrongType(object? index, object? entityType, object? otherEntityType) => string.Format( - GetString("IndexWrongType", nameof(indexProperties), nameof(entityType), nameof(otherEntityType)), - indexProperties, entityType, otherEntityType); + GetString("IndexWrongType", nameof(index), nameof(entityType), nameof(otherEntityType)), + index, entityType, otherEntityType); /// <summary> /// The property '{property}' cannot be ignored on entity type '{entityType}' because it's declared on the base entity type '{baseEntityType}'. To exclude this property from your model, use the [NotMapped] attribute or 'Ignore' on the base type in 'OnModelCreating'. @@ -1219,6 +1219,14 @@ public static string InvalidNavigationWithInverseProperty(object? property, obje GetString("InvalidNavigationWithInverseProperty", "0_property", "1_entityType", nameof(referencedProperty), nameof(referencedEntityType)), property, entityType, referencedProperty, referencedEntityType); + /// <summary> + /// Invalid number of index sort order values provided for {indexProperties}: {numValues} values were provided, but the index has {numProperties} properties. + /// </summary> + public static string InvalidNumberOfIndexSortOrderValues(object? indexProperties, object? numValues, object? numProperties) + => string.Format( + GetString("InvalidNumberOfIndexSortOrderValues", nameof(indexProperties), nameof(numValues), nameof(numProperties)), + indexProperties, numValues, numProperties); + /// <summary> /// The specified poolSize must be greater than 0. /// </summary> diff --git a/src/EFCore/Properties/CoreStrings.resx b/src/EFCore/Properties/CoreStrings.resx index e2872bc118d..4578370aa47 100644 --- a/src/EFCore/Properties/CoreStrings.resx +++ b/src/EFCore/Properties/CoreStrings.resx @@ -536,7 +536,7 @@ <value>The specified index properties {indexProperties} are not declared on the entity type '{entityType}'. Ensure that index properties are declared on the target entity type.</value> </data> <data name="IndexWrongType" xml:space="preserve"> - <value>The index {indexProperties} cannot be removed from the entity type '{entityType}' because it is defined on the entity type '{otherEntityType}'.</value> + <value>The index {index} cannot be removed from the entity type '{entityType}' because it is defined on the entity type '{otherEntityType}'.</value> </data> <data name="InheritedPropertyCannotBeIgnored" xml:space="preserve"> <value>The property '{property}' cannot be ignored on entity type '{entityType}' because it's declared on the base entity type '{baseEntityType}'. To exclude this property from your model, use the [NotMapped] attribute or 'Ignore' on the base type in 'OnModelCreating'.</value> @@ -574,6 +574,9 @@ <data name="InvalidNavigationWithInverseProperty" xml:space="preserve"> <value>The [InverseProperty] attribute on property '{1_entityType}.{0_property}' is not valid. The property '{referencedProperty}' is not a valid navigation on the related type '{referencedEntityType}'. Ensure that the property exists and is a valid reference or collection navigation.</value> </data> + <data name="InvalidNumberOfIndexSortOrderValues" xml:space="preserve"> + <value>Invalid number of index sort order values provided for {indexProperties}: {numValues} values were provided, but the index has {numProperties} properties.</value> + </data> <data name="InvalidPoolSize" xml:space="preserve"> <value>The specified poolSize must be greater than 0.</value> </data>
diff --git a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs index 22778a022c3..9bae3036bc4 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs @@ -963,6 +963,9 @@ public void CreateIndexOperation_required_args() Assert.Equal("IX_Post_Title", o.Name); Assert.Equal("Post", o.Table); Assert.Equal(new[] { "Title" }, o.Columns); + Assert.False(o.IsUnique); + Assert.Null(o.IsDescending); + Assert.Null(o.Filter); }); [ConditionalFact] @@ -973,8 +976,9 @@ public void CreateIndexOperation_all_args() Name = "IX_Post_Title", Schema = "dbo", Table = "Post", - Columns = new[] { "Title" }, + Columns = new[] { "Title", "Name" }, IsUnique = true, + IsDescending = new[] { true, false }, Filter = "[Title] IS NOT NULL" }, "mb.CreateIndex(" @@ -985,18 +989,22 @@ public void CreateIndexOperation_all_args() + _eol + " table: \"Post\"," + _eol - + " column: \"Title\"," + + " columns: new[] { \"Title\", \"Name\" }," + _eol + " unique: true," + _eol + + " descending: new[] { true, false }," + + _eol + " filter: \"[Title] IS NOT NULL\");", o => { Assert.Equal("IX_Post_Title", o.Name); Assert.Equal("dbo", o.Schema); Assert.Equal("Post", o.Table); - Assert.Equal(new[] { "Title" }, o.Columns); + Assert.Equal(new[] { "Title", "Name" }, o.Columns); Assert.True(o.IsUnique); + Assert.Equal(new[] { true, false }, o.IsDescending); + Assert.Equal("[Title] IS NOT NULL", o.Filter); }); [ConditionalFact] diff --git a/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs b/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs index 2779ba35261..b6e790757ae 100644 --- a/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs +++ b/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs @@ -164,6 +164,14 @@ private class EntityWithGenericProperty<TProperty> public TProperty Property { get; set; } } + private class EntityWithThreeProperties + { + public int Id { get; set; } + public int X { get; set; } + public int Y { get; set; } + public int Z { get; set; } + } + [Index(nameof(FirstName), nameof(LastName))] private class EntityWithIndexAttribute { @@ -4231,7 +4239,7 @@ public virtual void Index_Fluent_APIs_are_properly_generated() o => Assert.True(o.GetEntityTypes().Single().GetIndexes().Single().IsClustered())); [ConditionalFact] - public virtual void Index_isUnique_is_stored_in_snapshot() + public virtual void Index_IsUnique_is_stored_in_snapshot() => Test( builder => { @@ -4261,6 +4269,76 @@ public virtual void Index_isUnique_is_stored_in_snapshot() });"), o => Assert.True(o.GetEntityTypes().First().GetIndexes().First().IsUnique)); + [ConditionalFact] + public virtual void Index_IsDescending_is_stored_in_snapshot() + => Test( + builder => + { + builder.Entity<EntityWithThreeProperties>( + e => + { + e.HasIndex(t => new { t.X, t.Y, t.Z }, "IX_empty"); + e.HasIndex(t => new { t.X, t.Y, t.Z }, "IX_all_ascending") + .IsDescending(false, false, false); + e.HasIndex(t => new { t.X, t.Y, t.Z }, "IX_all_descending") + .IsDescending(true, true, true); + e.HasIndex(t => new { t.X, t.Y, t.Z }, "IX_mixed") + .IsDescending(false, true, false); + }); + }, + AddBoilerPlate( + GetHeading() + + @" + modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithThreeProperties"", b => + { + b.Property<int>(""Id"") + .ValueGeneratedOnAdd() + .HasColumnType(""int""); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>(""Id""), 1L, 1); + + b.Property<int>(""X"") + .HasColumnType(""int""); + + b.Property<int>(""Y"") + .HasColumnType(""int""); + + b.Property<int>(""Z"") + .HasColumnType(""int""); + + b.HasKey(""Id""); + + b.HasIndex(new[] { ""X"", ""Y"", ""Z"" }, ""IX_all_ascending"") + .IsDescending(false, false, false); + + b.HasIndex(new[] { ""X"", ""Y"", ""Z"" }, ""IX_all_descending"") + .IsDescending(true, true, true); + + b.HasIndex(new[] { ""X"", ""Y"", ""Z"" }, ""IX_empty""); + + b.HasIndex(new[] { ""X"", ""Y"", ""Z"" }, ""IX_mixed"") + .IsDescending(false, true, false); + + b.ToTable(""EntityWithThreeProperties""); + });"), + o => + { + var entityType = o.GetEntityTypes().Single(); + Assert.Equal(4, entityType.GetIndexes().Count()); + + var emptyIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_empty"); + Assert.Null(emptyIndex.IsDescending); + + var allAscendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_ascending"); + Assert.Equal(new[] { false, false, false}, allAscendingIndex.IsDescending); + + var allDescendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_descending"); + Assert.Equal(new[] { true, true, true }, allDescendingIndex.IsDescending); + + var mixedIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_mixed"); + Assert.Equal(new[] { false, true, false }, mixedIndex.IsDescending); + }); + [ConditionalFact] public virtual void Index_database_name_annotation_is_stored_in_snapshot_as_fluent_api() => Test( diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs index b0a56787422..33ed76d34e6 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs @@ -553,7 +553,8 @@ public void Entity_with_indexes_and_use_data_annotations_false_always_generates_ x.Property<int>("C"); x.HasKey("Id"); x.HasIndex(new[] { "A", "B" }, "IndexOnAAndB") - .IsUnique(); + .IsUnique() + .IsDescending(false, true); x.HasIndex(new[] { "B", "C" }, "IndexOnBAndC") .HasFilter("Filter SQL") .HasAnnotation("AnnotationName", "AnnotationValue"); @@ -598,7 +599,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity<EntityWithIndexes>(entity => { entity.HasIndex(e => new { e.A, e.B }, ""IndexOnAAndB"") - .IsUnique(); + .IsUnique() + .IsDescending(false, true); entity.HasIndex(e => new { e.B, e.C }, ""IndexOnBAndC"") .HasFilter(""Filter SQL"") @@ -633,7 +635,8 @@ public void Entity_with_indexes_and_use_data_annotations_true_generates_fluent_A x.Property<int>("C"); x.HasKey("Id"); x.HasIndex(new[] { "A", "B" }, "IndexOnAAndB") - .IsUnique(); + .IsUnique() + .IsDescending(false, true); x.HasIndex(new[] { "B", "C" }, "IndexOnBAndC") .HasFilter("Filter SQL") .HasAnnotation("AnnotationName", "AnnotationValue"); @@ -696,6 +699,107 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) model => Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes").GetIndexes().Count())); + [ConditionalFact] + public void Indexes_with_descending() + => Test( + modelBuilder => modelBuilder + .Entity( + "EntityWithIndexes", + x => + { + x.Property<int>("Id"); + x.Property<int>("X"); + x.Property<int>("Y"); + x.Property<int>("Z"); + x.HasKey("Id"); + x.HasIndex(new[] { "X", "Y", "Z" }, "IX_empty"); + x.HasIndex(new[] { "X", "Y", "Z" }, "IX_all_ascending") + .IsDescending(false, false, false); + x.HasIndex(new[] { "X", "Y", "Z" }, "IX_all_descending") + .IsDescending(true, true, true); + x.HasIndex(new[] { "X", "Y", "Z" }, "IX_mixed") + .IsDescending(false, true, false); + }), + new ModelCodeGenerationOptions { UseDataAnnotations = false }, + code => + { + AssertFileContents( + @"using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace TestNamespace +{ + public partial class TestDbContext : DbContext + { + public TestDbContext() + { + } + + public TestDbContext(DbContextOptions<TestDbContext> options) + : base(options) + { + } + + public virtual DbSet<EntityWithIndexes> EntityWithIndexes { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { +#warning " + + DesignStrings.SensitiveInformationWarning + + @" + optionsBuilder.UseSqlServer(""Initial Catalog=TestDatabase""); + } + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity<EntityWithIndexes>(entity => + { + entity.HasIndex(e => new { e.X, e.Y, e.Z }, ""IX_all_ascending"") + .IsDescending(false, false, false); + + entity.HasIndex(e => new { e.X, e.Y, e.Z }, ""IX_all_descending"") + .IsDescending(true, true, true); + + entity.HasIndex(e => new { e.X, e.Y, e.Z }, ""IX_empty""); + + entity.HasIndex(e => new { e.X, e.Y, e.Z }, ""IX_mixed"") + .IsDescending(false, true, false); + + entity.Property(e => e.Id).UseIdentityColumn(); + }); + + OnModelCreatingPartial(modelBuilder); + } + + partial void OnModelCreatingPartial(ModelBuilder modelBuilder); + } +} +", + code.ContextFile); + }, + model => + { + var entityType = model.FindEntityType("TestNamespace.EntityWithIndexes")!; + Assert.Equal(4, entityType.GetIndexes().Count()); + + var emptyIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_empty"); + Assert.Null(emptyIndex.IsDescending); + + var allAscendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_ascending"); + Assert.Equal(new[] { false, false, false }, allAscendingIndex.IsDescending); + + var allDescendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_descending"); + Assert.Equal(new[] { true, true, true }, allDescendingIndex.IsDescending); + + var mixedIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_mixed"); + Assert.Equal(new[] { false, true, false }, mixedIndex.IsDescending); + }); + [ConditionalFact] public void Entity_lambda_uses_correct_identifiers() => Test( diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs index b368816418b..b14b813c5e0 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs @@ -247,7 +247,7 @@ public partial class Vista }); [ConditionalFact] - public void IndexAttribute_is_generated_for_multiple_indexes_with_name_unique() + public void IndexAttribute_is_generated_for_multiple_indexes_with_name_unique_descending() => Test( modelBuilder => modelBuilder .Entity( @@ -260,7 +260,8 @@ public void IndexAttribute_is_generated_for_multiple_indexes_with_name_unique() x.Property<int>("C"); x.HasKey("Id"); x.HasIndex(new[] { "A", "B" }, "IndexOnAAndB") - .IsUnique(); + .IsUnique() + .IsDescending(true, false); x.HasIndex(new[] { "B", "C" }, "IndexOnBAndC"); x.HasIndex("C"); }), @@ -277,7 +278,7 @@ public void IndexAttribute_is_generated_for_multiple_indexes_with_name_unique() namespace TestNamespace { [Index(""C"")] - [Index(""A"", ""B"", Name = ""IndexOnAAndB"", IsUnique = true)] + [Index(""A"", ""B"", Name = ""IndexOnAAndB"", IsUnique = true, IsDescending = new[] { true, false })] [Index(""B"", ""C"", Name = ""IndexOnBAndC"")] public partial class EntityWithIndexes { diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs index acfee0d4baa..6cf32d7cebf 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs @@ -1376,6 +1376,90 @@ public void Unique_index_composite_foreign_key() Assert.Equal(parent.FindPrimaryKey(), fk.PrincipalKey); } + [ConditionalFact] + public void Index_descending() + { + var table = new DatabaseTable + { + Database = Database, + Name = "SomeTable", + Columns = + { + new DatabaseColumn + { + Table = Table, + Name = "X", + StoreType = "int" + }, + new DatabaseColumn + { + Table = Table, + Name = "Y", + StoreType = "int" + }, + new DatabaseColumn + { + Table = Table, + Name = "Z", + StoreType = "int" + } + } + }; + + table.Indexes.Add( + new DatabaseIndex + { + Table = Table, + Name = "IX_empty", + Columns = { table.Columns[0], table.Columns[1], table.Columns[2] } + }); + + table.Indexes.Add( + new DatabaseIndex + { + Table = Table, + Name = "IX_all_ascending", + Columns = { table.Columns[0], table.Columns[1], table.Columns[2] }, + IsDescending = { false, false, false } + }); + + table.Indexes.Add( + new DatabaseIndex + { + Table = Table, + Name = "IX_all_descending", + Columns = { table.Columns[0], table.Columns[1], table.Columns[2] }, + IsDescending = { true, true, true } + }); + + table.Indexes.Add( + new DatabaseIndex + { + Table = Table, + Name = "IX_mixed", + Columns = { table.Columns[0], table.Columns[1], table.Columns[2] }, + IsDescending = { false, true, false } + }); + + var model = _factory.Create( + new DatabaseModel { Tables = { table } }, + new ModelReverseEngineerOptions { NoPluralize = true }); + + var entityType = model.FindEntityType("SomeTable")!; + + var emptyIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_empty"); + Assert.Null(emptyIndex.IsDescending); + + var allAscendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_ascending"); + Assert.Null(allAscendingIndex.IsDescending); + + var allDescendingIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_all_descending"); + Assert.Equal(new[] { true, true, true }, allDescendingIndex.IsDescending); + + var mixedIndex = Assert.Single(entityType.GetIndexes(), i => i.Name == "IX_mixed"); + Assert.Equal(new[] { false, true, false }, mixedIndex.IsDescending); + } + [ConditionalFact] public void Unique_names() { diff --git a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs index ade454b8d5a..8e8604dd05f 100644 --- a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs @@ -1042,6 +1042,12 @@ public virtual Task Create_index() Assert.Same(table.Columns.Single(c => c.Name == "FirstName"), Assert.Single(index.Columns)); Assert.Equal("IX_People_FirstName", index.Name); Assert.False(index.IsUnique); + + if (index.IsDescending.Count > 0) + { + Assert.Collection(index.IsDescending, descending => Assert.False(descending)); + } + Assert.Null(index.Filter); }); @@ -1064,6 +1070,88 @@ public virtual Task Create_index_unique() Assert.True(index.IsUnique); }); + [ConditionalFact] + public virtual Task Create_index_descending() + => Test( + builder => builder.Entity( + "People", e => + { + e.Property<int>("Id"); + e.Property<int>("X"); + }), + builder => { }, + builder => builder.Entity("People").HasIndex("X").IsDescending(true), + model => + { + var table = Assert.Single(model.Tables); + var index = Assert.Single(table.Indexes); + Assert.Collection(index.IsDescending, Assert.True); + }); + + [ConditionalFact] + public virtual Task Create_index_descending_mixed() + => Test( + builder => builder.Entity( + "People", e => + { + e.Property<int>("Id"); + e.Property<int>("X"); + e.Property<int>("Y"); + e.Property<int>("Z"); + }), + builder => { }, + builder => builder.Entity("People") + .HasIndex("X", "Y", "Z") + .IsDescending(false, true, false), + model => + { + var table = Assert.Single(model.Tables); + var index = Assert.Single(table.Indexes); + Assert.Collection(index.IsDescending, Assert.False, Assert.True, Assert.False); + }); + + [ConditionalFact] + public virtual Task Alter_index_make_unique() + => Test( + builder => builder.Entity( + "People", e => + { + e.Property<int>("Id"); + e.Property<int>("X"); + }), + builder => builder.Entity("People").HasIndex("X"), + builder => builder.Entity("People").HasIndex("X").IsUnique(), + model => + { + var table = Assert.Single(model.Tables); + var index = Assert.Single(table.Indexes); + Assert.True(index.IsUnique); + }); + + [ConditionalFact] + public virtual Task Alter_index_change_sort_order() + => Test( + builder => builder.Entity( + "People", e => + { + e.Property<int>("Id"); + e.Property<int>("X"); + e.Property<int>("Y"); + e.Property<int>("Z"); + }), + builder => builder.Entity("People") + .HasIndex("X", "Y", "Z") + .IsDescending(true, false, true), + builder => builder.Entity("People") + .HasIndex("X", "Y", "Z") + .IsDescending(false, true, false), + model => + { + var table = Assert.Single(model.Tables); + var index = Assert.Single(table.Indexes); + Assert.Collection(index.IsDescending, Assert.False, Assert.True, Assert.False); + }); + [ConditionalFact] public virtual Task Create_index_with_filter() => Test( diff --git a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs index 754c5b88990..b50fdd57f5c 100644 --- a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs +++ b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs @@ -1308,6 +1308,24 @@ public virtual void Detects_duplicate_index_names_within_hierarchy_with_differen modelBuilder); } + [ConditionalFact] + public virtual void Detects_duplicate_index_names_within_hierarchy_with_different_sort_orders() + { + var modelBuilder = CreateConventionalModelBuilder(); + modelBuilder.Entity<Animal>(); + modelBuilder.Entity<Cat>().HasIndex(c => c.Name).HasDatabaseName("IX_Animal_Name") + .IsDescending(true); + modelBuilder.Entity<Dog>().HasIndex(d => d.Name).HasDatabaseName("IX_Animal_Name") + .IsDescending(false); + + VerifyError( + RelationalStrings.DuplicateIndexSortOrdersMismatch( + "{'" + nameof(Dog.Name) + "'}", nameof(Dog), + "{'" + nameof(Cat.Name) + "'}", nameof(Cat), + nameof(Animal), "IX_Animal_Name"), + modelBuilder); + } + [ConditionalFact] public virtual void Detects_duplicate_index_names_within_hierarchy_with_different_filters() { diff --git a/test/EFCore.Relational.Tests/Migrations/Operations/CreateIndexOperationTest.cs b/test/EFCore.Relational.Tests/Migrations/Operations/CreateIndexOperationTest.cs new file mode 100644 index 00000000000..c1ea868be05 --- /dev/null +++ b/test/EFCore.Relational.Tests/Migrations/Operations/CreateIndexOperationTest.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.EntityFrameworkCore.Migrations.Operations; + +public class CreateIndexOperationTest +{ + [Fact] + public void IsDescending_count_matches_column_count() + { + var operation = new CreateIndexOperation(); + + operation.IsDescending = new[] { true }; + Assert.Throws<ArgumentException>(() => operation.Columns = new[] { "X", "Y" }); + + operation.IsDescending = null; + + operation.Columns = new[] { "X", "Y" }; + Assert.Throws<ArgumentException>(() => operation.IsDescending = new[] { true }); + } +} diff --git a/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs b/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs index 31229cd649b..9daa1ebd398 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs @@ -505,6 +505,7 @@ public void RemoveAllConventions() Conventions.IndexAnnotationChangedConventions.Clear(); Conventions.IndexRemovedConventions.Clear(); Conventions.IndexUniquenessChangedConventions.Clear(); + Conventions.IndexSortOrderChangedConventions.Clear(); Conventions.KeyAddedConventions.Clear(); Conventions.KeyAnnotationChangedConventions.Clear(); Conventions.KeyRemovedConventions.Clear(); diff --git a/test/EFCore.SqlServer.FunctionalTests/Migrations/MigrationsSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Migrations/MigrationsSqlServerTest.cs index 9e317426c62..cfbeec406c4 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Migrations/MigrationsSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Migrations/MigrationsSqlServerTest.cs @@ -19,7 +19,7 @@ public MigrationsSqlServerTest(MigrationsSqlServerFixture fixture, ITestOutputHe : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); - // Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); + //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } public override async Task Create_table() @@ -1246,6 +1246,42 @@ FROM [sys].[default_constraints] [d] @"CREATE UNIQUE INDEX [IX_People_FirstName_LastName] ON [People] ([FirstName], [LastName]) WHERE [FirstName] IS NOT NULL AND [LastName] IS NOT NULL;"); } + public override async Task Create_index_descending() + { + await base.Create_index_descending(); + + AssertSql( + @"CREATE INDEX [IX_People_X] ON [People] ([X] DESC);"); + } + + public override async Task Create_index_descending_mixed() + { + await base.Create_index_descending_mixed(); + + AssertSql( + @"CREATE INDEX [IX_People_X_Y_Z] ON [People] ([X], [Y] DESC, [Z]);"); + } + + public override async Task Alter_index_make_unique() + { + await base.Alter_index_make_unique(); + + AssertSql( + @"DROP INDEX [IX_People_X] ON [People];", + // + @"CREATE UNIQUE INDEX [IX_People_X] ON [People] ([X]);"); + } + + public override async Task Alter_index_change_sort_order() + { + await base.Alter_index_change_sort_order(); + + AssertSql( + @"DROP INDEX [IX_People_X_Y_Z] ON [People];", + // + @"CREATE INDEX [IX_People_X_Y_Z] ON [People] ([X], [Y] DESC, [Z]);"); + } + public override async Task Create_index_with_filter() { await base.Create_index_with_filter(); diff --git a/test/EFCore.Tests/Metadata/Conventions/ConventionDispatcherTest.cs b/test/EFCore.Tests/Metadata/Conventions/ConventionDispatcherTest.cs index b25f94fd245..2e83815ef7f 100644 --- a/test/EFCore.Tests/Metadata/Conventions/ConventionDispatcherTest.cs +++ b/test/EFCore.Tests/Metadata/Conventions/ConventionDispatcherTest.cs @@ -2983,6 +2983,104 @@ public void ProcessIndexUniquenessChanged( } } +#nullable enable + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + [ConditionalTheory] + public void OnIndexSortOrderChanged_calls_conventions_in_order(bool useBuilder, bool useScope) + { + var conventions = new ConventionSet(); + + var convention1 = new IndexSortOrderChangedConvention(terminate: false); + var convention2 = new IndexSortOrderChangedConvention(terminate: true); + var convention3 = new IndexSortOrderChangedConvention(terminate: false); + conventions.IndexSortOrderChangedConventions.Add(convention1); + conventions.IndexSortOrderChangedConventions.Add(convention2); + conventions.IndexSortOrderChangedConventions.Add(convention3); + + var builder = new InternalModelBuilder(new Model(conventions)); + var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention)!; + var index = entityBuilder.HasIndex(new List<string> { "OrderId" }, ConfigurationSource.Convention)!.Metadata; + + var scope = useScope ? builder.Metadata.ConventionDispatcher.DelayConventions() : null; + + if (useBuilder) + { + index.Builder.IsDescending(new[] { true }, ConfigurationSource.Convention); + } + else + { + index.IsDescending = new[] { true }; + } + + if (useScope) + { + Assert.Empty(convention1.Calls); + Assert.Empty(convention2.Calls); + scope!.Dispose(); + } + + Assert.Equal(new[] { new[] { true } }, convention1.Calls); + Assert.Equal(new[] { new[] { true } }, convention2.Calls); + Assert.Empty(convention3.Calls); + + if (useBuilder) + { + index.Builder.IsDescending(new[] { true }, ConfigurationSource.Convention); + } + else + { + index.IsDescending = new[] { true }; + } + + Assert.Equal(new[] { new[] { true } }, convention1.Calls); + Assert.Equal(new[] { new[] { true } }, convention2.Calls); + Assert.Empty(convention3.Calls); + + if (useBuilder) + { + index.Builder.IsDescending(new[] { false }, ConfigurationSource.Convention); + } + else + { + index.IsDescending = new[] { false }; + } + + Assert.Equal(new[] { new[] { true }, new[] { false } }, convention1.Calls); + Assert.Equal(new[] { new[] { true }, new[] { false } }, convention2.Calls); + Assert.Empty(convention3.Calls); + + Assert.Same(index, entityBuilder.Metadata.RemoveIndex(index.Properties)); + } + + private class IndexSortOrderChangedConvention : IIndexSortOrderChangedConvention + { + private readonly bool _terminate; + public readonly List<IReadOnlyList<bool>?> Calls = new(); + + public IndexSortOrderChangedConvention(bool terminate) + { + _terminate = terminate; + } + + public void ProcessIndexSortOrderChanged( + IConventionIndexBuilder indexBuilder, + IConventionContext<IReadOnlyList<bool>?> context) + { + Assert.NotNull(indexBuilder.Metadata.Builder); + + Calls.Add(indexBuilder.Metadata.IsDescending); + + if (_terminate) + { + context.StopProcessing(); + } + } + } +#nullable restore + [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] diff --git a/test/EFCore.Tests/Metadata/Conventions/IndexAttributeConventionTest.cs b/test/EFCore.Tests/Metadata/Conventions/IndexAttributeConventionTest.cs index 829a87585ef..e989e1dfc84 100644 --- a/test/EFCore.Tests/Metadata/Conventions/IndexAttributeConventionTest.cs +++ b/test/EFCore.Tests/Metadata/Conventions/IndexAttributeConventionTest.cs @@ -28,6 +28,7 @@ public void IndexAttribute_overrides_configuration_from_convention() var indexProperties = new List<string> { propABuilder.Metadata.Name, propBBuilder.Metadata.Name }; var indexBuilder = entityBuilder.HasIndex(indexProperties, "IndexOnAAndB", ConfigurationSource.Convention); indexBuilder.IsUnique(false, ConfigurationSource.Convention); + indexBuilder.IsDescending(new[] { false, true }, ConfigurationSource.Convention); RunConvention(entityBuilder); RunConvention(modelBuilder); @@ -35,8 +36,11 @@ public void IndexAttribute_overrides_configuration_from_convention() var index = entityBuilder.Metadata.GetIndexes().Single(); Assert.Equal(ConfigurationSource.DataAnnotation, index.GetConfigurationSource()); Assert.Equal("IndexOnAAndB", index.Name); + Assert.True(index.IsUnique); Assert.Equal(ConfigurationSource.DataAnnotation, index.GetIsUniqueConfigurationSource()); + Assert.Equal(new[] { true, false }, index.IsDescending); + Assert.Equal(ConfigurationSource.DataAnnotation, index.GetIsDescendingConfigurationSource()); Assert.Collection( index.Properties, prop0 => Assert.Equal("A", prop0.Name), @@ -50,7 +54,8 @@ public void IndexAttribute_can_be_overriden_using_explicit_configuration() var entityBuilder = modelBuilder.Entity<EntityWithIndex>(); entityBuilder.HasIndex(new[] { "A", "B" }, "IndexOnAAndB") - .IsUnique(false); + .IsUnique(false) + .IsDescending(false, true); modelBuilder.Model.FinalizeModel(); @@ -59,6 +64,8 @@ public void IndexAttribute_can_be_overriden_using_explicit_configuration() Assert.Equal("IndexOnAAndB", index.Name); Assert.False(index.IsUnique); Assert.Equal(ConfigurationSource.Explicit, index.GetIsUniqueConfigurationSource()); + Assert.Equal(new[] { false, true }, index.IsDescending); + Assert.Equal(ConfigurationSource.Explicit, index.GetIsDescendingConfigurationSource()); Assert.Collection( index.Properties, prop0 => Assert.Equal("A", prop0.Name), @@ -316,7 +323,7 @@ private IndexAttributeConvention CreateIndexAttributeConvention() private ProviderConventionSetBuilderDependencies CreateDependencies() => InMemoryTestHelpers.Instance.CreateContextServices().GetRequiredService<ProviderConventionSetBuilderDependencies>(); - [Index(nameof(A), nameof(B), Name = "IndexOnAAndB", IsUnique = true)] + [Index(nameof(A), nameof(B), Name = "IndexOnAAndB", IsUnique = true, IsDescending = new[] { true, false })] private class EntityWithIndex { public int Id { get; set; } diff --git a/test/EFCore.Tests/ModelBuilding/ModelBuilderGenericTest.cs b/test/EFCore.Tests/ModelBuilding/ModelBuilderGenericTest.cs index f4e025e6f25..c7a2e0af068 100644 --- a/test/EFCore.Tests/ModelBuilding/ModelBuilderGenericTest.cs +++ b/test/EFCore.Tests/ModelBuilding/ModelBuilderGenericTest.cs @@ -581,6 +581,9 @@ public override TestIndexBuilder<TEntity> HasAnnotation(string annotation, objec public override TestIndexBuilder<TEntity> IsUnique(bool isUnique = true) => new GenericTestIndexBuilder<TEntity>(IndexBuilder.IsUnique(isUnique)); + public override TestIndexBuilder<TEntity> IsDescending(params bool[] isDescending) + => new GenericTestIndexBuilder<TEntity>(IndexBuilder.IsDescending(isDescending)); + IndexBuilder<TEntity> IInfrastructure<IndexBuilder<TEntity>>.Instance => IndexBuilder; } diff --git a/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs b/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs index a657349bf48..6904a9b0078 100644 --- a/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs +++ b/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs @@ -686,6 +686,9 @@ public override TestIndexBuilder<TEntity> HasAnnotation(string annotation, objec public override TestIndexBuilder<TEntity> IsUnique(bool isUnique = true) => new NonGenericTestIndexBuilder<TEntity>(IndexBuilder.IsUnique(isUnique)); + public override TestIndexBuilder<TEntity> IsDescending(params bool[] isDescending) + => new NonGenericTestIndexBuilder<TEntity>(IndexBuilder.IsDescending(isDescending)); + IndexBuilder IInfrastructure<IndexBuilder>.Instance => IndexBuilder; } diff --git a/test/EFCore.Tests/ModelBuilding/ModelBuilderTestBase.cs b/test/EFCore.Tests/ModelBuilding/ModelBuilderTestBase.cs index c54b376fa60..368b3aaa84f 100644 --- a/test/EFCore.Tests/ModelBuilding/ModelBuilderTestBase.cs +++ b/test/EFCore.Tests/ModelBuilding/ModelBuilderTestBase.cs @@ -362,6 +362,7 @@ public abstract class TestIndexBuilder<TEntity> public abstract TestIndexBuilder<TEntity> HasAnnotation(string annotation, object? value); public abstract TestIndexBuilder<TEntity> IsUnique(bool isUnique = true); + public abstract TestIndexBuilder<TEntity> IsDescending(params bool[] isDescending); } public abstract class TestPropertyBuilder<TProperty> diff --git a/test/EFCore.Tests/ModelBuilding/NonRelationshipTestBase.cs b/test/EFCore.Tests/ModelBuilding/NonRelationshipTestBase.cs index af02579ec2f..d69d92909eb 100644 --- a/test/EFCore.Tests/ModelBuilding/NonRelationshipTestBase.cs +++ b/test/EFCore.Tests/ModelBuilding/NonRelationshipTestBase.cs @@ -1722,6 +1722,7 @@ public virtual void Can_add_multiple_indexes() entityBuilder.HasIndex(ix => ix.Id).IsUnique(); entityBuilder.HasIndex(ix => ix.Name).HasAnnotation("A1", "V1"); entityBuilder.HasIndex(ix => ix.Id, "Named"); + entityBuilder.HasIndex(ix => ix.Id, "Descending").IsDescending(true); var model = modelBuilder.FinalizeModel(); @@ -1729,7 +1730,7 @@ public virtual void Can_add_multiple_indexes() var idProperty = entityType.FindProperty(nameof(Customer.Id)); var nameProperty = entityType.FindProperty(nameof(Customer.Name)); - Assert.Equal(3, entityType.GetIndexes().Count()); + Assert.Equal(4, entityType.GetIndexes().Count()); var firstIndex = entityType.FindIndex(idProperty); Assert.True(firstIndex.IsUnique); var secondIndex = entityType.FindIndex(nameProperty); @@ -1737,6 +1738,8 @@ public virtual void Can_add_multiple_indexes() Assert.Equal("V1", secondIndex["A1"]); var namedIndex = entityType.FindIndex("Named"); Assert.False(namedIndex.IsUnique); + var descendingIndex = entityType.FindIndex("Descending"); + Assert.Equal(new[] { true }, descendingIndex.IsDescending); } [ConditionalFact]
Support for index ordering (ASC/DESC) After discussion on #11846, we decided that the way to handle this is to allow multiple named indexes to be created over columns, while still preserving the current semantics (i.e. addressing by ordered property set) for unnamed indexes. Original issue: Add support for column sort order to migrations, metadata, and reverse engineering. - Add API to specific ascending/descending columns in an index ( `CREATE INDEX IX_1 ON Table ( Col1 DESC, Col2 ASC)` ) - Add to reverse engineering database model ([prototype here](https://github.com/natemcmaster/EntityFramework/tree/scaffold-sort-order)) - Adapt to older version of SQLite (sort order is not supported < 3.8.9)
Is this going to happen anytime soon? Using EfCore.Shaman to workaround this issue and others at the moment... @jjxtra This issue is in the Backlog milestone. This means that it is not going to happen for the 2.1 release. We will re-assess the backlog following the 2.1 release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources. Note that this is being done in Npgsql as part of https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/pull/705. It would ideally be better to have implemented here as well so that Npgsql can align (and reuse the same SortOrder enum, possibly). Hello any news ont this feature @bhugot This issue is in the Backlog milestone. This means that it is not currently planned for any upcoming release. We will re-assess the backlog for 5.0 and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources. Another variant of this issue is for having multiple indexes on the same column, but with different collations (supported by PostgreSQL and Sqlite, but not SQL Server and MySQL). Clearing Milestone to reconsider this, or part of this, for 5.0 per [this comment](https://github.com/dotnet/efcore/pull/21012#issuecomment-632859604). I hope this makes it for the next release. Our entity has a primary key `TenantId bigint, IsPriority bit` Ideally, we want to be able specify `DESC` on the `IsPriority`, so that values of 1 are naturally ordered before values of 0 when we select the rows of a given tenant. As a work around, we have had to changed the name of the property to `IsNotPriority`, so that the priority rows have a 0 and are ordered first in the index. It's a shame to have to improperly name things because of limitations of EF.
2022-01-19T00:16:41Z
0.2
['Microsoft.EntityFrameworkCore.Migrations.Operations.CreateIndexOperationTest.IsDescending_count_matches_column_count']
[]
dotnet/efcore
dotnet__efcore-27128
bbbd2c88778ec693bd0e857dd770093f32a2f8a4
diff --git a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs index 4a2b63721b5..814ea482535 100644 --- a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs +++ b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs @@ -40,11 +40,8 @@ public static int Execute(string? context, Assembly assembly, Assembly startupAs _assembly = assembly; _startupAssembly = startupAssembly; - var app = new CommandLineApplication - { - Name = "bundle", - HandleResponseFiles = true - }; + var app = new CommandLineApplication { Name = "efbundle" }; + Configure(app); try @@ -73,6 +70,7 @@ public static int Execute(string? context, Assembly assembly, Assembly startupAs internal static void Configure(CommandLineApplication app) { app.FullName = DesignStrings.BundleFullName; + app.AllowArgumentSeparator = true; _migration = app.Argument("<MIGRATION>", DesignStrings.MigrationDescription); _connection = app.Option("--connection <CONNECTION>", DesignStrings.ConnectionDescription); @@ -83,6 +81,8 @@ internal static void Configure(CommandLineApplication app) var noColor = app.Option("--no-color", DesignStrings.NoColorDescription); var prefixOutput = app.Option("--prefix-output", DesignStrings.PrefixDescription); + app.HandleResponseFiles = true; + app.OnExecute( args => {
diff --git a/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs b/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs index cf4a7e5fa74..ade059f6ef5 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs @@ -44,9 +44,27 @@ public void Long_names_are_unique() } } + [Fact] + public void HandleResponseFiles_is_true() + { + var app = new CommandLineApplication { Name = "efbundle" }; + MigrationsBundle.Configure(app); + + Assert.True(app.HandleResponseFiles); + } + + [Fact] + public void AllowArgumentSeparator_is_true() + { + var app = new CommandLineApplication { Name = "efbundle" }; + MigrationsBundle.Configure(app); + + Assert.True(app.AllowArgumentSeparator); + } + private static IEnumerable<CommandLineApplication> GetCommands() { - var app = new CommandLineApplication { Name = "bundle" }; + var app = new CommandLineApplication { Name = "efbundle" }; MigrationsBundle.Configure(app);
EF Core Migration Bundles: no way to passthrough custom args to generated efbundle I use IDesignTimeDbContextFactory and custom args in CreateDbContext(string[] args) Then it is possible to apply update like so `dotnet ef database update -- --environment TEST It is expected to do the same with bundles ` .\efbundle.exe -- --environment TEST
Note for triage: repros for me. ``` PS C:\local\code\AllTogetherNow\SixOh> dotnet ef database update -- --environment TEST Build started... Build succeeded. --environment TEST Applying migration '20211217110035_One'. Done. PS C:\local\code\AllTogetherNow\SixOh> dotnet ef migrations bundle Build started... Build succeeded. Building bundle... Done. Migrations Bundle: C:\local\code\AllTogetherNow\SixOh\efbundle.exe PS C:\local\code\AllTogetherNow\SixOh> .\efbundle.exe -- --environment TEST Specify --help for a list of available options and commands. Unrecognized option '--' PS C:\local\code\AllTogetherNow\SixOh> .\efbundle.exe --environment TEST Specify --help for a list of available options and commands. Unrecognized option '--environment' PS C:\local\code\AllTogetherNow\SixOh> ``` /cc @bricelam Doh, looks like I forgot to set `AllowArgumentSeparator` to true in [MigrationsBundle.Configure](https://github.com/dotnet/efcore/blob/b39ca7f24c96df9aec977a29f35b1c0c70b54f5f/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs#L65).
2022-01-06T18:40:04Z
0.2
['Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsBundleTest.HandleResponseFiles_is_true', 'Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsBundleTest.AllowArgumentSeparator_is_true']
['Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsBundleTest.Short_names_are_unique', 'Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsBundleTest.Long_names_are_unique']
serilog/serilog
serilog__serilog-2116
68881e15fde7f977ff472fff61f042ad47c5b098
diff --git a/src/Serilog/Log.cs b/src/Serilog/Log.cs index 3258d852a..a5b1d8d67 100644 --- a/src/Serilog/Log.cs +++ b/src/Serilog/Log.cs @@ -59,11 +59,18 @@ public static void CloseAndFlush() /// <summary> /// Resets <see cref="Logger"/> to the default and disposes the original if possible /// </summary> - public static ValueTask CloseAndFlushAsync() + public static async ValueTask CloseAndFlushAsync() { var logger = Interlocked.Exchange(ref _logger, Serilog.Core.Logger.None); - return (logger as IAsyncDisposable)?.DisposeAsync() ?? default; + if (logger is IAsyncDisposable asyncDisposable) + { + await asyncDisposable.DisposeAsync(); + } + else + { + (logger as IDisposable)?.Dispose(); + } } #endif
diff --git a/test/Serilog.Tests/Core/BatchingSinkTests.cs b/test/Serilog.Tests/Core/BatchingSinkTests.cs index 2f3efe7d6..7022cae1b 100644 --- a/test/Serilog.Tests/Core/BatchingSinkTests.cs +++ b/test/Serilog.Tests/Core/BatchingSinkTests.cs @@ -15,9 +15,9 @@ public void WhenAnEventIsEnqueuedItIsWrittenToABatchOnDispose() var evt = Some.InformationEvent(); pbs.Emit(evt); pbs.Dispose(); - Assert.Single(bs.Batches); - Assert.Single(bs.Batches[0]); - Assert.Same(evt, bs.Batches[0][0]); + var batch = Assert.Single(bs.Batches); + var actual = Assert.Single(batch); + Assert.Same(evt, actual); Assert.True(bs.IsDisposed); Assert.False(bs.WasCalledAfterDisposal); } @@ -35,9 +35,9 @@ public async Task WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeAsync() var evt = Some.InformationEvent(); pbs.Emit(evt); await pbs.DisposeAsync(); - Assert.Single(bs.Batches); - Assert.Single(bs.Batches[0]); - Assert.Same(evt, bs.Batches[0][0]); + var batch = Assert.Single(bs.Batches); + var actual = Assert.Single(batch); + Assert.Same(evt, actual); Assert.True(bs.IsDisposed); Assert.True(bs.IsDisposedAsync); Assert.False(bs.WasCalledAfterDisposal); diff --git a/test/Serilog.Tests/LogTests.cs b/test/Serilog.Tests/LogTests.cs index cbd9ceccb..dd9a51a39 100644 --- a/test/Serilog.Tests/LogTests.cs +++ b/test/Serilog.Tests/LogTests.cs @@ -39,6 +39,16 @@ public async Task CloseAndFlushAsyncDisposesTheLogger() Assert.True(disposableLogger.IsDisposedAsync); } + [Fact] + public async Task CloseAndFlushAsyncDisposesTheLoggerEvenWhenItIsNotAsyncDisposable() + { + var disposableLogger = new SyncDisposableLogger(); + Assert.IsNotAssignableFrom<IAsyncDisposable>(disposableLogger); + Log.Logger = disposableLogger; + await Log.CloseAndFlushAsync(); + Assert.True(disposableLogger.IsDisposed); + } + [Fact] public async Task CloseAndFlushAsyncResetsLoggerToSilentLogger() { diff --git a/test/Serilog.Tests/Support/DisposableLogger.cs b/test/Serilog.Tests/Support/DisposableLogger.cs index 4c23b482b..7c85cc6f0 100644 --- a/test/Serilog.Tests/Support/DisposableLogger.cs +++ b/test/Serilog.Tests/Support/DisposableLogger.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Serilog.Tests.Support; public class DisposableLogger : ILogger, IDisposable diff --git a/test/Serilog.Tests/Support/InMemoryBatchedSink.cs b/test/Serilog.Tests/Support/InMemoryBatchedSink.cs index 0ae904f50..15b687150 100644 --- a/test/Serilog.Tests/Support/InMemoryBatchedSink.cs +++ b/test/Serilog.Tests/Support/InMemoryBatchedSink.cs @@ -6,18 +6,58 @@ sealed class InMemoryBatchedSink(TimeSpan batchEmitDelay) : IBatchedLogEventSink #endif { readonly object _stateLock = new(); - bool _stopped; + readonly SyncState _syncState = new(); - // Postmortem only - public bool WasCalledAfterDisposal { get; private set; } - public IList<IList<LogEvent>> Batches { get; } = new List<IList<LogEvent>>(); - public bool IsDisposed { get; private set; } + sealed class SyncState + { + public bool Stopped { get; set; } + public bool WasCalledAfterDisposal { get; set; } + public List<IReadOnlyCollection<LogEvent>> Batches { get; } = new(); + public bool IsDisposed { get; set; } + public bool IsDisposedAsync { get; set; } + } + + public bool WasCalledAfterDisposal + { + get + { + lock (_stateLock) + return _syncState.WasCalledAfterDisposal; + } + } + + public IReadOnlyList<IReadOnlyCollection<LogEvent>> Batches + { + get + { + lock (_stateLock) + return _syncState.Batches.ToList(); + } + } + + public bool IsDisposed + { + get + { + lock (_stateLock) + return _syncState.IsDisposed; + } + } + + public bool IsDisposedAsync + { + get + { + lock (_stateLock) + return _syncState.IsDisposedAsync; + } + } public void Stop() { lock (_stateLock) { - _stopped = true; + _syncState.Stopped = true; } } @@ -25,14 +65,14 @@ public Task EmitBatchAsync(IReadOnlyCollection<LogEvent> events) { lock (_stateLock) { - if (_stopped) + if (_syncState.Stopped) return Task.CompletedTask; if (IsDisposed) - WasCalledAfterDisposal = true; + _syncState.WasCalledAfterDisposal = true; Thread.Sleep(batchEmitDelay); - Batches.Add(events.ToList()); + _syncState.Batches.Add(events.ToList()); } return Task.CompletedTask; @@ -43,17 +83,15 @@ public Task EmitBatchAsync(IReadOnlyCollection<LogEvent> events) public void Dispose() { lock (_stateLock) - IsDisposed = true; + _syncState.IsDisposed = true; } #if FEATURE_ASYNCDISPOSABLE - public bool IsDisposedAsync { get; private set; } - public ValueTask DisposeAsync() { lock (_stateLock) { - IsDisposedAsync = true; + _syncState.IsDisposedAsync = true; Dispose(); return default; } diff --git a/test/Serilog.Tests/Support/SyncDisposableLogger.cs b/test/Serilog.Tests/Support/SyncDisposableLogger.cs new file mode 100644 index 000000000..8a6d88ed7 --- /dev/null +++ b/test/Serilog.Tests/Support/SyncDisposableLogger.cs @@ -0,0 +1,19 @@ +#if FEATURE_ASYNCDISPOSABLE && FEATURE_DEFAULT_INTERFACE + +namespace Serilog.Tests.Support; + +public class SyncDisposableLogger: ILogger, IDisposable +{ + public bool IsDisposed { get; private set; } + + public void Write(LogEvent logEvent) + { + } + + public void Dispose() + { + IsDisposed = true; + } +} + +#endif
CloseAndFlushAsync doesn't work with ReloadableLogger **Description** Calling Log.CloseAndFlushAsync() when using ReloadableLogger as a static logger silently fails and does nothing. **Reproduction** 1. Set the static logger to a ReloadableLogger. 2. Call Log.CloseAndFlushAsync(). **Expected behavior** The ReloadableLogger should either: * Support DisposeAsync() and properly flush the sinks * Fall back to Dispose() if DisposeAsync() is not available, * Throw an exception indicating the failure to close and flush. **Relevant package, tooling and runtime versions** Serilog 4.0.1
That's an awful bug, thanks for the report, will PR a patch now.
2024-09-26T06:49:02Z
0.1
['Serilog.Tests.LogTests.CloseAndFlushAsyncDisposesTheLoggerEvenWhenItIsNotAsyncDisposable']
['Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnDispose', 'Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeAsync', 'Serilog.Tests.LogTests.CloseAndFlushAsyncDisposesTheLogger']
serilog/serilog
serilog__serilog-2103
3f6d855a9a3b3cfab8f756b739d8120f9f398e04
diff --git a/src/Serilog/Capturing/PropertyValueConverter.cs b/src/Serilog/Capturing/PropertyValueConverter.cs index f113680b6..642fa736b 100644 --- a/src/Serilog/Capturing/PropertyValueConverter.cs +++ b/src/Serilog/Capturing/PropertyValueConverter.cs @@ -397,7 +397,7 @@ internal StructureValue CreateStructureValue(object value, [DynamicallyAccessedM for (var i = 0; i < properties.Length; ++i) { var property = properties[i]; - if (!property.CanRead) + if (property.GetMethod == null || !property.GetMethod.IsPublic) { continue; }
diff --git a/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs b/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs index b0c73ac62..b863df7a9 100644 --- a/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs +++ b/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs @@ -488,4 +488,18 @@ public class SubclassWithOverride : BaseClass { public override string Name => "override"; } + + [Fact] + public void PrivateGettersAreIgnoredWhenCapturing() + { + var structure = _converter.CreateStructureValue(new HasPropertyWithPrivateGetter(), typeof(HasPropertyWithPrivateGetter), false); + Assert.Contains(structure.Properties, p => p.Name == "A"); + Assert.DoesNotContain(structure.Properties, p => p.Name == "B"); + } + + public class HasPropertyWithPrivateGetter + { + public string A { get; set; } = "A"; + public string B { private get; set; } = "B"; + } }
Destructuring behaviour of objects with private getter has changed **Description** With the latest version of Serilog it appears that the behaviour of what properties are logged has changed from an earlier version (2.12) Here's the old output: `2024-08-20 09:12:09 [Information] Testing of destructing! OuterObjectToLog { Name: "Test", Description: "My Description" }` Here's the new output with the same object structure. `[09:09:52 INF] Testing of destructing! {"Name": "Test", "Description": "My Description", "InnerObject": {"InnerObjectName": "InnerObject", "InnerObjectDescription": "My Inner Object Description", "$type": "InnerObjectNotToLog"}, "$type": "OuterObjectToLog"}` **Reproduction** ``` using Serilog; namespace SerilogTest { internal class Program { static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); OuterObjectToLog outerObjectToLog = new OuterObjectToLog("Test", "My Description", new InnerObjectNotToLog("InnerObject", "My Inner Object Description")); Log.Information("Testing of destructing! {@OuterObject}", outerObjectToLog); // Finally, once just before the application exits... Log.CloseAndFlush(); } } public class OuterObjectToLog (string name, string description, InnerObjectNotToLog innerObject) { public string Name { get; set; } = name; public string Description { get; set; } = description; **public InnerObjectNotToLog InnerObject { private get; set; } = innerObject;** // note the private getter and likely unexpected } public class InnerObjectNotToLog(string name, string description) { public string InnerObjectName { get; set; } = name; public string InnerObjectDescription { get; set; } = description; } } ``` **Expected behavior** Expecting that the property InnerObject is not included in the serilog output. **Relevant package, tooling and runtime versions** Version 4.0.1, .NET 8 on Windows 11. Likely related to changes made in this commit? https://github.com/serilog/serilog/commit/580c55fd01bd0dc2c4ace63f1308e4c74fd3d95c
null
2024-08-21T00:19:19Z
0.1
['Serilog.Tests.Capturing.PropertyValueConverterTests.PrivateGettersAreIgnoredWhenCapturing']
[]
serilog/serilog
serilog__serilog-2083
fdf4a4872b4effd02dcd7d788e45b6b8ffdfa2fc
diff --git a/src/Serilog/Serilog.csproj b/src/Serilog/Serilog.csproj index cafe30469..8a5a3d4f8 100644 --- a/src/Serilog/Serilog.csproj +++ b/src/Serilog/Serilog.csproj @@ -2,6 +2,7 @@ <PropertyGroup> <Description>Simple .NET logging with fully-structured events</Description> <VersionPrefix>4.0.1</VersionPrefix> + <AssemblyVersion>$(VersionPrefix.Substring(0, 3)).0.0</AssemblyVersion> <Authors>Serilog Contributors</Authors> <!-- .NET Framework version targeting is frozen at these two TFMs. --> <TargetFrameworks Condition=" '$(OS)' == 'Windows_NT'">net471;net462</TargetFrameworks>
diff --git a/test/Serilog.Tests/MethodOverloadConventionTests.cs b/test/Serilog.Tests/MethodOverloadConventionTests.cs index a2fedb014..9e2d1750b 100644 --- a/test/Serilog.Tests/MethodOverloadConventionTests.cs +++ b/test/Serilog.Tests/MethodOverloadConventionTests.cs @@ -35,7 +35,7 @@ public class MethodOverloadConventionTests /// </para> /// /// <para> - /// A similar <see cref="ReadOnlySpan{T}"/> accepting method does not exists in the <see cref="ILogger"/> interface, + /// A similar <see cref="ReadOnlySpan{T}"/> accepting method does not exist in the <see cref="ILogger"/> interface, /// and introducing it is a breaking change. /// </para> /// </remarks> diff --git a/test/Serilog.Tests/VersioningTests.cs b/test/Serilog.Tests/VersioningTests.cs new file mode 100644 index 000000000..fe5c88e5e --- /dev/null +++ b/test/Serilog.Tests/VersioningTests.cs @@ -0,0 +1,20 @@ +namespace Serilog.Tests; + +public class VersioningTests +{ + [Fact] + public void AssemblyIsExplicitlyVersioned() + { + var version = typeof(Log).Assembly.GetName().Version; + Assert.NotNull(version); + Assert.False(version.Major is 0 or 1); + } + + [Fact] + public void AssemblySubordinateVersionPartsAreZero() + { + var version = typeof(Log).Assembly.GetName().Version; + Assert.True(version?.Build is 0); + Assert.True(version.Revision is 0); + } +} \ No newline at end of file
Consider using `Major.0.0.0` or `Major.Minor.0.0` assembly versioning Since Serilog 4.0.0 uses an assembly version 4.0.0.0, we've still got some wiggle-room to tweak the assembly versioning policy. Because new features _do_ cause issues when assembly versions are mismatched, `Major.Minor.0.0` is the most general versioning scheme that is likely to work for us. See also #2073 and https://learn.microsoft.com/en-us/dotnet/standard/library-guidance/versioning.
null
2024-07-10T04:00:37Z
0.1
['Serilog.Tests.VersioningTests.AssemblySubordinateVersionPartsAreZero']
['Serilog.Tests.MethodOverloadConventionTests.ValidateIsEnabledMethods', 'Serilog.Tests.MethodOverloadConventionTests.ILoggerValidateConventions', 'Serilog.Tests.MethodOverloadConventionTests.ValidateWriteEventLogMethods', 'Serilog.Tests.MethodOverloadConventionTests.ValidateBindPropertyMethods', 'Serilog.Tests.MethodOverloadConventionTests.ILoggerDefaultMethodsShouldBeInSyncWithLogger', 'Serilog.Tests.MethodOverloadConventionTests.ValidateForContextMethods', 'Serilog.Tests.MethodOverloadConventionTests.LogValidateConventions', 'Serilog.Tests.MethodOverloadConventionTests.LoggerValidateConventions', 'Serilog.Tests.MethodOverloadConventionTests.ValidateBindMessageTemplateMethods', 'Serilog.Tests.MethodOverloadConventionTests.SilentLoggerValidateConventions']
serilog/serilog
serilog__serilog-2055
a7eb5a75640319a0791d2e3afc3497fbe7edcf7a
diff --git a/Serilog.sln.DotSettings b/Serilog.sln.DotSettings index b9aebc18f..26729a031 100644 --- a/Serilog.sln.DotSettings +++ b/Serilog.sln.DotSettings @@ -171,6 +171,21 @@ <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=StaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypeParameters/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=15b5b1f1_002D457c_002D4ca6_002Db278_002D5615aedc07d3/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=236f7aa5_002D7b06_002D43ca_002Dbf2a_002D9b31bfcff09a/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="CONSTANT_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=2c62818f_002D621b_002D4425_002Dadc9_002D78611099bfcb/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Type parameters"&gt;&lt;ElementKinds&gt;&lt;Kind Name="TYPE_PARAMETER" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=4a98fdf6_002D7d98_002D4f5a_002Dafeb_002Dea44ad98c70c/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=53eecf85_002Dd821_002D40e8_002Dac97_002Dfdb734542b84/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Instance" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Instance fields (not private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=61a991a4_002Dd0a3_002D4d19_002D90a5_002Df8f4d75c30c1/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Local variables"&gt;&lt;ElementKinds&gt;&lt;Kind Name="LOCAL_VARIABLE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=669e5282_002Dfb4b_002D4e90_002D91e7_002D07d269d04b60/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="CONSTANT_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=70345118_002D4b40_002D4ece_002D937c_002Dbbeb7a0b2e70/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static fields (not private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=8a85b61a_002D1024_002D4f87_002Db9ef_002D1fdae19930a1/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"&gt;&lt;ElementKinds&gt;&lt;Kind Name="PARAMETER" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=8b8504e3_002Df0be_002D4c14_002D9103_002Dc732f2bddc15/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"&gt;&lt;ElementKinds&gt;&lt;Kind Name="ENUM_MEMBER" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a0b4bc4d_002Dd13b_002D4a37_002Db37e_002Dc9c6864e4302/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="NAMESPACE" /&gt;&lt;Kind Name="CLASS" /&gt;&lt;Kind Name="STRUCT" /&gt;&lt;Kind Name="ENUM" /&gt;&lt;Kind Name="DELEGATE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a4f433b8_002Dabcd_002D4e55_002Da08f_002D82e78cef0f0c/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Local constants"&gt;&lt;ElementKinds&gt;&lt;Kind Name="LOCAL_CONSTANT" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a7a3339e_002D4e89_002D4319_002D9735_002Da9dc4cb74cc7/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Interfaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="INTERFACE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=c873eafb_002Dd57f_002D481d_002D8c93_002D77f6863c2f88/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String> + <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=f9fce829_002De6f4_002D4cb2_002D80f1_002D5497c44f51df/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FCONSTRUCTOR/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FFUNCTION/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FGLOBAL_005FVARIABLE/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String> @@ -207,6 +222,7 @@ <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsCodeFormatterSettingsUpgrader/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsParsFormattingSettingsUpgrader/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsWrapperSettingsUpgrader/@EntryIndexedValue">True</s:Boolean> diff --git a/src/Serilog/Configuration/BatchingOptions.cs b/src/Serilog/Configuration/BatchingOptions.cs new file mode 100644 index 000000000..fe7ac7cf2 --- /dev/null +++ b/src/Serilog/Configuration/BatchingOptions.cs @@ -0,0 +1,46 @@ +// Copyright © Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Serilog.Core.Sinks.Batching; + +/// <summary> +/// Initialization options for <see cref="BatchingSink"/>. +/// </summary> +public class BatchingOptions +{ + /// <summary> + /// Eagerly emit a batch containing the first received event, regardless of + /// the target batch size or batching time. This helps with perceived "liveness" + /// when running/debugging applications interactively. The default is <c>true</c>. + /// </summary> + public bool EagerlyEmitFirstEvent { get; set; } = true; + + /// <summary> + /// The maximum number of events to include in a single batch. The default is <c>1000</c>. + /// </summary> + public int BatchSizeLimit { get; set; } = 1000; + + /// <summary> + /// The maximum delay between event batches. The default is two seconds. If a batch can be filled + /// before the buffering time limit is reached, it will be emitted without waiting. + /// </summary> + public TimeSpan BufferingTimeLimit { get; set; } = TimeSpan.FromSeconds(2); + + /// <summary> + /// Maximum number of events to hold in the sink's internal queue, or <c>null</c> + /// for an unbounded queue. The default is <c>100000</c>. When the limit is exceeded, + /// backpressure is applied. + /// </summary> + public int? QueueLimit { get; set; } = 100000; +} diff --git a/src/Serilog/Configuration/LoggerSinkConfiguration.cs b/src/Serilog/Configuration/LoggerSinkConfiguration.cs index 8f869972f..28feb9ebf 100644 --- a/src/Serilog/Configuration/LoggerSinkConfiguration.cs +++ b/src/Serilog/Configuration/LoggerSinkConfiguration.cs @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// ReSharper disable MergeCastWithTypeCheck + +using Serilog.Core.Sinks.Batching; + namespace Serilog.Configuration; /// <summary> @@ -29,7 +33,7 @@ internal LoggerSinkConfiguration(LoggerConfiguration loggerConfiguration, Action } /// <summary> - /// Write log events to the specified <see cref="ILogEventSink"/>. + /// Write log events to an <see cref="ILogEventSink"/>. /// </summary> /// <param name="logEventSink">The sink.</param> /// <param name="restrictedToMinimumLevel">The minimum level for @@ -46,7 +50,7 @@ public LoggerConfiguration Sink( } /// <summary> - /// Write log events to the specified <see cref="ILogEventSink"/>. + /// Write log events to an <see cref="ILogEventSink"/>. /// </summary> /// <param name="logEventSink">The sink.</param> /// <param name="restrictedToMinimumLevel">The minimum level for @@ -62,6 +66,8 @@ public LoggerConfiguration Sink( // ReSharper disable once MethodOverloadWithOptionalParameter LoggingLevelSwitch? levelSwitch = null) { + Guard.AgainstNull(logEventSink); + var sink = logEventSink; if (levelSwitch != null) { @@ -96,6 +102,50 @@ public LoggerConfiguration Sink<TSink>( return Sink(new TSink(), restrictedToMinimumLevel, levelSwitch); } + /// <summary> + /// Write log events to an <see cref="IBatchedLogEventSink"/>. Events will be internally buffered, and + /// written to the sink in batches. + /// </summary> + /// <param name="batchedLogEventSink">The batched sink to receive events.</param> + /// <param name="batchingOptions">Options that control batch sizes, buffering time, and backpressure.</param> + /// <param name="restrictedToMinimumLevel">The minimum level for + /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param> + /// <param name="levelSwitch">A switch allowing the pass-through minimum level + /// to be changed at runtime.</param> + /// <returns>Configuration object allowing method chaining.</returns> + public LoggerConfiguration Sink( + IBatchedLogEventSink batchedLogEventSink, + BatchingOptions batchingOptions, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, + LoggingLevelSwitch? levelSwitch = null) + { + Guard.AgainstNull(batchedLogEventSink); + Guard.AgainstNull(batchingOptions); + + return Sink(new BatchingSink(batchedLogEventSink, batchingOptions), restrictedToMinimumLevel, levelSwitch); + } + + /// <summary> + /// Write log events to an <see cref="IBatchedLogEventSink"/>. Events will be internally buffered, and + /// written to the sink in batches. + /// </summary> + /// <typeparam name="TSink">The type of a batched sink to receive events. The sink must provide a public, + /// parameterless constructor.</param> + /// <param name="batchingOptions">Options that control batch sizes, buffering time, and backpressure.</param> + /// <param name="restrictedToMinimumLevel">The minimum level for + /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param> + /// <param name="levelSwitch">A switch allowing the pass-through minimum level + /// to be changed at runtime.</param> + /// <returns>Configuration object allowing method chaining.</returns> + public LoggerConfiguration Sink<TSink>( + BatchingOptions batchingOptions, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, + LoggingLevelSwitch? levelSwitch = null) + where TSink : IBatchedLogEventSink, new() + { + return Sink(new TSink(), batchingOptions, restrictedToMinimumLevel, levelSwitch); + } + /// <summary> /// Write log events to a sub-logger, where further processing may occur. Events through /// the sub-logger will be constrained by filters and enriched by enrichers that are @@ -197,7 +247,7 @@ public LoggerConfiguration Conditional(Func<LogEvent, bool> condition, Action<Lo // Level aliases and so on don't need to be accepted here; if the user wants both a condition and leveling, they // can specify `restrictedToMinimumLevel` etc in the wrapped sink configuration. - return Wrap(this, s => new ConditionalSink(s, condition), configureSink, LevelAlias.Minimum, null); + return Wrap(this, s => new ConditionalSink(s, condition), configureSink); } /// <summary> @@ -251,7 +301,7 @@ public static LoggerConfiguration Wrap( #if FEATURE_ASYNCDISPOSABLE or IAsyncDisposable #endif - ) + ) { wrapper = new DisposeDelegatingSink(wrapper, enclosed as IDisposable #if FEATURE_ASYNCDISPOSABLE diff --git a/src/Serilog/Core/IBatchedLogEventSink.cs b/src/Serilog/Core/IBatchedLogEventSink.cs new file mode 100644 index 000000000..5b548c1ed --- /dev/null +++ b/src/Serilog/Core/IBatchedLogEventSink.cs @@ -0,0 +1,46 @@ +// Copyright © Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Serilog.Core; + +/// <summary> +/// A destination that accepts events in batches. Many sinks gain a performance advantage by handling events in batches, +/// for example to combine multiple events into a single network request to a remote collector. Because the client +/// application cannot wait for every event to be flushed when batching is used, batched sinks normally work +/// asynchronously to conserve local resources while batches are sent. +/// </summary> +/// <seealso cref="ILogEventSink"/> +public interface IBatchedLogEventSink +{ + /// <summary> + /// Emit a batch of log events, asynchronously. + /// </summary> + /// <param name="batch">The batch of events to emit.</param> + /// <remarks>Implementers should allow exceptions to propagate when batches fail. The batching infrastructure + /// handles exception handling, diagnostics, and retries.</remarks> + Task EmitBatchAsync(IReadOnlyCollection<LogEvent> batch); + + /// <summary> + /// Allows sinks to perform periodic work without requiring additional threads + /// or timers (thus avoiding additional flush/shut-down complexity). + /// </summary> + Task OnEmptyBatchAsync() +#if FEATURE_DEFAULT_INTERFACE + { + return Task.CompletedTask; + } +#else + ; +#endif +} \ No newline at end of file diff --git a/src/Serilog/Core/ILogEventSink.cs b/src/Serilog/Core/ILogEventSink.cs index 85db94a1d..b2d34c948 100644 --- a/src/Serilog/Core/ILogEventSink.cs +++ b/src/Serilog/Core/ILogEventSink.cs @@ -1,4 +1,4 @@ -// Copyright 2013-2015 Serilog Contributors +// Copyright © Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,11 +17,15 @@ namespace Serilog.Core; /// <summary> /// A destination for log events. /// </summary> +/// <seealso cref="ILogEventSink"/> public interface ILogEventSink { /// <summary> /// Emit the provided log event to the sink. /// </summary> /// <param name="logEvent">The log event to write.</param> + /// <seealso cref="IBatchedLogEventSink"/> + /// <remarks>Implementers should allow exceptions to propagate when event emission fails. The logger will handle + /// exceptions and produce diagnostics appropriately. void Emit(LogEvent logEvent); } diff --git a/src/Serilog/Core/Logger.cs b/src/Serilog/Core/Logger.cs index 04214787f..ddb344bbc 100644 --- a/src/Serilog/Core/Logger.cs +++ b/src/Serilog/Core/Logger.cs @@ -213,7 +213,7 @@ public void Write<T>(LogEventLevel level, string messageTemplate, T propertyValu span[0] = propertyValue; Write(level, messageTemplate, span); #else - Write(level, messageTemplate, new object?[] { propertyValue }); + Write(level, messageTemplate, [propertyValue]); #endif } } @@ -238,7 +238,7 @@ public void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 proper span[1] = propertyValue1; Write(level, messageTemplate, span); #else - Write(level, messageTemplate, new object?[] { propertyValue0, propertyValue1 }); + Write(level, messageTemplate, [propertyValue0, propertyValue1]); #endif } } @@ -265,7 +265,7 @@ public void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 pr span[2] = propertyValue2; Write(level, messageTemplate, span); #else - Write(level, messageTemplate, new object?[] { propertyValue0, propertyValue1, propertyValue2 }); + Write(level, messageTemplate, [propertyValue0, propertyValue1, propertyValue2]); #endif } } @@ -339,7 +339,7 @@ public void Write<T>(LogEventLevel level, Exception? exception, string messageTe span[0] = propertyValue; Write(level, exception, messageTemplate, span); #else - Write(level, exception, messageTemplate, new object?[] { propertyValue }); + Write(level, exception, messageTemplate, [propertyValue]); #endif } } @@ -365,7 +365,7 @@ public void Write<T0, T1>(LogEventLevel level, Exception? exception, string mess span[1] = propertyValue1; Write(level, exception, messageTemplate, span); #else - Write(level, exception, messageTemplate, new object?[] { propertyValue0, propertyValue1 }); + Write(level, exception, messageTemplate, [propertyValue0, propertyValue1]); #endif } } @@ -393,7 +393,7 @@ public void Write<T0, T1, T2>(LogEventLevel level, Exception? exception, string span[2] = propertyValue2; Write(level, exception, messageTemplate, span); #else - Write(level, exception, messageTemplate, new object?[] { propertyValue0, propertyValue1, propertyValue2 }); + Write(level, exception, messageTemplate, [propertyValue0, propertyValue1, propertyValue2]); #endif } } @@ -414,7 +414,7 @@ public void Write(LogEventLevel level, Exception? exception, string messageTempl // Catch a common pitfall when a single non-object array is cast to object[] if (propertyValues != null && propertyValues.GetType() != typeof(object[])) - propertyValues = new object[] { propertyValues }; + propertyValues = [propertyValues]; var logTimestamp = DateTimeOffset.Now; #if FEATURE_SPAN diff --git a/src/Serilog/Core/Sinks/AggregateSink.cs b/src/Serilog/Core/Sinks/AggregateSink.cs index c314391b6..ea419241c 100644 --- a/src/Serilog/Core/Sinks/AggregateSink.cs +++ b/src/Serilog/Core/Sinks/AggregateSink.cs @@ -37,7 +37,7 @@ public void Emit(LogEvent logEvent) catch (Exception ex) { SelfLog.WriteLine("Caught exception while emitting to sink {0}: {1}", sink, ex); - exceptions ??= new(); + exceptions ??= []; exceptions.Add(ex); } } diff --git a/src/Serilog/Core/Sinks/Batching/BatchingSink.cs b/src/Serilog/Core/Sinks/Batching/BatchingSink.cs new file mode 100644 index 000000000..2a15f1448 --- /dev/null +++ b/src/Serilog/Core/Sinks/Batching/BatchingSink.cs @@ -0,0 +1,296 @@ +// Copyright © Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System.Threading.Channels; + +// ReSharper disable UnusedParameter.Global, ConvertIfStatementToConditionalTernaryExpression, MemberCanBePrivate.Global, UnusedMember.Global, VirtualMemberNeverOverridden.Global, ClassWithVirtualMembersNeverInherited.Global, SuspiciousTypeConversion.Global + +namespace Serilog.Core.Sinks.Batching; + +/// <summary> +/// Buffers log events into batches for background flushing. +/// </summary> +sealed class BatchingSink : ILogEventSink, IDisposable +#if FEATURE_ASYNCDISPOSABLE + , IAsyncDisposable +#endif +{ + // Buffers events from the write- to the read side. + readonly Channel<LogEvent> _queue; + + // These fields are used by the write side to signal shutdown. + // A mutex is required because the queue writer `Complete()` call is not idempotent and will throw if + // called multiple times, e.g. via multiple `Dispose()` calls on this sink. + readonly object _stateLock = new(); + // Needed because the read loop needs to observe shutdown even when the target batched (remote) sink is + // unable to accept events (preventing the queue from being drained and completion being observed). + readonly CancellationTokenSource _shutdownSignal = new(); + // The write side can wait on this to ensure shutdown has completed. + readonly Task _runLoop; + + // Used only by the read side. + readonly IBatchedLogEventSink _targetSink; + readonly int _batchSizeLimit; + readonly bool _eagerlyEmitFirstEvent; + readonly FailureAwareBatchScheduler _batchScheduler; + readonly Queue<LogEvent> _currentBatch = new(); + readonly Task _waitForShutdownSignal; + Task<bool>? _cachedWaitToRead; + + /// <summary> + /// Construct a <see cref="BatchingSink"/>. + /// </summary> + /// <param name="batchedSink">A <see cref="IBatchedLogEventSink"/> to send log event batches to. Batches and empty + /// batch notifications will not be sent concurrently. When the <see cref="BatchingSink"/> is disposed, + /// it will dispose this object if possible.</param> + /// <param name="options">Options controlling behavior of the sink.</param> + public BatchingSink(IBatchedLogEventSink batchedSink, BatchingOptions options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + if (options.BatchSizeLimit <= 0) + throw new ArgumentOutOfRangeException(nameof(options), "The batch size limit must be greater than zero."); + if (options.BufferingTimeLimit <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), "The period must be greater than zero."); + + _targetSink = batchedSink ?? throw new ArgumentNullException(nameof(batchedSink)); + _batchSizeLimit = options.BatchSizeLimit; + _queue = options.QueueLimit is { } limit + ? Channel.CreateBounded<LogEvent>(new BoundedChannelOptions(limit) { SingleReader = true }) + : Channel.CreateUnbounded<LogEvent>(new UnboundedChannelOptions { SingleReader = true }); + _batchScheduler = new FailureAwareBatchScheduler(options.BufferingTimeLimit); + _eagerlyEmitFirstEvent = options.EagerlyEmitFirstEvent; + _waitForShutdownSignal = Task.Delay(Timeout.InfiniteTimeSpan, _shutdownSignal.Token) + .ContinueWith(e => e.Exception, TaskContinuationOptions.OnlyOnFaulted); + + // The conditional here is no longer required in .NET 8+ (dotnet/runtime#82912) + using (ExecutionContext.IsFlowSuppressed() ? (IDisposable?)null : ExecutionContext.SuppressFlow()) + { + _runLoop = Task.Run(LoopAsync); + } + } + + /// <summary> + /// Emit the provided log event to the sink. If the sink is being disposed or + /// the app domain unloaded, then the event is ignored. + /// </summary> + /// <param name="logEvent">Log event to emit.</param> + /// <exception cref="ArgumentNullException">The event is null.</exception> + /// <remarks> + /// The sink implements the contract that any events whose Emit() method has + /// completed at the time of sink disposal will be flushed (or attempted to, + /// depending on app domain state). + /// </remarks> + public void Emit(LogEvent logEvent) + { + if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); + + if (_shutdownSignal.IsCancellationRequested) + return; + + _queue.Writer.TryWrite(logEvent); + } + + async Task LoopAsync() + { + var isEagerBatch = _eagerlyEmitFirstEvent; + do + { + // Code from here through to the `try` block is expected to be infallible. It's structured this way because + // any failure modes within it haven't been accounted for in the rest of the sink design, and would need + // consideration in order for the sink to function robustly (i.e. to avoid hot/infinite looping). + + var fillBatch = Task.Delay(_batchScheduler.NextInterval); + do + { + while (_currentBatch.Count < _batchSizeLimit && + !_shutdownSignal.IsCancellationRequested && + _queue.Reader.TryRead(out var next)) + { + _currentBatch.Enqueue(next); + } + } while ((_currentBatch.Count < _batchSizeLimit && !isEagerBatch || _currentBatch.Count == 0) && + !_shutdownSignal.IsCancellationRequested && + await TryWaitToReadAsync(_queue.Reader, fillBatch, _shutdownSignal.Token).ConfigureAwait(false)); + + try + { + if (_currentBatch.Count == 0) + { + await _targetSink.OnEmptyBatchAsync().ConfigureAwait(false); + } + else + { + isEagerBatch = false; + + await _targetSink.EmitBatchAsync(_currentBatch).ConfigureAwait(false); + + _currentBatch.Clear(); + _batchScheduler.MarkSuccess(); + } + } + catch (Exception ex) + { + WriteToSelfLog("failed emitting a batch", ex); + _batchScheduler.MarkFailure(); + + if (_batchScheduler.ShouldDropBatch) + { + WriteToSelfLog("dropping the current batch"); + _currentBatch.Clear(); + } + + if (_batchScheduler.ShouldDropQueue) + { + WriteToSelfLog("dropping all queued events"); + + // Not ideal, uses some CPU capacity unnecessarily and doesn't complete in bounded time. The goal is + // to reduce memory pressure on the client if the server is offline for extended periods. May be + // worth reviewing and possibly abandoning this. + while (_queue.Reader.TryRead(out _) && !_shutdownSignal.IsCancellationRequested) { } + } + + // Wait out the remainder of the batch fill time so that we don't overwhelm the server. With each + // successive failure the interval will increase. Needs special handling so that we don't need to + // make `fillBatch` cancellable (and thus fallible). + await Task.WhenAny(fillBatch, _waitForShutdownSignal).ConfigureAwait(false); + } + } + while (!_shutdownSignal.IsCancellationRequested); + + // At this point: + // - The sink is being disposed + // - The queue has been completed + // - The queue may or may not be empty + // - The waiting batch may or may not be empty + // - The target sink may or may not be accepting events + + // Try flushing the rest of the queue, but bail out on any failure. Shutdown time is unbounded, but it + // doesn't make sense to pick an arbitrary limit - a future version might add a new option to control this. + try + { + while (_queue.Reader.TryPeek(out _)) + { + while (_currentBatch.Count < _batchSizeLimit && + _queue.Reader.TryRead(out var next)) + { + _currentBatch.Enqueue(next); + } + + if (_currentBatch.Count != 0) + { + await _targetSink.EmitBatchAsync(_currentBatch).ConfigureAwait(false); + _currentBatch.Clear(); + } + } + } + catch (Exception ex) + { + WriteToSelfLog("failed emitting a batch during shutdown; dropping remaining queued events", ex); + } + } + + // Wait until `reader` has items to read. Returns `false` if the `timeout` task completes, or if the reader is cancelled. + async Task<bool> TryWaitToReadAsync(ChannelReader<LogEvent> reader, Task timeout, CancellationToken cancellationToken) + { + var waitToRead = _cachedWaitToRead ?? reader.WaitToReadAsync(cancellationToken).AsTask(); + _cachedWaitToRead = null; + + var completed = await Task.WhenAny(timeout, waitToRead).ConfigureAwait(false); + + // Avoid unobserved task exceptions in the cancellation and failure cases. Note that we may not end up observing + // read task cancellation exceptions during shutdown, may be some room to improve. + if (completed is { Exception: not null, IsCanceled: false }) + { + WriteToSelfLog($"could not read from queue: {completed.Exception}"); + } + + if (completed == timeout) + { + // Dropping references to `waitToRead` will cause it and some supporting objects to leak; disposing it + // will break the channel and cause future attempts to read to fail. So, we cache and reuse it next time + // around the loop. + + _cachedWaitToRead = waitToRead; + return false; + } + + if (waitToRead.Status is not TaskStatus.RanToCompletion) + return false; + + return await waitToRead; + } + + /// <inheritdoc/> + public void Dispose() + { + SignalShutdown(); + + try + { + _runLoop.Wait(); + } + catch (Exception ex) + { + // E.g. the task was canceled before ever being run, or internally failed and threw + // an unexpected exception. + WriteToSelfLog("caught exception during disposal", ex); + } + + (_targetSink as IDisposable)?.Dispose(); + } + +#if FEATURE_ASYNCDISPOSABLE + /// <inheritdoc/> + public async ValueTask DisposeAsync() + { + SignalShutdown(); + + try + { + await _runLoop.ConfigureAwait(false); + } + catch (Exception ex) + { + // E.g. the task was canceled before ever being run, or internally failed and threw + // an unexpected exception. + WriteToSelfLog("caught exception during async disposal", ex); + } + + if (_targetSink is IAsyncDisposable asyncDisposable) + await asyncDisposable.DisposeAsync().ConfigureAwait(false); + else + (_targetSink as IDisposable)?.Dispose(); + } +#endif + + void SignalShutdown() + { + lock (_stateLock) + { + if (!_shutdownSignal.IsCancellationRequested) + { + // Relies on synchronization via `_stateLock`: once the writer is completed, subsequent attempts to + // complete it will throw. + _queue.Writer.Complete(); + _shutdownSignal.Cancel(); + } + } + } + + void WriteToSelfLog(string message, Exception? exception = null) + { + var ex = exception != null ? $"{Environment.NewLine}{exception}" : ""; + SelfLog.WriteLine($"BatchingSink ({_targetSink}): {message}{ex}"); + } +} diff --git a/src/Serilog/Core/Sinks/Batching/FailureAwareBatchScheduler.cs b/src/Serilog/Core/Sinks/Batching/FailureAwareBatchScheduler.cs new file mode 100644 index 000000000..ff9b934ec --- /dev/null +++ b/src/Serilog/Core/Sinks/Batching/FailureAwareBatchScheduler.cs @@ -0,0 +1,88 @@ +// Copyright © Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Serilog.Core.Sinks.Batching; + +/// <summary> +/// Manages reconnection period and transient fault response for <see cref="BatchingSink"/>. +/// During normal operation an object of this type will simply echo the configured batch transmission +/// period. When availability fluctuates, the class tracks the number of failed attempts, each time +/// increasing the interval before reconnection is attempted (up to a set maximum) and at predefined +/// points indicating that either the current batch, or entire waiting queue, should be dropped. This +/// Serves two purposes - first, a loaded receiver may need a temporary reduction in traffic while coming +/// back online. Second, the sender needs to account for both bad batches (the first fault response) and +/// also overproduction (the second, queue-dropping response). In combination these should provide a +/// reasonable delivery effort but ultimately protect the sender from memory exhaustion. +/// </summary> +class FailureAwareBatchScheduler +{ + static readonly TimeSpan MinimumBackoffPeriod = TimeSpan.FromSeconds(5); + static readonly TimeSpan MaximumBackoffInterval = TimeSpan.FromMinutes(10); + + const int FailuresBeforeDroppingBatch = 8; + const int FailuresBeforeDroppingQueue = 10; + + readonly TimeSpan _period; + + int _failuresSinceSuccessfulBatch; + + public FailureAwareBatchScheduler(TimeSpan period) + { + if (period < TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(period), "The batching period must be a positive timespan."); + + _period = period; + } + + public void MarkSuccess() + { + _failuresSinceSuccessfulBatch = 0; + } + + public void MarkFailure() + { + ++_failuresSinceSuccessfulBatch; + } + + public TimeSpan NextInterval + { + get + { + // Available, and first failure, just try the batch interval + if (_failuresSinceSuccessfulBatch <= 1) return _period; + + // Second failure, start ramping up the interval - first 2x, then 4x, ... + var backoffFactor = Math.Pow(2, _failuresSinceSuccessfulBatch - 1); + + // If the period is ridiculously short, give it a boost so we get some + // visible backoff. + var backoffPeriod = Math.Max(_period.Ticks, MinimumBackoffPeriod.Ticks); + + // The "ideal" interval + var backedOff = (long) (backoffPeriod * backoffFactor); + + // Capped to the maximum interval + var cappedBackoff = Math.Min(MaximumBackoffInterval.Ticks, backedOff); + + // Unless that's shorter than the period, in which case we'll just apply the period + var actual = Math.Max(_period.Ticks, cappedBackoff); + + return TimeSpan.FromTicks(actual); + } + } + + public bool ShouldDropBatch => _failuresSinceSuccessfulBatch >= FailuresBeforeDroppingBatch; + + public bool ShouldDropQueue => _failuresSinceSuccessfulBatch >= FailuresBeforeDroppingQueue; +} diff --git a/src/Serilog/Core/Sinks/DisposingAggregateSink.cs b/src/Serilog/Core/Sinks/DisposingAggregateSink.cs index 7336a58c7..5427baf23 100644 --- a/src/Serilog/Core/Sinks/DisposingAggregateSink.cs +++ b/src/Serilog/Core/Sinks/DisposingAggregateSink.cs @@ -39,7 +39,7 @@ public void Emit(LogEvent logEvent) catch (Exception ex) { SelfLog.WriteLine("Caught exception while emitting to sink {0}: {1}", sink, ex); - exceptions ??= new(); + exceptions ??= []; exceptions.Add(ex); } } diff --git a/src/Serilog/Formatting/Display/LevelOutputFormat.cs b/src/Serilog/Formatting/Display/LevelOutputFormat.cs index 2a9173b10..3776fb39d 100644 --- a/src/Serilog/Formatting/Display/LevelOutputFormat.cs +++ b/src/Serilog/Formatting/Display/LevelOutputFormat.cs @@ -22,32 +22,35 @@ namespace Serilog.Formatting.Display; /// </summary> static class LevelOutputFormat { - static readonly string[][] _titleCaseLevelMap = { - new []{ "V", "Vb", "Vrb", "Verb", "Verbo", "Verbos", "Verbose" }, - new []{ "D", "De", "Dbg", "Dbug", "Debug" }, - new []{ "I", "In", "Inf", "Info", "Infor", "Inform", "Informa", "Informat", "Informati", "Informatio", "Information" }, - new []{ "W", "Wn", "Wrn", "Warn", "Warni", "Warnin", "Warning" }, - new []{ "E", "Er", "Err", "Eror", "Error" }, - new []{ "F", "Fa", "Ftl", "Fatl", "Fatal" } - }; + static readonly string[][] _titleCaseLevelMap = + [ + ["V", "Vb", "Vrb", "Verb", "Verbo", "Verbos", "Verbose"], + ["D", "De", "Dbg", "Dbug", "Debug"], + ["I", "In", "Inf", "Info", "Infor", "Inform", "Informa", "Informat", "Informati", "Informatio", "Information"], + ["W", "Wn", "Wrn", "Warn", "Warni", "Warnin", "Warning"], + ["E", "Er", "Err", "Eror", "Error"], + ["F", "Fa", "Ftl", "Fatl", "Fatal"] + ]; - static readonly string[][] _lowerCaseLevelMap = { - new []{ "v", "vb", "vrb", "verb", "verbo", "verbos", "verbose" }, - new []{ "d", "de", "dbg", "dbug", "debug" }, - new []{ "i", "in", "inf", "info", "infor", "inform", "informa", "informat", "informati", "informatio", "information" }, - new []{ "w", "wn", "wrn", "warn", "warni", "warnin", "warning" }, - new []{ "e", "er", "err", "eror", "error" }, - new []{ "f", "fa", "ftl", "fatl", "fatal" } - }; + static readonly string[][] _lowerCaseLevelMap = + [ + ["v", "vb", "vrb", "verb", "verbo", "verbos", "verbose"], + ["d", "de", "dbg", "dbug", "debug"], + ["i", "in", "inf", "info", "infor", "inform", "informa", "informat", "informati", "informatio", "information"], + ["w", "wn", "wrn", "warn", "warni", "warnin", "warning"], + ["e", "er", "err", "eror", "error"], + ["f", "fa", "ftl", "fatl", "fatal"] + ]; - static readonly string[][] _upperCaseLevelMap = { - new []{ "V", "VB", "VRB", "VERB", "VERBO", "VERBOS", "VERBOSE" }, - new []{ "D", "DE", "DBG", "DBUG", "DEBUG" }, - new []{ "I", "IN", "INF", "INFO", "INFOR", "INFORM", "INFORMA", "INFORMAT", "INFORMATI", "INFORMATIO", "INFORMATION" }, - new []{ "W", "WN", "WRN", "WARN", "WARNI", "WARNIN", "WARNING" }, - new []{ "E", "ER", "ERR", "EROR", "ERROR" }, - new []{ "F", "FA", "FTL", "FATL", "FATAL" } - }; + static readonly string[][] _upperCaseLevelMap = + [ + ["V", "VB", "VRB", "VERB", "VERBO", "VERBOS", "VERBOSE"], + ["D", "DE", "DBG", "DBUG", "DEBUG"], + ["I", "IN", "INF", "INFO", "INFOR", "INFORM", "INFORMA", "INFORMAT", "INFORMATI", "INFORMATIO", "INFORMATION"], + ["W", "WN", "WRN", "WARN", "WARNI", "WARNIN", "WARNING"], + ["E", "ER", "ERR", "EROR", "ERROR"], + ["F", "FA", "FTL", "FATL", "FATAL"] + ]; public static string GetLevelMoniker(LogEventLevel value, string? format = null) { diff --git a/src/Serilog/ILogger.cs b/src/Serilog/ILogger.cs index 95ac8d67f..87733721a 100644 --- a/src/Serilog/ILogger.cs +++ b/src/Serilog/ILogger.cs @@ -12,7 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if FEATURE_DEFAULT_INTERFACE using System.Diagnostics; +#endif namespace Serilog; @@ -162,7 +164,7 @@ void Write<T>(LogEventLevel level, string messageTemplate, T propertyValue) // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, messageTemplate, new object?[] { propertyValue }); + Write(level, messageTemplate, [propertyValue]); } } #else @@ -183,7 +185,7 @@ void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 propertyValue // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, messageTemplate, new object?[] { propertyValue0, propertyValue1 }); + Write(level, messageTemplate, [propertyValue0, propertyValue1]); } } #else @@ -205,7 +207,7 @@ void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 propertyV // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, messageTemplate, new object?[] { propertyValue0, propertyValue1, propertyValue2 }); + Write(level, messageTemplate, [propertyValue0, propertyValue1, propertyValue2]); } } #else @@ -259,7 +261,7 @@ void Write<T>(LogEventLevel level, Exception? exception, string messageTemplate, // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, exception, messageTemplate, new object?[] { propertyValue }); + Write(level, exception, messageTemplate, [propertyValue]); } } #else @@ -281,7 +283,7 @@ void Write<T0, T1>(LogEventLevel level, Exception? exception, string messageTemp // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, exception, messageTemplate, new object?[] { propertyValue0, propertyValue1 }); + Write(level, exception, messageTemplate, [propertyValue0, propertyValue1]); } } #else @@ -304,7 +306,7 @@ void Write<T0, T1, T2>(LogEventLevel level, Exception? exception, string message // Avoid the array allocation and any boxing allocations when the level isn't enabled if (IsEnabled(level)) { - Write(level, exception, messageTemplate, new object?[] { propertyValue0, propertyValue1, propertyValue2 }); + Write(level, exception, messageTemplate, [propertyValue0, propertyValue1, propertyValue2]); } } #else @@ -331,7 +333,7 @@ void Write(LogEventLevel level, Exception? exception, string messageTemplate, pa // Catch a common pitfall when a single non-object array is cast to object[] if (propertyValues != null && propertyValues.GetType() != typeof(object[])) - propertyValues = new object[] { propertyValues }; + propertyValues = [propertyValues]; var logTimestamp = DateTimeOffset.Now; if (BindMessageTemplate(messageTemplate, propertyValues, out var parsedTemplate, out var boundProperties)) diff --git a/src/Serilog/LoggerConfiguration.cs b/src/Serilog/LoggerConfiguration.cs index d6e7f1d15..cef595654 100644 --- a/src/Serilog/LoggerConfiguration.cs +++ b/src/Serilog/LoggerConfiguration.cs @@ -19,13 +19,13 @@ namespace Serilog; /// </summary> public class LoggerConfiguration { - readonly List<ILogEventSink> _logEventSinks = new(); - readonly List<ILogEventSink> _auditSinks = new(); - readonly List<ILogEventEnricher> _enrichers = new(); - readonly List<ILogEventFilter> _filters = new(); - readonly List<Type> _additionalScalarTypes = new(); - readonly HashSet<Type> _additionalDictionaryTypes = new(); - readonly List<IDestructuringPolicy> _additionalDestructuringPolicies = new(); + readonly List<ILogEventSink> _logEventSinks = []; + readonly List<ILogEventSink> _auditSinks = []; + readonly List<ILogEventEnricher> _enrichers = []; + readonly List<ILogEventFilter> _filters = []; + readonly List<Type> _additionalScalarTypes = []; + readonly HashSet<Type> _additionalDictionaryTypes = []; + readonly List<IDestructuringPolicy> _additionalDestructuringPolicies = []; readonly Dictionary<string, LoggingLevelSwitch> _overrides = new(); LogEventLevel _minimumLevel = LogEventLevel.Information; LoggingLevelSwitch? _levelSwitch; diff --git a/src/Serilog/Policies/SimpleScalarConversionPolicy.cs b/src/Serilog/Policies/SimpleScalarConversionPolicy.cs index 6c030adc0..c802653f7 100644 --- a/src/Serilog/Policies/SimpleScalarConversionPolicy.cs +++ b/src/Serilog/Policies/SimpleScalarConversionPolicy.cs @@ -20,7 +20,7 @@ class SimpleScalarConversionPolicy : IScalarConversionPolicy public SimpleScalarConversionPolicy(IEnumerable<Type> scalarTypes) { - _scalarTypes = new(scalarTypes); + _scalarTypes = [..scalarTypes]; } public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result) diff --git a/src/Serilog/Serilog.csproj b/src/Serilog/Serilog.csproj index 690d922e7..39306d9b8 100644 --- a/src/Serilog/Serilog.csproj +++ b/src/Serilog/Serilog.csproj @@ -57,15 +57,18 @@ <ItemGroup Condition=" '$(TargetFramework)' == 'net462' "> <PackageReference Include="System.ValueTuple" Version="4.5.0" /> - <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" /> + <PackageReference Include="System.Threading.Channels" Version="8.0.0" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net471' "> - <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" /> + <PackageReference Include="System.Threading.Channels" Version="8.0.0" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> - <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" /> + <PackageReference Include="System.Threading.Channels" Version="8.0.0" /> </ItemGroup> </Project> diff --git a/src/Serilog/Settings/KeyValuePairs/KeyValuePairSettings.cs b/src/Serilog/Settings/KeyValuePairs/KeyValuePairSettings.cs index ccca2ea19..2c1bbd476 100644 --- a/src/Serilog/Settings/KeyValuePairs/KeyValuePairSettings.cs +++ b/src/Serilog/Settings/KeyValuePairs/KeyValuePairSettings.cs @@ -37,7 +37,7 @@ class KeyValuePairSettings : ILoggerSettings const string LevelSwitchNameRegex = @"^\$[A-Za-z]+[A-Za-z0-9]*$"; static readonly string[] _supportedDirectives = - { + [ UsingDirective, LevelSwitchDirective, AuditToDirective, @@ -48,7 +48,7 @@ class KeyValuePairSettings : ILoggerSettings EnrichWithDirective, FilterDirective, DestructureDirective - }; + ]; static readonly Dictionary<string, Type> CallableDirectiveReceiverTypes = new() {
diff --git a/test/Serilog.ApprovalTests/Serilog.approved.txt b/test/Serilog.ApprovalTests/Serilog.approved.txt index 71a596147..0613a5fa3 100644 --- a/test/Serilog.ApprovalTests/Serilog.approved.txt +++ b/test/Serilog.ApprovalTests/Serilog.approved.txt @@ -75,8 +75,11 @@ namespace Serilog.Configuration public Serilog.LoggerConfiguration Logger(Serilog.ILogger logger, bool attemptDispose = false, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } public Serilog.LoggerConfiguration Sink(Serilog.Core.ILogEventSink logEventSink, Serilog.Events.LogEventLevel restrictedToMinimumLevel) { } public Serilog.LoggerConfiguration Sink(Serilog.Core.ILogEventSink logEventSink, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } + public Serilog.LoggerConfiguration Sink(Serilog.Core.IBatchedLogEventSink batchedLogEventSink, Serilog.Core.Sinks.Batching.BatchingOptions batchingOptions, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } public Serilog.LoggerConfiguration Sink<TSink>(Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) where TSink : Serilog.Core.ILogEventSink, new () { } + public Serilog.LoggerConfiguration Sink<TSink>(Serilog.Core.Sinks.Batching.BatchingOptions batchingOptions, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) + where TSink : Serilog.Core.IBatchedLogEventSink, new () { } public static Serilog.LoggerConfiguration Wrap(Serilog.Configuration.LoggerSinkConfiguration loggerSinkConfiguration, System.Func<Serilog.Core.ILogEventSink, Serilog.Core.ILogEventSink> wrapSink, System.Action<Serilog.Configuration.LoggerSinkConfiguration> configureWrappedSink, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } } } @@ -98,6 +101,11 @@ namespace Serilog.Core { public const string SourceContextPropertyName = "SourceContext"; } + public interface IBatchedLogEventSink + { + System.Threading.Tasks.Task EmitBatchAsync(System.Collections.Generic.IReadOnlyCollection<Serilog.Events.LogEvent> batch); + System.Threading.Tasks.Task OnEmptyBatchAsync(); + } public interface IDestructuringPolicy { bool TryDestructure(object value, Serilog.Core.ILogEventPropertyValueFactory propertyValueFactory, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Serilog.Events.LogEventPropertyValue? result); @@ -305,6 +313,17 @@ namespace Serilog.Core.Enrichers public void Enrich(Serilog.Events.LogEvent logEvent, Serilog.Core.ILogEventPropertyFactory propertyFactory) { } } } +namespace Serilog.Core.Sinks.Batching +{ + public class BatchingOptions + { + public BatchingOptions() { } + public int BatchSizeLimit { get; set; } + public System.TimeSpan BufferingTimeLimit { get; set; } + public bool EagerlyEmitFirstEvent { get; set; } + public int? QueueLimit { get; set; } + } +} namespace Serilog.Data { public abstract class LogEventPropertyValueRewriter<TState> : Serilog.Data.LogEventPropertyValueVisitor<TState, Serilog.Events.LogEventPropertyValue> diff --git a/test/Serilog.PerformanceTests/BindingBenchmark.cs b/test/Serilog.PerformanceTests/BindingBenchmark.cs index a5d1844f0..84fce7a93 100644 --- a/test/Serilog.PerformanceTests/BindingBenchmark.cs +++ b/test/Serilog.PerformanceTests/BindingBenchmark.cs @@ -36,8 +36,8 @@ public void Setup() .CreateLogger(); _zero = Array.Empty<object>(); - _one = new object[] { 1 }; - _five = new object[] { 1, 2, 3, 4, 5 }; + _one = [1]; + _five = [1, 2, 3, 4, 5]; } // The benchmarks run p.Count() to force enumeration; this will be representative of how the API diff --git a/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs b/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs index ffdc8ad7b..d02d701cf 100644 --- a/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs +++ b/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs @@ -6,14 +6,14 @@ public class SourceContextMatchBenchmark { readonly LevelOverrideMap _levelOverrideMap; readonly Logger _loggerWithOverrides; - readonly List<ILogger> _loggersWithFilters = new(); + readonly List<ILogger> _loggersWithFilters = []; readonly LogEvent _event = Some.InformationEvent(); readonly string[] _contexts; public SourceContextMatchBenchmark() { - _contexts = new[] - { + _contexts = + [ "Serilog", "MyApp", "MyAppSomething", @@ -23,7 +23,7 @@ public SourceContextMatchBenchmark() "MyApp.Api.Controllers.AboutController", "MyApp.Api.Controllers.HomeController", "Api.Controllers.HomeController" - }; + ]; var overrides = new Dictionary<string, LoggingLevelSwitch> { diff --git a/test/Serilog.Tests/Core/BatchingSinkTests.cs b/test/Serilog.Tests/Core/BatchingSinkTests.cs new file mode 100644 index 000000000..5fd8f61ac --- /dev/null +++ b/test/Serilog.Tests/Core/BatchingSinkTests.cs @@ -0,0 +1,140 @@ +using Serilog.Core.Sinks.Batching; + +namespace Serilog.Core.Tests; + +public class BatchingSinkTests +{ + static readonly TimeSpan TinyWait = TimeSpan.FromMilliseconds(200); + static readonly TimeSpan MicroWait = TimeSpan.FromMilliseconds(1); + + [Fact] + public void WhenAnEventIsEnqueuedItIsWrittenToABatchOnDispose() + { + var bs = new InMemoryBatchedSink(TimeSpan.Zero); + var pbs = new BatchingSink(bs, new() { BatchSizeLimit = 2, BufferingTimeLimit = TinyWait, EagerlyEmitFirstEvent = true }); + var evt = Some.InformationEvent(); + pbs.Emit(evt); + pbs.Dispose(); + Assert.Single(bs.Batches); + Assert.Single(bs.Batches[0]); + Assert.Same(evt, bs.Batches[0][0]); + Assert.True(bs.IsDisposed); + Assert.False(bs.WasCalledAfterDisposal); + } + +#if FEATURE_ASYNCDISPOSABLE + [Fact] + public async Task WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeAsync() + { + var bs = new InMemoryBatchedSink(TimeSpan.Zero); + var pbs = new BatchingSink( + bs, new() + { + BatchSizeLimit = 2, BufferingTimeLimit = TinyWait, EagerlyEmitFirstEvent = true + }); + var evt = Some.InformationEvent(); + pbs.Emit(evt); + await pbs.DisposeAsync(); + Assert.Single(bs.Batches); + Assert.Single(bs.Batches[0]); + Assert.Same(evt, bs.Batches[0][0]); + Assert.True(bs.IsDisposed); + Assert.True(bs.IsDisposedAsync); + Assert.False(bs.WasCalledAfterDisposal); + } +#endif + + [Fact] + public void WhenAnEventIsEnqueuedItIsWrittenToABatchOnTimer() + { + var bs = new InMemoryBatchedSink(TimeSpan.Zero); + var pbs = new BatchingSink( + bs, + new() + { + BatchSizeLimit = 2, BufferingTimeLimit = TinyWait, EagerlyEmitFirstEvent = true + }); + var evt = Some.InformationEvent(); + pbs.Emit(evt); + Thread.Sleep(TinyWait + TinyWait); + bs.Stop(); + pbs.Dispose(); + Assert.Single(bs.Batches); + Assert.True(bs.IsDisposed); + Assert.False(bs.WasCalledAfterDisposal); + } + + [Fact] + public void WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeWhileRunning() + { + var bs = new InMemoryBatchedSink(TinyWait + TinyWait); + var pbs = new BatchingSink(bs, new() { BatchSizeLimit = 2, BufferingTimeLimit = MicroWait, EagerlyEmitFirstEvent = true }); + var evt = Some.InformationEvent(); + pbs.Emit(evt); + Thread.Sleep(TinyWait); + pbs.Dispose(); + Assert.Single(bs.Batches); + Assert.True(bs.IsDisposed); + Assert.False(bs.WasCalledAfterDisposal); + } + + [Fact] + public void ExecutionContextDoesNotFlowToBatchedSink() + { + var local = new AsyncLocal<int> + { + Value = 5 + }; + + var observed = 17; + var bs = new CallbackBatchedSink(_ => + { + observed = local.Value; + return Task.CompletedTask; + }); + + var pbs = new BatchingSink(bs, new()); + var evt = Some.InformationEvent(); + pbs.Emit(evt); + pbs.Dispose(); + + Assert.Equal(default, observed); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task EagerlyEmitFirstEventCausesQuickInitialBatch(bool eagerlyEmit) + { + var x = new ManualResetEvent(false); + var bs = new CallbackBatchedSink(_ => + { + x.Set(); + return Task.CompletedTask; + }); + + var options = new BatchingOptions + { + BufferingTimeLimit = TimeSpan.FromSeconds(3), + EagerlyEmitFirstEvent = eagerlyEmit, + BatchSizeLimit = 10, + QueueLimit = 1000 + }; + + var pbs = new BatchingSink(bs, options); + + var evt = Some.InformationEvent(); + pbs.Emit(evt); + + await Task.Delay(1900); + Assert.Equal(eagerlyEmit, x.WaitOne(0)); + +#if FEATURE_ASYNCDISPOSABLE + await pbs.DisposeAsync(); +#else + pbs.Dispose(); +#endif + + Assert.True(x.WaitOne(0)); + } +} diff --git a/test/Serilog.Tests/Core/ChildLoggerKnownLimitationsTests.cs b/test/Serilog.Tests/Core/ChildLoggerKnownLimitationsTests.cs index d1e6de96f..11e3b3f26 100644 --- a/test/Serilog.Tests/Core/ChildLoggerKnownLimitationsTests.cs +++ b/test/Serilog.Tests/Core/ChildLoggerKnownLimitationsTests.cs @@ -66,7 +66,7 @@ public void SpecifyingMinimumLevelOverridesInWriteToLoggerWritesWarningToSelfLog // static object?[] T(string? rs, int? rl, string cs, int? cl) { - return new object?[] { rs, rl, cs, cl }; + return [rs, rl, cs, cl]; } // numbers are relative to incoming event level // Information + 1 = Warning diff --git a/test/Serilog.Tests/Core/ChildLoggerTests.cs b/test/Serilog.Tests/Core/ChildLoggerTests.cs index 10dccf2db..0defe52c5 100644 --- a/test/Serilog.Tests/Core/ChildLoggerTests.cs +++ b/test/Serilog.Tests/Core/ChildLoggerTests.cs @@ -11,7 +11,7 @@ public class ChildLoggerTests // static object?[] T(LogEventLevel el, int? rl, int? rt, int? cl, bool r) { - return new object?[] { el, rl, rt, cl, r }; + return [el, rl, rt, cl, r]; } // numbers are relative to incoming event level // Information + 1 = Warning @@ -144,7 +144,7 @@ public void WriteToLoggerMinimumLevelInheritanceScenarios( // static object?[] T(string? rs, int? rl, string? cs, int? cl, bool r, LogEventLevel dl = LevelAlias.Minimum) { - return new object?[] { dl, rs, rl, cs, cl, r }; + return [dl, rs, rl, cs, cl, r]; } // numbers are relative to incoming event level // Information + 1 = Warning diff --git a/test/Serilog.Tests/Core/FailureAwareBatchSchedulerTests.cs b/test/Serilog.Tests/Core/FailureAwareBatchSchedulerTests.cs new file mode 100644 index 000000000..1f5dbe2ee --- /dev/null +++ b/test/Serilog.Tests/Core/FailureAwareBatchSchedulerTests.cs @@ -0,0 +1,104 @@ +using Serilog.Core.Sinks.Batching; + +namespace Serilog.Core.Tests; + +public class FailureAwareBatchSchedulerTests +{ + static TimeSpan Period => TimeSpan.FromSeconds(2); + FailureAwareBatchScheduler Scheduler { get; } = new(Period); + + [Fact] + public void WhenNoFailuresHaveOccurredTheInitialIntervalIsUsed() + { + Assert.Equal(Period, Scheduler.NextInterval); + } + + [Fact] + public void WhenOneFailureHasOccurredTheInitialIntervalIsUsed() + { + Scheduler.MarkFailure(); + Assert.Equal(Period, Scheduler.NextInterval); + } + + [Fact] + public void WhenTwoFailuresHaveOccurredTheIntervalBacksOff() + { + Scheduler.MarkFailure(); + Scheduler.MarkFailure(); + Assert.Equal(TimeSpan.FromSeconds(10), Scheduler.NextInterval); + } + + [Fact] + public void WhenABatchSucceedsTheStatusResets() + { + Scheduler.MarkFailure(); + Scheduler.MarkFailure(); + Scheduler.MarkSuccess(); + Assert.Equal(Period, Scheduler.NextInterval); + } + + [Fact] + public void WhenThreeFailuresHaveOccurredTheIntervalBacksOff() + { + Scheduler.MarkFailure(); + Scheduler.MarkFailure(); + Scheduler.MarkFailure(); + Assert.Equal(TimeSpan.FromSeconds(20), Scheduler.NextInterval); + Assert.False(Scheduler.ShouldDropBatch); + } + + [Fact] + public void WhenEightFailuresHaveOccurredTheIntervalBacksOffAndBatchIsDropped() + { + for (var i = 0; i < 8; ++i) + { + Assert.False(Scheduler.ShouldDropBatch); + Scheduler.MarkFailure(); + } + Assert.Equal(TimeSpan.FromMinutes(10), Scheduler.NextInterval); + Assert.True(Scheduler.ShouldDropBatch); + Assert.False(Scheduler.ShouldDropQueue); + } + + [Fact] + public void WhenTenFailuresHaveOccurredTheQueueIsDropped() + { + for (var i = 0; i < 10; ++i) + { + Assert.False(Scheduler.ShouldDropQueue); + Scheduler.MarkFailure(); + } + Assert.True(Scheduler.ShouldDropQueue); + } + + [Fact] + public void AtTheDefaultIntervalRetriesForTenMinutesBeforeDroppingBatch() + { + var cumulative = TimeSpan.Zero; + do + { + Scheduler.MarkFailure(); + + if (!Scheduler.ShouldDropBatch) + cumulative += Scheduler.NextInterval; + } while (!Scheduler.ShouldDropBatch); + + Assert.False(Scheduler.ShouldDropQueue); + Assert.Equal(TimeSpan.Parse("00:10:32", CultureInfo.InvariantCulture), cumulative); + } + + [Fact] + public void AtTheDefaultIntervalRetriesForThirtyMinutesBeforeDroppingQueue() + { + var cumulative = TimeSpan.Zero; + do + { + Scheduler.MarkFailure(); + + if (!Scheduler.ShouldDropQueue) + cumulative += Scheduler.NextInterval; + } while (!Scheduler.ShouldDropQueue); + + Assert.Equal(TimeSpan.Parse("00:30:32", CultureInfo.InvariantCulture), cumulative); + } +} diff --git a/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs b/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs index 43a67e4ac..d6f87579e 100644 --- a/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs +++ b/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs @@ -86,8 +86,8 @@ public void WillCaptureSequenceOfScalarsWhenAdditionalNamedPropsNotInTemplateAre { new LogEventProperty("who", new ScalarValue("who")), new LogEventProperty("what", new ScalarValue("what")), - new LogEventProperty("__2", new SequenceValue(new[] { new ScalarValue("__2") })), - new LogEventProperty("__3", new SequenceValue(new[] { new ScalarValue("__3") })), + new LogEventProperty("__2", new SequenceValue([new ScalarValue("__2")])), + new LogEventProperty("__3", new SequenceValue([new ScalarValue("__3")])), }, Capture("Hello {who} {what} where}", "who", "what", new[] { "__2" }, new[] { "__3" }), new LogEventPropertyStructuralEqualityComparer()); @@ -114,10 +114,11 @@ public void CapturingIntArrayAsScalarSequenceValuesWorks() var templateArguments = new[] { 1, 2, 3, }; var expected = new[] { new LogEventProperty("sequence", - new SequenceValue(new[] { + new SequenceValue([ new ScalarValue(1), new ScalarValue(2), - new ScalarValue(3) })) }; + new ScalarValue(3) + ])) }; Assert.Equal(expected, Capture(template, templateArguments), new LogEventPropertyStructuralEqualityComparer()); @@ -130,12 +131,13 @@ public void CapturingDestructuredStringArrayAsScalarSequenceValuesWorks() var templateArguments = new[] { "1", "2", "3", }; var expected = new[] { new LogEventProperty("sequence", - new SequenceValue(new[] { + new SequenceValue([ new ScalarValue("1"), new ScalarValue("2"), - new ScalarValue("3") })) }; + new ScalarValue("3") + ])) }; - Assert.Equal(expected, Capture(template, new object[] { templateArguments }), + Assert.Equal(expected, Capture(template, [templateArguments]), new LogEventPropertyStructuralEqualityComparer()); } diff --git a/test/Serilog.Tests/Core/LoggerTests.cs b/test/Serilog.Tests/Core/LoggerTests.cs index f469021cb..5307b4cc5 100644 --- a/test/Serilog.Tests/Core/LoggerTests.cs +++ b/test/Serilog.Tests/Core/LoggerTests.cs @@ -112,7 +112,7 @@ public void MessageTemplatesCanBeBound(Type loggerType) var log = CreateLogger(loggerType, lc => lc); // ReSharper disable StructuredMessageTemplateProblem - Assert.True(log.BindMessageTemplate("Hello, {Name}!", new object[] { "World" }, out var template, out var properties)); + Assert.True(log.BindMessageTemplate("Hello, {Name}!", ["World"], out var template, out var properties)); // ReSharper restore StructuredMessageTemplateProblem Assert.Equal("Hello, {Name}!", template.Text); @@ -203,7 +203,7 @@ public void DelegatingLoggerShouldDelegateCallsToInnerLogger() Assert.Equal(42, collectingSink.SingleEvent.Properties["number"].LiteralValue()); Assert.Equal( // ReSharper disable once CoVariantArrayConversion - expected: new SequenceValue(new[] { new ScalarValue(1), new ScalarValue(2), new ScalarValue(3) }), + expected: new SequenceValue([new ScalarValue(1), new ScalarValue(2), new ScalarValue(3)]), actual: (SequenceValue)collectingSink.SingleEvent.Properties["values"], comparer: new LogEventPropertyValueComparer()); diff --git a/test/Serilog.Tests/Core/MessageTemplateTests.cs b/test/Serilog.Tests/Core/MessageTemplateTests.cs index 148a4536a..9d289f630 100755 --- a/test/Serilog.Tests/Core/MessageTemplateTests.cs +++ b/test/Serilog.Tests/Core/MessageTemplateTests.cs @@ -8,7 +8,7 @@ class Chair { // ReSharper disable UnusedMember.Local public string Back => "straight"; - public int[] Legs => new[] { 1, 2, 3, 4 }; + public int[] Legs => [1, 2, 3, 4]; // ReSharper restore UnusedMember.Local public override string ToString() => "a chair"; } diff --git a/test/Serilog.Tests/Data/LogEventPropertyValueRewriterTests.cs b/test/Serilog.Tests/Data/LogEventPropertyValueRewriterTests.cs index 97e0a4f7d..bed2a3741 100644 --- a/test/Serilog.Tests/Data/LogEventPropertyValueRewriterTests.cs +++ b/test/Serilog.Tests/Data/LogEventPropertyValueRewriterTests.cs @@ -21,13 +21,12 @@ public class LogEventPropertyValueRewriterTests [Fact] public void StatePropagatesAndNestedStructuresAreRewritten() { - var value = new SequenceValue(new[] - { + var value = new SequenceValue([ new StructureValue(new[] { new LogEventProperty("S", new ScalarValue("abcde")) }) - }); + ]); var limiter = new LimitingRewriter(); var limited = limiter.LimitStringLength(value, 3); @@ -50,13 +49,12 @@ public void StatePropagatesAndNestedStructuresAreRewritten() [Fact] public void WhenNoRewritingTakesPlaceAllElementsAreUnchanged() { - var value = new SequenceValue(new[] - { + var value = new SequenceValue([ new StructureValue(new[] { new LogEventProperty("S", new ScalarValue("abcde")) }) - }); + ]); var limiter = new LimitingRewriter(); var unchanged = limiter.LimitStringLength(value, 10); Assert.Same(value, unchanged); diff --git a/test/Serilog.Tests/Debugging/SelfLogTests.cs b/test/Serilog.Tests/Debugging/SelfLogTests.cs index 5c6efbf0b..2460c04d3 100644 --- a/test/Serilog.Tests/Debugging/SelfLogTests.cs +++ b/test/Serilog.Tests/Debugging/SelfLogTests.cs @@ -8,7 +8,7 @@ public class SelfLogTests [Fact] public void MessagesAreWrittenWhenOutputIsSet() { - Messages = new(); + Messages = []; SelfLog.Enable(m => { Messages.Add(m); @@ -28,7 +28,7 @@ public void MessagesAreWrittenWhenOutputIsSet() [Fact] public void SelfLogReportsErrorWhenPositionalParameterCountIsMismatched() { - Messages = new(); + Messages = []; SelfLog.Enable(m => { Messages.Add(m); @@ -49,7 +49,7 @@ public void SelfLogReportsErrorWhenPositionalParameterCountIsMismatched() [Fact] public void SelfLogDoesNotReportErrorWhenPositionalParameterIsRepeated() { - Messages = new(); + Messages = []; SelfLog.Enable(m => { Messages.Add(m); @@ -69,7 +69,7 @@ public void SelfLogDoesNotReportErrorWhenPositionalParameterIsRepeated() [Fact] public void WritingToUndeclaredSinkWritesToSelfLog() { - Messages = new(); + Messages = []; SelfLog.Enable(m => { Messages.Add(m); diff --git a/test/Serilog.Tests/Events/DictionaryValueTests.cs b/test/Serilog.Tests/Events/DictionaryValueTests.cs index 7cb012378..b13432637 100644 --- a/test/Serilog.Tests/Events/DictionaryValueTests.cs +++ b/test/Serilog.Tests/Events/DictionaryValueTests.cs @@ -9,7 +9,7 @@ public void ADictionaryValueRendersAsMappingOfKeysToValues() new KeyValuePair<ScalarValue, LogEventPropertyValue>( new ScalarValue(1), new ScalarValue("hello")), new KeyValuePair<ScalarValue, LogEventPropertyValue>( - new ScalarValue("world"), new SequenceValue(new [] { new ScalarValue(1.2) })) + new ScalarValue("world"), new SequenceValue([new ScalarValue(1.2)])) }); var sw = new StringWriter(); diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index f0afd5f5b..2db48757e 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -268,7 +268,7 @@ public void SequencesOfSequencesAreSerialized() { var p = new MessageTemplateParser(); var e = new LogEvent(Some.OffsetInstant(), Information, null, - p.Parse("{@AProperty}"), new[] { new LogEventProperty("AProperty", new SequenceValue(new[] { new SequenceValue(new[] { new ScalarValue("Hello") }) })) }); + p.Parse("{@AProperty}"), new[] { new LogEventProperty("AProperty", new SequenceValue([new SequenceValue([new ScalarValue("Hello")])])) }); var d = FormatEvent(e); diff --git a/test/Serilog.Tests/Formatting/Json/JsonValueFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonValueFormatterTests.cs index a4b5329c8..89a38ba1f 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonValueFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonValueFormatterTests.cs @@ -157,7 +157,7 @@ public void ScalarPropertiesFormatAsLiteralValues() [Fact] public void SequencePropertiesFormatAsArrayValue() { - var f = Format(new SequenceValue(new[] { new ScalarValue(123), new ScalarValue(456) })); + var f = Format(new SequenceValue([new ScalarValue(123), new ScalarValue(456)])); Assert.Equal("[123,456]", f); } @@ -183,7 +183,7 @@ public void DictionaryWithScalarKeyFormatsAsAnObject() [Fact] public void SequencesOfSequencesAreFormatted() { - var s = new SequenceValue(new[] { new SequenceValue(new[] { new ScalarValue("Hello") }) }); + var s = new SequenceValue([new SequenceValue([new ScalarValue("Hello")])]); var f = Format(s); Assert.Equal("[[\"Hello\"]]", f); diff --git a/test/Serilog.Tests/MethodOverloadConventionTests.cs b/test/Serilog.Tests/MethodOverloadConventionTests.cs index 852bbf122..425407881 100644 --- a/test/Serilog.Tests/MethodOverloadConventionTests.cs +++ b/test/Serilog.Tests/MethodOverloadConventionTests.cs @@ -247,7 +247,7 @@ public void ValidateWriteEventLogMethods(Type loggerType) var logger = GetLogger(loggerType, out var sink); - InvokeMethod(writeMethod, logger, new object[] { Some.LogEvent(DateTimeOffset.Now, level) }); + InvokeMethod(writeMethod, logger, [Some.LogEvent(DateTimeOffset.Now, level)]); //handle silent logger special case i.e. no result validation if (loggerType == typeof(SilentLogger)) @@ -283,7 +283,7 @@ public void ValidateForContextMethods(Type loggerType) { try { - testMethod.Invoke(this, new object[] { method }); + testMethod.Invoke(this, [method]); signatureMatchAndInvokeSuccess = true; @@ -365,7 +365,7 @@ public void ValidateBindMessageTemplateMethods(Type loggerType) Assert.True(result as bool?); //test null arg path - var falseResult = InvokeMethod(method, logger, new object?[] { null, null, null, null }); + var falseResult = InvokeMethod(method, logger, [null, null, null, null]); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); @@ -421,7 +421,7 @@ public void ValidateBindPropertyMethods(Type loggerType) Assert.True(result as bool?); //test null arg path/ invalid property name - var falseResult = InvokeMethod(method, logger, new object?[] { " ", null, false, null }); + var falseResult = InvokeMethod(method, logger, [" ", null, false, null]); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); @@ -451,12 +451,12 @@ public void ValidateIsEnabledMethods(Type loggerType) var logger = GetLogger(loggerType, out _, Information); - var falseResult = InvokeMethod(method, logger, new object[] { Verbose }); + var falseResult = InvokeMethod(method, logger, [Verbose]); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); - var trueResult = InvokeMethod(method, logger, new object[] { Warning }); + var trueResult = InvokeMethod(method, logger, [Warning]); Assert.IsType<bool>(trueResult); @@ -492,7 +492,7 @@ void ForContextMethod0(MethodInfo method) var logEnricher = new DummyThreadIdEnricher(); - var enrichedLogger = InvokeMethod(method, logger, new object[] { logEnricher }); + var enrichedLogger = InvokeMethod(method, logger, [logEnricher]); TestForContextResult(method, logger, normalResult: enrichedLogger); } @@ -525,7 +525,7 @@ void ForContextMethod1(MethodInfo method) var logEnricher = new DummyThreadIdEnricher(); var enrichedLogger = InvokeMethod(method, logger, - new object[] { new ILogEventEnricher[] { logEnricher, logEnricher } }); + [new ILogEventEnricher[] { logEnricher, logEnricher }]); TestForContextResult(method, logger, normalResult: enrichedLogger); } @@ -564,7 +564,7 @@ void ForContextMethod2(MethodInfo method) var propertyName = "SomeString"; var propertyValue = "someString"; - var enrichedLogger = InvokeMethod(method, logger, new object[] { propertyName, propertyValue, false }); + var enrichedLogger = InvokeMethod(method, logger, [propertyName, propertyValue, false]); Assert.NotNull(enrichedLogger); Assert.True(enrichedLogger is ILogger); @@ -576,7 +576,7 @@ void ForContextMethod2(MethodInfo method) Assert.NotSame(logger, enrichedLogger); //invalid args path - var sameLogger = InvokeMethod(method, logger, new object?[] { null, null, false }); + var sameLogger = InvokeMethod(method, logger, [null, null, false]); Assert.NotNull(sameLogger); Assert.True(sameLogger is ILogger); @@ -611,7 +611,7 @@ void ForContextMethod3(MethodInfo method) var logger = GetLogger(method.DeclaringType!); - var enrichedLogger = InvokeMethod(method, logger, null, new[] { typeof(object) }); + var enrichedLogger = InvokeMethod(method, logger, null, [typeof(object)]); Assert.NotNull(enrichedLogger); Assert.True(enrichedLogger is ILogger); @@ -640,7 +640,7 @@ void ForContextMethod4(MethodInfo method) var logger = GetLogger(method.DeclaringType!); - var enrichedLogger = InvokeMethod(method, logger, new object[] { typeof(object) }); + var enrichedLogger = InvokeMethod(method, logger, [typeof(object)]); TestForContextResult(method, logger, normalResult: enrichedLogger); } @@ -657,7 +657,7 @@ static void TestForContextResult(MethodInfo method, ILogger? logger, object norm Assert.NotSame(logger, normalResult); //if invoked with null args it should return the same instance - var sameLogger = InvokeMethod(method, logger, new object?[] { null }); + var sameLogger = InvokeMethod(method, logger, [null]); Assert.NotNull(sameLogger); @@ -716,7 +716,7 @@ void ValidateConventionForMethodSet( else invokeTestMethod = InvokeConventionMethod; - testMethod.Invoke(this, new object[] { method, invokeTestMethod }); + testMethod.Invoke(this, [method, invokeTestMethod]); signatureMatchAndInvokeSuccess = true; diff --git a/test/Serilog.Tests/Support/CallbackBatchedSink.cs b/test/Serilog.Tests/Support/CallbackBatchedSink.cs new file mode 100644 index 000000000..626ddd1ca --- /dev/null +++ b/test/Serilog.Tests/Support/CallbackBatchedSink.cs @@ -0,0 +1,14 @@ +namespace Serilog.Tests.Support; + +class CallbackBatchedSink(Func<IEnumerable<LogEvent>, Task> callback) : IBatchedLogEventSink +{ + public Task EmitBatchAsync(IReadOnlyCollection<LogEvent> batch) + { + return callback(batch); + } + + public Task OnEmptyBatchAsync() + { + return Task.CompletedTask; + } +} diff --git a/test/Serilog.Tests/Support/CollectingEnricher.cs b/test/Serilog.Tests/Support/CollectingEnricher.cs index 4782ae940..1bfdb4b59 100644 --- a/test/Serilog.Tests/Support/CollectingEnricher.cs +++ b/test/Serilog.Tests/Support/CollectingEnricher.cs @@ -2,7 +2,7 @@ namespace Serilog.Tests.Support; class CollectingEnricher : ILogEventEnricher { - public List<LogEvent> Events { get; } = new(); + public List<LogEvent> Events { get; } = []; public LogEvent SingleEvent => Events.Single(); diff --git a/test/Serilog.Tests/Support/CollectingSink.cs b/test/Serilog.Tests/Support/CollectingSink.cs index 2fd4b59f2..2cf41b8b7 100644 --- a/test/Serilog.Tests/Support/CollectingSink.cs +++ b/test/Serilog.Tests/Support/CollectingSink.cs @@ -2,7 +2,7 @@ namespace Serilog.Tests.Support; class CollectingSink : ILogEventSink { - public List<LogEvent> Events { get; } = new(); + public List<LogEvent> Events { get; } = []; public LogEvent SingleEvent => Events.Single(); diff --git a/test/Serilog.Tests/Support/InMemoryBatchedSink.cs b/test/Serilog.Tests/Support/InMemoryBatchedSink.cs new file mode 100644 index 000000000..0ae904f50 --- /dev/null +++ b/test/Serilog.Tests/Support/InMemoryBatchedSink.cs @@ -0,0 +1,62 @@ +namespace Serilog.Tests.Support; + +sealed class InMemoryBatchedSink(TimeSpan batchEmitDelay) : IBatchedLogEventSink, IDisposable +#if FEATURE_ASYNCDISPOSABLE + , IAsyncDisposable +#endif +{ + readonly object _stateLock = new(); + bool _stopped; + + // Postmortem only + public bool WasCalledAfterDisposal { get; private set; } + public IList<IList<LogEvent>> Batches { get; } = new List<IList<LogEvent>>(); + public bool IsDisposed { get; private set; } + + public void Stop() + { + lock (_stateLock) + { + _stopped = true; + } + } + + public Task EmitBatchAsync(IReadOnlyCollection<LogEvent> events) + { + lock (_stateLock) + { + if (_stopped) + return Task.CompletedTask; + + if (IsDisposed) + WasCalledAfterDisposal = true; + + Thread.Sleep(batchEmitDelay); + Batches.Add(events.ToList()); + } + + return Task.CompletedTask; + } + + public Task OnEmptyBatchAsync() => Task.CompletedTask; + + public void Dispose() + { + lock (_stateLock) + IsDisposed = true; + } + +#if FEATURE_ASYNCDISPOSABLE + public bool IsDisposedAsync { get; private set; } + + public ValueTask DisposeAsync() + { + lock (_stateLock) + { + IsDisposedAsync = true; + Dispose(); + return default; + } + } +#endif +} diff --git a/test/Serilog.Tests/Support/LogEventPropertyStructuralEqualityComparerTests.cs b/test/Serilog.Tests/Support/LogEventPropertyStructuralEqualityComparerTests.cs index b84b0e901..0e03c6fbc 100644 --- a/test/Serilog.Tests/Support/LogEventPropertyStructuralEqualityComparerTests.cs +++ b/test/Serilog.Tests/Support/LogEventPropertyStructuralEqualityComparerTests.cs @@ -23,10 +23,10 @@ public void LogEventPropertyStructuralEqualityComparerWorksForSequences() var sequenceOfScalarsIntStringDoubleA = new LogEventProperty("a", new SequenceValue(intStringDoubleScalarArray)); var sequenceOfScalarsIntStringDoubleAStructurallyEqual = new LogEventProperty("a", - new SequenceValue(new[] { new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.0), })); + new SequenceValue([new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.0)])); var sequenceOfScalarsIntStringDoubleAStructurallyNotEqual = new LogEventProperty("a", - new SequenceValue(new[] { new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.1), })); + new SequenceValue([new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.1)])); var sequenceOfScalarsIntStringFloatA = new LogEventProperty("a", new ScalarValue(intStringFloatScalarArray)); diff --git a/test/TestDummies/DummyRollingFileAuditSink.cs b/test/TestDummies/DummyRollingFileAuditSink.cs index f9365e016..86a73b012 100644 --- a/test/TestDummies/DummyRollingFileAuditSink.cs +++ b/test/TestDummies/DummyRollingFileAuditSink.cs @@ -5,7 +5,7 @@ public class DummyRollingFileAuditSink : ILogEventSink [ThreadStatic] static List<LogEvent>? _emitted; - public static List<LogEvent> Emitted => _emitted ??= new(); + public static List<LogEvent> Emitted => _emitted ??= []; public void Emit(LogEvent logEvent) { diff --git a/test/TestDummies/DummyRollingFileSink.cs b/test/TestDummies/DummyRollingFileSink.cs index f822e9bcd..372b688a6 100644 --- a/test/TestDummies/DummyRollingFileSink.cs +++ b/test/TestDummies/DummyRollingFileSink.cs @@ -5,7 +5,7 @@ public class DummyRollingFileSink : ILogEventSink [ThreadStatic] static List<LogEvent>? _emitted; - public static List<LogEvent> Emitted => _emitted ??= new(); + public static List<LogEvent> Emitted => _emitted ??= []; public void Emit(LogEvent logEvent) { diff --git a/test/TestDummies/DummyWithLevelSwitchSink.cs b/test/TestDummies/DummyWithLevelSwitchSink.cs index c8d19c9b2..4ffbc9f7a 100644 --- a/test/TestDummies/DummyWithLevelSwitchSink.cs +++ b/test/TestDummies/DummyWithLevelSwitchSink.cs @@ -12,7 +12,7 @@ public DummyWithLevelSwitchSink(LoggingLevelSwitch? loggingControlLevelSwitch) [ThreadStatic] // ReSharper disable ThreadStaticFieldHasInitializer - public static List<LogEvent> Emitted = new(); + public static List<LogEvent> Emitted = []; // ReSharper restore ThreadStaticFieldHasInitializer public void Emit(LogEvent logEvent) diff --git a/test/TestDummies/DummyWrappingSink.cs b/test/TestDummies/DummyWrappingSink.cs index 5b8f782fc..e7ef9c34d 100644 --- a/test/TestDummies/DummyWrappingSink.cs +++ b/test/TestDummies/DummyWrappingSink.cs @@ -5,7 +5,7 @@ public class DummyWrappingSink : ILogEventSink [ThreadStatic] static List<LogEvent>? _emitted; - public static List<LogEvent> Emitted => _emitted ??= new(); + public static List<LogEvent> Emitted => _emitted ??= []; readonly ILogEventSink _sink;
`WriteTo.Batched()` and `IBatchedLogEventSink` _Serilog.Sinks.PeriodicBatching_ is used by many, many publicly-available Serilog sinks. Although currently managed as a separate package, it's a fundamental part of the ecosystem. Over the past two years we've been trying to update _Serilog.Sinks.PeriodicBatching_ to work more efficiently with async and tasks, but moving things forward cleanly has been [hampered by ten years of downstream consuming packages](https://github.com/serilog/serilog-sinks-periodicbatching/issues/74) in various states of (non-) maintenance. I've just [drafted a PR to revert _Serilog.Sinks.PeriodicBatching_ to its original API, again](https://github.com/serilog/serilog-sinks-periodicbatching/pull/75). My proposal is that after merging it, we put _Serilog.Sinks.PeriodicBatching_ into legacy/maintenance mode, and move `IBatchedLogEventSink` into _Serilog_ itself. Along with the interface, we'd add a `WriteTo.Batched()` public API on `LoggerConfiguration`, along with a public "options" type to parameterize it, and an internal `BatchingSink` implementation. The full cost here would be ~4 types, and a _System.Threading.Channels_ dependency (supported on all current TFMs). This would present the opportunity we need to nail down a minimal, stable, evolvable API, while promoting batch-oriented sinks to a first-class part of Serilog. Maintained sinks would migrate and drop their _PeriodicBatching_ dependency, while unmaintained sinks could continue using the older package. Although it may not be in scope for the initial version of the feature, the underlying implementation of the updated batching sink in Serilog could also drive a built-in `WriteTo.Async()`, given the current _Serilog.Sinks.Async_ is expected to migrate to a very similar implementation based on _System.Threading.Channels_ in the future.
null
2024-05-02T00:13:27Z
0.1
['Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeAsync', 'Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnDispose', 'Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnTimer', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenOneFailureHasOccurredTheInitialIntervalIsUsed', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenABatchSucceedsTheStatusResets', 'Serilog.Core.Tests.BatchingSinkTests.EagerlyEmitFirstEventCausesQuickInitialBatch', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.AtTheDefaultIntervalRetriesForTenMinutesBeforeDroppingBatch', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenNoFailuresHaveOccurredTheInitialIntervalIsUsed', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenTwoFailuresHaveOccurredTheIntervalBacksOff', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenTenFailuresHaveOccurredTheQueueIsDropped', 'Serilog.Core.Tests.BatchingSinkTests.WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeWhileRunning', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.AtTheDefaultIntervalRetriesForThirtyMinutesBeforeDroppingQueue', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenThreeFailuresHaveOccurredTheIntervalBacksOff', 'Serilog.Core.Tests.FailureAwareBatchSchedulerTests.WhenEightFailuresHaveOccurredTheIntervalBacksOffAndBatchIsDropped', 'Serilog.Core.Tests.BatchingSinkTests.ExecutionContextDoesNotFlowToBatchedSink']
[]
serilog/serilog
serilog__serilog-1955
63bff1e93f8141b1ffa9f1632d05f90c72c42f65
diff --git a/Serilog.sln b/Serilog.sln index 066faba06..7e847867e 100644 --- a/Serilog.sln +++ b/Serilog.sln @@ -8,7 +8,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{E9D1B5 appveyor.yml = appveyor.yml Build.ps1 = Build.ps1 build.sh = build.sh - CHANGES.md = CHANGES.md Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets global.json = global.json diff --git a/Serilog.sln.DotSettings b/Serilog.sln.DotSettings index d98a03dac..b9aebc18f 100644 --- a/Serilog.sln.DotSettings +++ b/Serilog.sln.DotSettings @@ -218,6 +218,7 @@ <s:Boolean x:Key="/Default/UserDictionary/Words/=destructure/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Enricher/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Enrichers/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/UserDictionary/Words/=formattable/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Obsoletion/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=stringified/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary> \ No newline at end of file diff --git a/src/Serilog/Core/Logger.cs b/src/Serilog/Core/Logger.cs index a39b91058..7ab16d433 100644 --- a/src/Serilog/Core/Logger.cs +++ b/src/Serilog/Core/Logger.cs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; + #pragma warning disable Serilog004 // Constant MessageTemplate verifier namespace Serilog.Core; @@ -79,7 +81,7 @@ internal Logger( /// <returns>A logger that will enrich log events as specified.</returns> public ILogger ForContext(ILogEventEnricher enricher) { - if (enricher == null) + if (enricher == null!) return this; // No context here, so little point writing to SelfLog. return new Logger( @@ -102,7 +104,7 @@ public ILogger ForContext(ILogEventEnricher enricher) /// <returns>A logger that will enrich log events as specified.</returns> public ILogger ForContext(IEnumerable<ILogEventEnricher> enrichers) { - if (enrichers == null) + if (enrichers == null!) return this; // No context here, so little point writing to SelfLog. return ForContext(new SafeAggregateEnricher(enrichers)); @@ -164,7 +166,7 @@ public ILogger ForContext(string propertyName, object? value, bool destructureOb /// <returns>A logger that will enrich log events as specified.</returns> public ILogger ForContext(Type source) { - if (source == null) + if (source == null!) return this; // Little point in writing to SelfLog here because we don't have any contextual information return ForContext(Constants.SourceContextPropertyName, source.FullName); @@ -352,7 +354,7 @@ public void Write<T0, T1, T2>(LogEventLevel level, Exception? exception, string public void Write(LogEventLevel level, Exception? exception, string messageTemplate, params object?[]? propertyValues) { if (!IsEnabled(level)) return; - if (messageTemplate == null) return; + if (messageTemplate == null!) return; // Catch a common pitfall when a single non-object array is cast to object[] if (propertyValues != null && @@ -362,7 +364,8 @@ public void Write(LogEventLevel level, Exception? exception, string messageTempl var logTimestamp = DateTimeOffset.Now; _messageTemplateProcessor.Process(messageTemplate, propertyValues, out var parsedTemplate, out var boundProperties); - var logEvent = new LogEvent(logTimestamp, level, exception, parsedTemplate, boundProperties); + var currentActivity = Activity.Current; + var logEvent = new LogEvent(logTimestamp, level, exception, parsedTemplate, boundProperties, currentActivity?.TraceId ?? default, currentActivity?.SpanId ?? default); Dispatch(logEvent); } @@ -372,7 +375,7 @@ public void Write(LogEventLevel level, Exception? exception, string messageTempl /// <param name="logEvent">The event to write.</param> public void Write(LogEvent logEvent) { - if (logEvent == null) return; + if (logEvent == null!) return; if (!IsEnabled(logEvent.Level)) return; Dispatch(logEvent); } diff --git a/src/Serilog/Events/LogEvent.cs b/src/Serilog/Events/LogEvent.cs index 2950da1e7..e66d0d913 100644 --- a/src/Serilog/Events/LogEvent.cs +++ b/src/Serilog/Events/LogEvent.cs @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; +// ReSharper disable IntroduceOptionalParameters.Global + namespace Serilog.Events; /// <summary> @@ -20,12 +23,23 @@ namespace Serilog.Events; public class LogEvent { readonly Dictionary<string, LogEventPropertyValue> _properties; - - LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exception, MessageTemplate messageTemplate, Dictionary<string, LogEventPropertyValue> properties) + ActivityTraceId _traceId; + ActivitySpanId _spanId; + + LogEvent( + DateTimeOffset timestamp, + LogEventLevel level, + Exception? exception, + MessageTemplate messageTemplate, + Dictionary<string, LogEventPropertyValue> properties, + ActivityTraceId traceId, + ActivitySpanId spanId) { Timestamp = timestamp; Level = level; Exception = exception; + _traceId = traceId; + _spanId = spanId; MessageTemplate = Guard.AgainstNull(messageTemplate); _properties = Guard.AgainstNull(properties); } @@ -41,12 +55,8 @@ public class LogEvent /// <exception cref="ArgumentNullException">When <paramref name="messageTemplate"/> is <code>null</code></exception> /// <exception cref="ArgumentNullException">When <paramref name="properties"/> is <code>null</code></exception> public LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exception, MessageTemplate messageTemplate, IEnumerable<LogEventProperty> properties) - : this(timestamp, level, exception, messageTemplate, new Dictionary<string, LogEventPropertyValue>()) + : this(timestamp, level, exception, messageTemplate, properties, default, default) { - Guard.AgainstNull(properties); - - foreach (var property in properties) - AddOrUpdateProperty(property); } /// <summary> @@ -57,10 +67,22 @@ public LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? except /// <param name="exception">An exception associated with the event, or null.</param> /// <param name="messageTemplate">The message template describing the event.</param> /// <param name="properties">Properties associated with the event, including those presented in <paramref name="messageTemplate"/>.</param> + /// <param name="traceId">The id of the trace that was active when the event was created, if any.</param> + /// <param name="spanId">The id of the span that was active when the event was created, if any.</param> /// <exception cref="ArgumentNullException">When <paramref name="messageTemplate"/> is <code>null</code></exception> /// <exception cref="ArgumentNullException">When <paramref name="properties"/> is <code>null</code></exception> - internal LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exception, MessageTemplate messageTemplate, EventProperty[] properties) - : this(timestamp, level, exception, messageTemplate, new Dictionary<string, LogEventPropertyValue>(Guard.AgainstNull(properties).Length)) + [CLSCompliant(false)] + public LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exception, MessageTemplate messageTemplate, IEnumerable<LogEventProperty> properties, ActivityTraceId traceId, ActivitySpanId spanId) + : this(timestamp, level, exception, messageTemplate, new Dictionary<string, LogEventPropertyValue>(), traceId, spanId) + { + Guard.AgainstNull(properties); + + foreach (var property in properties) + AddOrUpdateProperty(property); + } + + internal LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exception, MessageTemplate messageTemplate, EventProperty[] properties, ActivityTraceId traceId, ActivitySpanId spanId) + : this(timestamp, level, exception, messageTemplate, new Dictionary<string, LogEventPropertyValue>(Guard.AgainstNull(properties).Length), traceId, spanId) { for (var i = 0; i < properties.Length; ++i) _properties[properties[i].Name] = properties[i].Value; @@ -76,6 +98,18 @@ internal LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception? exce /// </summary> public LogEventLevel Level { get; } + /// <summary> + /// The id of the trace that was active when the event was created, if any. + /// </summary> + [CLSCompliant(false)] + public ActivityTraceId? TraceId => _traceId == default ? null : _traceId; + + /// <summary> + /// The id of the span that was active when the event was created, if any. + /// </summary> + [CLSCompliant(false)] + public ActivitySpanId? SpanId => _spanId == default ? null : _spanId; + /// <summary> /// The message template describing the event. /// </summary> @@ -201,6 +235,8 @@ internal LogEvent Copy() Level, Exception, MessageTemplate, - properties); + properties, + TraceId ?? default, + SpanId ?? default); } } diff --git a/src/Serilog/Formatting/Display/MessageTemplateTextFormatter.cs b/src/Serilog/Formatting/Display/MessageTemplateTextFormatter.cs index aca0e650c..835124883 100644 --- a/src/Serilog/Formatting/Display/MessageTemplateTextFormatter.cs +++ b/src/Serilog/Formatting/Display/MessageTemplateTextFormatter.cs @@ -24,6 +24,7 @@ namespace Serilog.Formatting.Display; /// to them. Second, tokens without matching properties are skipped /// rather than being written as raw text. /// </summary> +/// <remarks>New code should prefer <c>ExpressionTemplate</c> from <c>Serilog.Expressions</c>.</remarks> public class MessageTemplateTextFormatter : ITextFormatter { readonly IFormatProvider? _formatProvider; @@ -70,6 +71,14 @@ public void Format(LogEvent logEvent, TextWriter output) var moniker = LevelOutputFormat.GetLevelMoniker(logEvent.Level, pt.Format); Padding.Apply(output, moniker, pt.Alignment); } + else if (pt.PropertyName == OutputProperties.TraceIdPropertyName) + { + Padding.Apply(output, logEvent.TraceId?.ToString() ?? "", pt.Alignment); + } + else if (pt.PropertyName == OutputProperties.SpanIdPropertyName) + { + Padding.Apply(output, logEvent.SpanId?.ToString() ?? "", pt.Alignment); + } else if (pt.PropertyName == OutputProperties.NewLinePropertyName) { Padding.Apply(output, Environment.NewLine, pt.Alignment); diff --git a/src/Serilog/Formatting/Display/OutputProperties.cs b/src/Serilog/Formatting/Display/OutputProperties.cs index 1f11398b4..e24cc65f2 100644 --- a/src/Serilog/Formatting/Display/OutputProperties.cs +++ b/src/Serilog/Formatting/Display/OutputProperties.cs @@ -35,6 +35,16 @@ public static class OutputProperties /// </summary> public const string LevelPropertyName = "Level"; + /// <summary> + /// The id of the trace that was active at the log event's time of creation, if any. + /// </summary> + public const string TraceIdPropertyName = "TraceId"; + + /// <summary> + /// The id of the span that was active at the log event's time of creation, if any. + /// </summary> + public const string SpanIdPropertyName = "SpanId"; + /// <summary> /// A new line. /// </summary> diff --git a/src/Serilog/Formatting/Json/JsonFormatter.cs b/src/Serilog/Formatting/Json/JsonFormatter.cs index fab5e95e7..b5c7a9e89 100644 --- a/src/Serilog/Formatting/Json/JsonFormatter.cs +++ b/src/Serilog/Formatting/Json/JsonFormatter.cs @@ -71,6 +71,18 @@ public void Format(LogEvent logEvent, TextWriter output) JsonValueFormatter.WriteQuotedJsonString(message, output); } + if (logEvent.TraceId != null) + { + output.Write(",\"TraceId\":"); + JsonValueFormatter.WriteQuotedJsonString(logEvent.TraceId.ToString()!, output); + } + + if (logEvent.SpanId != null) + { + output.Write(",\"SpanId\":"); + JsonValueFormatter.WriteQuotedJsonString(logEvent.SpanId.ToString()!, output); + } + if (logEvent.Exception != null) { output.Write(",\"Exception\":"); diff --git a/src/Serilog/ILogger.cs b/src/Serilog/ILogger.cs index c307d21d0..95ac8d67f 100644 --- a/src/Serilog/ILogger.cs +++ b/src/Serilog/ILogger.cs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; + namespace Serilog; /// <summary> @@ -62,7 +64,7 @@ ILogger ForContext(ILogEventEnricher enricher) ILogger ForContext(IEnumerable<ILogEventEnricher> enrichers) #if FEATURE_DEFAULT_INTERFACE { - if (enrichers == null) + if (enrichers == null!) return this; // No context here, so little point writing to SelfLog. return ForContext(new SafeAggregateEnricher(enrichers)); @@ -113,7 +115,7 @@ ILogger ForContext<TSource>() ILogger ForContext(Type source) #if FEATURE_DEFAULT_INTERFACE { - if (source == null) + if (source == null!) return this; // Little point in writing to SelfLog here because we don't have any contextual information return ForContext(Constants.SourceContextPropertyName, source.FullName); @@ -324,16 +326,19 @@ void Write(LogEventLevel level, Exception? exception, string messageTemplate, pa #if FEATURE_DEFAULT_INTERFACE { if (!IsEnabled(level)) return; - if (messageTemplate == null) return; + if (messageTemplate == null!) return; // Catch a common pitfall when a single non-object array is cast to object[] if (propertyValues != null && propertyValues.GetType() != typeof(object[])) propertyValues = new object[] { propertyValues }; + var logTimestamp = DateTimeOffset.Now; if (BindMessageTemplate(messageTemplate, propertyValues, out var parsedTemplate, out var boundProperties)) { - Write(new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, boundProperties)); + var currentActivity = Activity.Current; + var logEvent = new LogEvent(logTimestamp, level, exception, parsedTemplate, boundProperties, currentActivity?.TraceId ?? default, currentActivity?.SpanId ?? default); + Write(logEvent); } } #else diff --git a/src/Serilog/Serilog.csproj b/src/Serilog/Serilog.csproj index 6ef15e6b8..b01695e9e 100644 --- a/src/Serilog/Serilog.csproj +++ b/src/Serilog/Serilog.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Description>Simple .NET logging with fully-structured events</Description> - <VersionPrefix>3.0.2</VersionPrefix> + <VersionPrefix>3.1.0</VersionPrefix> <Authors>Serilog Contributors</Authors> <TargetFrameworks Condition=" '$(OS)' == 'Windows_NT'">net462;net471</TargetFrameworks> <TargetFrameworks>$(TargetFrameworks);netstandard2.1;netstandard2.0;net5.0;net6.0;net7.0</TargetFrameworks> @@ -66,6 +66,19 @@ <ItemGroup Condition=" '$(TargetFramework)' == 'net462' "> <PackageReference Include="System.ValueTuple" Version="4.5.0" /> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + </ItemGroup> + + <ItemGroup Condition=" '$(TargetFramework)' == 'net471' "> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + </ItemGroup> + + <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> + </ItemGroup> + + <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.1' "> + <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> </ItemGroup> </Project>
diff --git a/test/Serilog.ApprovalTests/Serilog.approved.txt b/test/Serilog.ApprovalTests/Serilog.approved.txt index 4aba4ae9a..1824ecc72 100644 --- a/test/Serilog.ApprovalTests/Serilog.approved.txt +++ b/test/Serilog.ApprovalTests/Serilog.approved.txt @@ -358,11 +358,17 @@ namespace Serilog.Events public class LogEvent { public LogEvent(System.DateTimeOffset timestamp, Serilog.Events.LogEventLevel level, System.Exception? exception, Serilog.Events.MessageTemplate messageTemplate, System.Collections.Generic.IEnumerable<Serilog.Events.LogEventProperty> properties) { } + [System.CLSCompliant(false)] + public LogEvent(System.DateTimeOffset timestamp, Serilog.Events.LogEventLevel level, System.Exception? exception, Serilog.Events.MessageTemplate messageTemplate, System.Collections.Generic.IEnumerable<Serilog.Events.LogEventProperty> properties, System.Diagnostics.ActivityTraceId traceId, System.Diagnostics.ActivitySpanId spanId) { } public System.Exception? Exception { get; } public Serilog.Events.LogEventLevel Level { get; } public Serilog.Events.MessageTemplate MessageTemplate { get; } public System.Collections.Generic.IReadOnlyDictionary<string, Serilog.Events.LogEventPropertyValue> Properties { get; } + [System.CLSCompliant(false)] + public System.Diagnostics.ActivitySpanId? SpanId { get; } public System.DateTimeOffset Timestamp { get; } + [System.CLSCompliant(false)] + public System.Diagnostics.ActivityTraceId? TraceId { get; } public void AddOrUpdateProperty(Serilog.Events.LogEventProperty property) { } public void AddPropertyIfAbsent(Serilog.Events.LogEventProperty property) { } public void RemovePropertyIfPresent(string propertyName) { } @@ -452,7 +458,9 @@ namespace Serilog.Formatting.Display public const string MessagePropertyName = "Message"; public const string NewLinePropertyName = "NewLine"; public const string PropertiesPropertyName = "Properties"; + public const string SpanIdPropertyName = "SpanId"; public const string TimestampPropertyName = "Timestamp"; + public const string TraceIdPropertyName = "TraceId"; } } namespace Serilog.Formatting diff --git a/test/Serilog.PerformanceTests/PipelineBenchmark.cs b/test/Serilog.PerformanceTests/PipelineBenchmark.cs index 2509a0960..946dd7ed3 100644 --- a/test/Serilog.PerformanceTests/PipelineBenchmark.cs +++ b/test/Serilog.PerformanceTests/PipelineBenchmark.cs @@ -30,9 +30,6 @@ public void Setup() _log = new LoggerConfiguration() .WriteTo.Sink(new NullSink()) .CreateLogger(); - - // Ensure template is cached - _log.Information(_exception, "Hello, {Name}!", "World"); } [Benchmark] diff --git a/test/Serilog.Tests/Core/LoggerTests.cs b/test/Serilog.Tests/Core/LoggerTests.cs index 799139766..5b555d082 100644 --- a/test/Serilog.Tests/Core/LoggerTests.cs +++ b/test/Serilog.Tests/Core/LoggerTests.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + #pragma warning disable Serilog004 // Constant MessageTemplate verifier #pragma warning disable Serilog003 // Property binding verifier @@ -5,6 +7,14 @@ namespace Serilog.Tests.Core; public class LoggerTests { + static LoggerTests() + { + // This is necessary to force activity id allocation on .NET Framework and early .NET Core versions. When this isn't + // done, log events end up carrying null trace and span ids (which is fine). + Activity.DefaultIdFormat = ActivityIdFormat.W3C; + Activity.ForceDefaultIdFormat = true; + } + [Theory] [InlineData(typeof(Logger))] #if FEATURE_DEFAULT_INTERFACE @@ -54,7 +64,9 @@ public void PropertiesInANestedContextOverrideParentContextValues() [Fact] public void ParametersForAnEmptyTemplateAreIgnored() { + // ReSharper disable StructuredMessageTemplateProblem var e = DelegatingSink.GetLogEvent(l => l.Error("message", new object())); + // ReSharper restore StructuredMessageTemplateProblem Assert.Equal("message", e.RenderMessage()); } @@ -99,7 +111,9 @@ public void MessageTemplatesCanBeBound(Type loggerType) { var log = CreateLogger(loggerType, lc => lc); + // ReSharper disable StructuredMessageTemplateProblem Assert.True(log.BindMessageTemplate("Hello, {Name}!", new object[] { "World" }, out var template, out var properties)); + // ReSharper restore StructuredMessageTemplateProblem Assert.Equal("Hello, {Name}!", template.Text); Assert.Equal("World", properties.Single().Value.LiteralValue()); @@ -188,6 +202,7 @@ public void DelegatingLoggerShouldDelegateCallsToInnerLogger() Assert.Equal("message", collectingSink.SingleEvent.Properties["prop"].LiteralValue()); Assert.Equal(42, collectingSink.SingleEvent.Properties["number"].LiteralValue()); Assert.Equal( + // ReSharper disable once CoVariantArrayConversion expected: new SequenceValue(new[] { new ScalarValue(1), new ScalarValue(2), new ScalarValue(3) }), actual: (SequenceValue)collectingSink.SingleEvent.Properties["values"], comparer: new LogEventPropertyValueComparer()); @@ -260,6 +275,34 @@ public void WrappedAggregatedSinksAreDisposedWhenLoggerIsDisposed() Assert.True(sinkB.IsDisposed); } + [Fact] + public void CurrentActivityIsCapturedAtLogEventCreation() + { + using var listener = new ActivityListener(); + listener.ShouldListenTo = _ => true; + listener.SampleUsingParentId = (ref ActivityCreationOptions<string> _) => ActivitySamplingResult.AllData; + listener.Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllData; + ActivitySource.AddActivityListener(listener); + + using var source = new ActivitySource(Some.String()); + using var activity = source.StartActivity(Some.String()); + Assert.NotNull(activity); + Assert.NotEqual("00000000000000000000000000000000", activity.TraceId.ToHexString()); + Assert.NotEqual("0000000000000000", activity.SpanId.ToHexString()); + + var sink = new CollectingSink(); + var log = new LoggerConfiguration() + .WriteTo.Sink(sink) + .CreateLogger(); + + log.Information("Hello, world!"); + + var single = sink.SingleEvent; + + Assert.Equal(activity.TraceId, single.TraceId); + Assert.Equal(activity.SpanId, single.SpanId); + } + #if FEATURE_ASYNCDISPOSABLE [Fact] diff --git a/test/Serilog.Tests/Events/LogEventTests.cs b/test/Serilog.Tests/Events/LogEventTests.cs new file mode 100644 index 000000000..59d35b967 --- /dev/null +++ b/test/Serilog.Tests/Events/LogEventTests.cs @@ -0,0 +1,17 @@ +using System.Diagnostics; + +namespace Serilog.Tests.Events; + +public class LogEventTests +{ + [Fact] + public void CopiedLogEventsPropagateTraceAndSpan() + { + var traceId = ActivityTraceId.CreateRandom(); + var spanId = ActivitySpanId.CreateRandom(); + var evt = Some.LogEvent(traceId: traceId, spanId: spanId); + var copy = evt.Copy(); + Assert.Equal(traceId, copy.TraceId); + Assert.Equal(spanId, copy.SpanId); + } +} diff --git a/test/Serilog.Tests/Formatting/Display/MessageTemplateTextFormatterTests.cs b/test/Serilog.Tests/Formatting/Display/MessageTemplateTextFormatterTests.cs index 6b0268988..6d532523a 100644 --- a/test/Serilog.Tests/Formatting/Display/MessageTemplateTextFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Display/MessageTemplateTextFormatterTests.cs @@ -1,4 +1,8 @@ +// ReSharper disable StringLiteralTypo + +using System.Diagnostics; + namespace Serilog.Tests.Formatting.Display; public class MessageTemplateTextFormatterTests @@ -53,12 +57,12 @@ public void LowercaseFormatSpecifierIsSupportedForStrings() [InlineData(Verbose, 6, "Verbos")] [InlineData(Verbose, 7, "Verbose")] [InlineData(Verbose, 8, "Verbose")] - [InlineData(Debug, 1, "D")] - [InlineData(Debug, 2, "De")] - [InlineData(Debug, 3, "Dbg")] - [InlineData(Debug, 4, "Dbug")] - [InlineData(Debug, 5, "Debug")] - [InlineData(Debug, 6, "Debug")] + [InlineData(LogEventLevel.Debug, 1, "D")] + [InlineData(LogEventLevel.Debug, 2, "De")] + [InlineData(LogEventLevel.Debug, 3, "Dbg")] + [InlineData(LogEventLevel.Debug, 4, "Dbug")] + [InlineData(LogEventLevel.Debug, 5, "Debug")] + [InlineData(LogEventLevel.Debug, 6, "Debug")] [InlineData(Information, 1, "I")] [InlineData(Information, 2, "In")] [InlineData(Information, 3, "Inf")] @@ -354,4 +358,26 @@ public void PaddingIsApplied(int n, string format, string expected) formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } + + [Fact] + public void TraceAndSpanAreEmptyWhenAbsent() + { + var formatter = new MessageTemplateTextFormatter("{TraceId}/{SpanId}", CultureInfo.InvariantCulture); + var evt = Some.LogEvent(traceId: default, spanId: default); + var sw = new StringWriter(); + formatter.Format(evt, sw); + Assert.Equal("/", sw.ToString()); + } + + [Fact] + public void TraceAndSpanAreIncludedWhenPresent() + { + var traceId = ActivityTraceId.CreateRandom(); + var spanId = ActivitySpanId.CreateRandom(); + var formatter = new MessageTemplateTextFormatter("{TraceId}/{SpanId}", CultureInfo.InvariantCulture); + var evt = Some.LogEvent(traceId: traceId, spanId: spanId); + var sw = new StringWriter(); + formatter.Format(evt, sw); + Assert.Equal($"{traceId}/{spanId}", sw.ToString()); + } } diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index 006255a34..f0afd5f5b 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using System.Collections.ObjectModel; +using System.Diagnostics; namespace Serilog.Tests.Formatting.Json; @@ -288,6 +289,32 @@ public void RenderedMessageIsIncludedCorrectlyWhenRequired() formatter.Format(e, buffer); var json = buffer.ToString(); - Assert.Contains(@",""MessageTemplate"":""value: {AProperty}"",""RenderedMessage"":""value: 12"",", json); + Assert.Contains(""","MessageTemplate":"value: {AProperty}","RenderedMessage":"value: 12",""", json); + } + + [Fact] + public void TraceAndSpanAreIgnoredWhenAbsent() + { + var evt = Some.LogEvent(traceId: default, spanId: default); + var sw = new StringWriter(); + var formatter = new JsonFormatter(); + formatter.Format(evt, sw); + var formatted = sw.ToString(); + Assert.DoesNotContain("TraceId", formatted); + Assert.DoesNotContain("SpanId", formatted); + } + + [Fact] + public void TraceAndSpanAreIncludedWhenPresent() + { + var traceId = ActivityTraceId.CreateRandom(); + var spanId = ActivitySpanId.CreateRandom(); + var evt = Some.LogEvent(traceId: traceId, spanId: spanId); + var sw = new StringWriter(); + var formatter = new JsonFormatter(); + formatter.Format(evt, sw); + var formatted = sw.ToString(); + Assert.Contains($"\"TraceId\":\"{traceId}\"", formatted); + Assert.Contains($"\"SpanId\":\"{spanId}\"", formatted); } } diff --git a/test/Serilog.Tests/LoggerConfigurationTests.cs b/test/Serilog.Tests/LoggerConfigurationTests.cs index 7ff386da0..1d020114e 100644 --- a/test/Serilog.Tests/LoggerConfigurationTests.cs +++ b/test/Serilog.Tests/LoggerConfigurationTests.cs @@ -602,12 +602,6 @@ public void ExceptionsThrownByDestructuringPoliciesAreNotPropagated() Assert.True(true, "No exception reached the caller"); } - class ThrowingProperty - { - // ReSharper disable once UnusedMember.Local - public string Property => throw new("Boom!"); - } - [Fact] public void WrappingDecoratesTheConfiguredSink() { diff --git a/test/Serilog.Tests/Support/Some.cs b/test/Serilog.Tests/Support/Some.cs index ab0edece7..c91ce75df 100644 --- a/test/Serilog.Tests/Support/Some.cs +++ b/test/Serilog.Tests/Support/Some.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + namespace Serilog.Tests.Support; static class Some @@ -16,17 +18,25 @@ static class Some public static DateTimeOffset OffsetInstant() => new(Instant()); - public static LogEvent LogEvent(string sourceContext, DateTimeOffset? timestamp = null, LogEventLevel level = Information) - { - return new(timestamp ?? OffsetInstant(), level, - null, MessageTemplate(), - new List<LogEventProperty> { new(Constants.SourceContextPropertyName, new ScalarValue(sourceContext)) }); - } - - public static LogEvent LogEvent(DateTimeOffset? timestamp = null, LogEventLevel level = Information) + public static LogEvent LogEvent( + DateTimeOffset? timestamp = null, + LogEventLevel level = Information, + Exception? exception = null, + string? messageTemplate = null, + object?[]? propertyValues = null, + ActivityTraceId traceId = default, + ActivitySpanId spanId = default) { - return new(timestamp ?? OffsetInstant(), level, - null, MessageTemplate(), Enumerable.Empty<LogEventProperty>()); + var logger = new LoggerConfiguration().CreateLogger(); + Assert.True(logger.BindMessageTemplate(messageTemplate ?? "DEFAULT TEMPLATE", propertyValues, out var parsedTemplate, out var boundProperties)); + return new( + timestamp ?? OffsetInstant(), + level, + exception, + parsedTemplate, + boundProperties, + traceId, + spanId); } public static LogEvent InformationEvent(DateTimeOffset? timestamp = null) @@ -36,7 +46,7 @@ public static LogEvent InformationEvent(DateTimeOffset? timestamp = null) public static LogEvent DebugEvent(DateTimeOffset? timestamp = null) { - return LogEvent(timestamp, Debug); + return LogEvent(timestamp, LogEventLevel.Debug); } public static LogEvent WarningEvent(DateTimeOffset? timestamp = null)
Discussion: built-in trace and span ids Trace and span correlation has become a widespread feature of diagnostics in .NET and elsewhere. If Serilog was designed today, it's more than likely that trace and span ids would be on an equal footing with levels, messages, and exceptions, as first-class attributes of log events. ## What are trace and span ids used for? A _trace_ constitutes one or more local operations - _spans_ - that occur within a larger, distributed unit of work. Tracing systems use trace and span identifiers to build a causal, hierarchical view of work done within a system. Annotating log events with trace and span ids mean that, when inspecting a trace, events occurring within the context of the trace or a particular span can be readily identified. In the absence of a dedicated tracing system, trace and span ids are still often present, and can therefore be used as a convenient way to correlate log events that were generated during a particular piece of work. ## Why give trace and span ids first-class support? Serilog's enrichment features are frequently used to attach `TraceId`, `SpanId`, and related properties to `LogEvents`. While this can be made to work for the most part, the lack of standardized names and formats mean that sinks supporting trace and span information can't provide a reliable out-of-the-box experience for trace and span correlation. This is akin to the situation with exceptions: having a standardized, top-level `Exception` field on all events means that Serilog sinks can all consistently and reliably record error information when it is present. [`System.Diagnostics.Activity`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.activity?view=net-7.0) standardizes trace propagation on recent .NET versions. Serilog can adopt the data model and propagation features of `Activity` to interop naturally with other .NET libraries and components. ## Strawman proposal First-class trace and span support would most likely mean adding `TraceId` and `SpanId` properties to the `LogEvent` class, along with a constructor overload accepting them. The trace and span ids would be captured using either the _System.Diagnostics_ types, or a compatible bytestring representation that can be used on all targeted platforms. The `Logger` functionality that constructs `LogEvents` would be updated to also collect trace and span details from `Activity.Current` when possible. Implementing first-class support would essentially entail "moving" trace and span information from regular properties to the dedicated fields. In the short term this might lead to perceived duplication where trace and span details are already collected, but this would resolve itself naturally over time. The various output formatting mechanisms would need to be updated to directly support the new trace and span properties, as would _Serilog.Expressions_ expression evaluation. ## See also * https://www.w3.org/TR/trace-context/ * https://github.com/serilog/serilog-sinks-opentelemetry/
Hey folks! I'm increasingly of the opinion that this will turn out to be important in Serilog's future; starting to look at spiking it out, but wondering whether anyone has any reservations/points against going in this direction? Will keep you posted here with updates :-) I find myself wondering if there's a significant benefit in having first-class support over a log enricher ```fsharp type LogEnricher() = interface ILogEventEnricher with member this.Enrich(logEvent, propertyFactory) = let prop k v = logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(k, v)) let act = System.Diagnostics.Activity.Current if act <> null then act.TraceId.ToString() |> prop "trace_id" act.SpanId.ToString() |> prop "span_id" ``` Thanks for sharing your thoughts @nordfjord. The challenge using enrichers is that sinks that need to consume trace and span ids can't rely on those properties coming through with consistent names or data types, so there isn't the "just works" usability I'd like. In many cases now, identifying a trace and span is as fundamental as identifying an exception or level, so it's really something of a historical artifact that Serilog has special support for those, but not for spans. Right, I see what you're saying. Would it make sense to align with the OpenTelemetry log data model in that case? https://opentelemetry.io/docs/specs/otel/logs/data-model/ 👍 that's one of the key inputs; the first consumer of this change would be https://github.com/serilog-sinks-opentelemetry, which goes to some significant lengths to work around the absence of first-class trace and span ids right now. There are some more aspects of the data model that play into how an OTLP sink might work (resource attrs etc) but not a lot of particularly important per-event data apart from these two key properties. (The proposal talks about `System.Diagnostics.Activity`, since this is the .NET API that ties into OpenTelemetry and whatever other diagnostic data collectors might be used.)
2023-09-19T01:19:41Z
0.1
['Serilog.Tests.Events.LogEventTests.CopiedLogEventsPropagateTraceAndSpan', 'Serilog.Tests.Core.LoggerTests.CurrentActivityIsCapturedAtLogEventCreation', 'Serilog.Tests.Formatting.Display.MessageTemplateTextFormatterTests.TraceAndSpanAreEmptyWhenAbsent', 'Serilog.Tests.Formatting.Display.MessageTemplateTextFormatterTests.TraceAndSpanAreIncludedWhenPresent', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.TraceAndSpanAreIgnoredWhenAbsent', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.TraceAndSpanAreIncludedWhenPresent']
[]
serilog/serilog
serilog__serilog-1927
7c395b66be91a772dccb5ad553d60bf8a116db33
diff --git a/src/Serilog/Formatting/Json/JsonFormatter.cs b/src/Serilog/Formatting/Json/JsonFormatter.cs index 3ea6b3836..fab5e95e7 100644 --- a/src/Serilog/Formatting/Json/JsonFormatter.cs +++ b/src/Serilog/Formatting/Json/JsonFormatter.cs @@ -66,7 +66,7 @@ public void Format(LogEvent logEvent, TextWriter output) if (_renderMessage) { - output.Write("\",\"RenderedMessage\":"); + output.Write(",\"RenderedMessage\":"); var message = logEvent.MessageTemplate.Render(logEvent.Properties); JsonValueFormatter.WriteQuotedJsonString(message, output); } diff --git a/src/Serilog/Serilog.csproj b/src/Serilog/Serilog.csproj index f64a96567..438832964 100644 --- a/src/Serilog/Serilog.csproj +++ b/src/Serilog/Serilog.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Description>Simple .NET logging with fully-structured events</Description> - <VersionPrefix>3.0.0</VersionPrefix> + <VersionPrefix>3.0.1</VersionPrefix> <Authors>Serilog Contributors</Authors> <TargetFrameworks Condition=" '$(OS)' == 'Windows_NT'">net462;net471</TargetFrameworks> <TargetFrameworks>$(TargetFrameworks);netstandard2.1;netstandard2.0;net5.0;net6.0;net7.0</TargetFrameworks>
diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index 39c76d285..006255a34 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -274,4 +274,20 @@ public void SequencesOfSequencesAreSerialized() var h = (string)d.Properties.AProperty[0][0]; Assert.Equal("Hello", h); } + + [Fact] // See https://github.com/serilog/serilog/issues/1924 + public void RenderedMessageIsIncludedCorrectlyWhenRequired() + { + var p = new MessageTemplateParser(); + var e = new LogEvent(Some.OffsetInstant(), Information, null, + p.Parse("value: {AProperty}"), new[] { new LogEventProperty("AProperty", new ScalarValue(12)) }); + + var formatter = new JsonFormatter(renderMessage: true); + + var buffer = new StringWriter(); + formatter.Format(e, buffer); + var json = buffer.ToString(); + + Assert.Contains(@",""MessageTemplate"":""value: {AProperty}"",""RenderedMessage"":""value: 12"",", json); + } }
JsonFormatter RenderedMessage writes invalid output **Description** When using JsonFormatter with renderMessage enabled to write console output, the JSON output is not created correctly and results in invalid JSON. **Reproduction** 1. Configure a default logger with a sinkConfiguration that uses the JsonFormatter with renderMessage = true 2. Log a message 3. The output results in invalid quoted JSON at the renderedMessage with an extra quote, for example: `{ "Timestamp": "2023-06-21T09:48:56.0952245+02:00", "Level": "Error", "MessageTemplate": "Testmessage with value: {TestMessageValue}"", "RenderedMessage": "Testmessage with value: 1", "Properties": { "TestMessageValue": "1" } }` **Expected behavior** Using Serilog 2.12.0 the output would result in valid JSON, we would expect the same behaviour in the latest version. **Relevant package, tooling and runtime versions** Serilog 3.0.0 **Additional context** Code where the extra quote is added can be found here: https://github.com/serilog/serilog/blob/main/src/Serilog/Formatting/Json/JsonFormatter.cs#L69
null
2023-06-21T21:22:56Z
0.1
['Serilog.Tests.Formatting.Json.JsonFormatterTests.SequencesOfSequencesAreSerialized', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.RenderedMessageIsIncludedCorrectlyWhenRequired']
['Serilog.Tests.Formatting.Json.JsonFormatterTests.ReadonlyDictionariesAreDestructuredViaDictionaryValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedEventsIncludeTimestamp', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ASequencePropertySerializesAsArrayValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ABooleanPropertySerializesAsBooleanValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ACharPropertySerializesAsStringValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedDateOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedTimeOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AStructureSerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADecimalSerializesAsNumericValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.DictionariesAreDestructuredViaDictionaryValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADictionaryWithScalarKeySerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AnIntegerPropertySerializesAsIntegerValue']
serilog/serilog
serilog__serilog-1926
2424cae597d19b12ea0b5e0b033a74810dc8bbbe
diff --git a/src/Serilog/Formatting/Json/JsonFormatter.cs b/src/Serilog/Formatting/Json/JsonFormatter.cs index 3ea6b3836..fab5e95e7 100644 --- a/src/Serilog/Formatting/Json/JsonFormatter.cs +++ b/src/Serilog/Formatting/Json/JsonFormatter.cs @@ -66,7 +66,7 @@ public void Format(LogEvent logEvent, TextWriter output) if (_renderMessage) { - output.Write("\",\"RenderedMessage\":"); + output.Write(",\"RenderedMessage\":"); var message = logEvent.MessageTemplate.Render(logEvent.Properties); JsonValueFormatter.WriteQuotedJsonString(message, output); }
diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index 39c76d285..006255a34 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -274,4 +274,20 @@ public void SequencesOfSequencesAreSerialized() var h = (string)d.Properties.AProperty[0][0]; Assert.Equal("Hello", h); } + + [Fact] // See https://github.com/serilog/serilog/issues/1924 + public void RenderedMessageIsIncludedCorrectlyWhenRequired() + { + var p = new MessageTemplateParser(); + var e = new LogEvent(Some.OffsetInstant(), Information, null, + p.Parse("value: {AProperty}"), new[] { new LogEventProperty("AProperty", new ScalarValue(12)) }); + + var formatter = new JsonFormatter(renderMessage: true); + + var buffer = new StringWriter(); + formatter.Format(e, buffer); + var json = buffer.ToString(); + + Assert.Contains(@",""MessageTemplate"":""value: {AProperty}"",""RenderedMessage"":""value: 12"",", json); + } }
JsonFormatter RenderedMessage writes invalid output **Description** When using JsonFormatter with renderMessage enabled to write console output, the JSON output is not created correctly and results in invalid JSON. **Reproduction** 1. Configure a default logger with a sinkConfiguration that uses the JsonFormatter with renderMessage = true 2. Log a message 3. The output results in invalid quoted JSON at the renderedMessage with an extra quote, for example: `{ "Timestamp": "2023-06-21T09:48:56.0952245+02:00", "Level": "Error", "MessageTemplate": "Testmessage with value: {TestMessageValue}"", "RenderedMessage": "Testmessage with value: 1", "Properties": { "TestMessageValue": "1" } }` **Expected behavior** Using Serilog 2.12.0 the output would result in valid JSON, we would expect the same behaviour in the latest version. **Relevant package, tooling and runtime versions** Serilog 3.0.0 **Additional context** Code where the extra quote is added can be found here: https://github.com/serilog/serilog/blob/main/src/Serilog/Formatting/Json/JsonFormatter.cs#L69
null
2023-06-21T21:08:21Z
0.1
['Serilog.Tests.Formatting.Json.JsonFormatterTests.RenderedMessageIsIncludedCorrectlyWhenRequired']
['Serilog.Tests.Formatting.Json.JsonFormatterTests.ReadonlyDictionariesAreDestructuredViaDictionaryValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedEventsIncludeTimestamp', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ASequencePropertySerializesAsArrayValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ABooleanPropertySerializesAsBooleanValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ACharPropertySerializesAsStringValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedDateOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedTimeOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AStructureSerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADecimalSerializesAsNumericValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.DictionariesAreDestructuredViaDictionaryValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADictionaryWithScalarKeySerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AnIntegerPropertySerializesAsIntegerValue']
serilog/serilog
serilog__serilog-1908
2994fabb55549d4a681f573c5a8196b6b15d882d
diff --git a/src/Serilog/Core/LoggingLevelSwitch.cs b/src/Serilog/Core/LoggingLevelSwitch.cs index 08c5db432..847bdc293 100644 --- a/src/Serilog/Core/LoggingLevelSwitch.cs +++ b/src/Serilog/Core/LoggingLevelSwitch.cs @@ -20,6 +20,7 @@ namespace Serilog.Core; public class LoggingLevelSwitch { volatile LogEventLevel _minimumLevel; + readonly object _levelUpdateLock = new(); /// <summary> /// Create a <see cref="LoggingLevelSwitch"/> at the initial @@ -31,6 +32,12 @@ public LoggingLevelSwitch(LogEventLevel initialMinimumLevel = LogEventLevel.Info _minimumLevel = initialMinimumLevel; } + /// <summary> + /// The event arises when <see cref="MinimumLevel"/> changed. Note that the event is raised + /// under a lock so be careful within event handler to not fall into deadlock. + /// </summary> + public event EventHandler<LoggingLevelSwitchChangedEventArgs>? MinimumLevelChanged; + /// <summary> /// The current minimum level, below which no events /// should be generated. @@ -40,6 +47,17 @@ public LoggingLevelSwitch(LogEventLevel initialMinimumLevel = LogEventLevel.Info public LogEventLevel MinimumLevel { get { return _minimumLevel; } - set { _minimumLevel = value; } + set + { + lock (_levelUpdateLock) + { + var old = _minimumLevel; + if (old != value) + { + _minimumLevel = value; + MinimumLevelChanged?.Invoke(this, new LoggingLevelSwitchChangedEventArgs(old, value)); + } + } + } } } diff --git a/src/Serilog/Core/LoggingLevelSwitchChangedEventArgs.cs b/src/Serilog/Core/LoggingLevelSwitchChangedEventArgs.cs new file mode 100644 index 000000000..b76a79de5 --- /dev/null +++ b/src/Serilog/Core/LoggingLevelSwitchChangedEventArgs.cs @@ -0,0 +1,42 @@ +// Copyright 2013-2015 Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Serilog.Core; + +/// <summary> +/// Event arguments for <see cref="LoggingLevelSwitch.MinimumLevelChanged"/> event. +/// </summary> +public class LoggingLevelSwitchChangedEventArgs : EventArgs +{ + /// <summary> + /// Creates an instance of <see cref="LoggingLevelSwitchChangedEventArgs"/> specifying old and new levels. + /// </summary> + /// <param name="oldLevel">Old level.</param> + /// <param name="newLevel">New level.</param> + public LoggingLevelSwitchChangedEventArgs(LogEventLevel oldLevel, LogEventLevel newLevel) + { + OldLevel = oldLevel; + NewLevel = newLevel; + } + + /// <summary> + /// Old level. + /// </summary> + public LogEventLevel OldLevel { get; } + + /// <summary> + /// New level. + /// </summary> + public LogEventLevel NewLevel { get; } +}
diff --git a/test/Serilog.ApprovalTests/Serilog.approved.txt b/test/Serilog.ApprovalTests/Serilog.approved.txt index ecb422542..fece82d1f 100644 --- a/test/Serilog.ApprovalTests/Serilog.approved.txt +++ b/test/Serilog.ApprovalTests/Serilog.approved.txt @@ -280,6 +280,13 @@ namespace Serilog.Core { public LoggingLevelSwitch(Serilog.Events.LogEventLevel initialMinimumLevel = 2) { } public Serilog.Events.LogEventLevel MinimumLevel { get; set; } + public event System.EventHandler<Serilog.Core.LoggingLevelSwitchChangedEventArgs>? MinimumLevelChanged; + } + public class LoggingLevelSwitchChangedEventArgs : System.EventArgs + { + public LoggingLevelSwitchChangedEventArgs(Serilog.Events.LogEventLevel oldLevel, Serilog.Events.LogEventLevel newLevel) { } + public Serilog.Events.LogEventLevel NewLevel { get; } + public Serilog.Events.LogEventLevel OldLevel { get; } } [System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method)] public sealed class MessageTemplateFormatMethodAttribute : System.Attribute diff --git a/test/Serilog.Tests/Core/LoggerTests.cs b/test/Serilog.Tests/Core/LoggerTests.cs index 90b19b2a3..799139766 100644 --- a/test/Serilog.Tests/Core/LoggerTests.cs +++ b/test/Serilog.Tests/Core/LoggerTests.cs @@ -137,7 +137,7 @@ public void TheNoneLoggerIsAConstant() [Fact] public void TheNoneLoggerIsSingleton() { - lock (new object()) + lock (this) { Log.CloseAndFlush(); Assert.Same(Log.Logger, Logger.None); diff --git a/test/Serilog.Tests/Core/LoggingLevekSwitchTests.cs b/test/Serilog.Tests/Core/LoggingLevekSwitchTests.cs new file mode 100644 index 000000000..0540fc378 --- /dev/null +++ b/test/Serilog.Tests/Core/LoggingLevekSwitchTests.cs @@ -0,0 +1,22 @@ +namespace Serilog.Tests.Core; + +public class LoggingLevekSwitchTests +{ + [Fact] + public void MinimumLevelChanged_Should_Work() + { + var sw = new LoggingLevelSwitch(); + bool changed = false; + sw.MinimumLevelChanged += (o, e) => + { + Assert.Equal(sw, o); + Assert.Equal(Information, e.OldLevel); + Assert.Equal(Fatal, e.NewLevel); + changed = true; + }; + Assert.Equal(Information, sw.MinimumLevel); + sw.MinimumLevel = Fatal; + Assert.Equal(Fatal, sw.MinimumLevel); + Assert.True(changed); + } +}
Allow developers to react to changes in the MinimumLevel of a LoggingLevelSwitch **Is your feature request related to a problem? Please describe.** There's currently no easy way of detecting when the `MinimumLevel` of a `LoggingLevelSwitch` changes, and the recommended workaround is monitoring its value on a timer, which works but is cumbersome. **Describe the solution you'd like** There has been requests to make the `MinimumLevel` virtual so it can be overridden, or change it to an interface for custom implementations, (e.g. #1436, #1417, #1232, and #682), and none of these were implemented because it would considerably affect performance of reads on the `MinimumLevel`. These requests seem to share the same end goal: Run custom code **when the `MinimumLevel` changes**. Given that _writes_ to `MinimumLevel` shouldn't happen nearly as often as _reads_, it seems that executing custom code immediately after the value of `MinimumLevel` is changed wouldn't be a big concern in terms of performance - unless I'm missing something (?). With that in mind, I'd like to propose the introduction of a couple of methods in the `LoggingLevelSwitch` class that allow developers to enable/disable running custom code when the `MinimumLevel` changes. It could be something along these lines: ```diff public class LoggingLevelSwitch { + Action<LogEventLevel> _notify; // ... (omitted for brevity) public LogEventLevel MinimumLevel { get { return _minimumLevel; } set { _minimumLevel = value; + var n = _notify; + n?.Invoke(value); } } + + public void EnableNotifications(Action<LogEventLevel> notify) + { + _notify = notify ?? throw new ArgumentNullException(nameof(notify)); + } + + public void DisableNotifications() + { + _notify = null; + } } ``` **Describe alternatives you've considered** Monitor instances of `LoggingLevelSwitch` on a timer or background thread. **Additional context** If executing custom code in the setter of `MinimumLevel` turns out not to be a bad idea, we could also consider: - Checking if the new value being assigned is different than the current value and only run the action if that's the case - Provide previous and actual `LogEventLevel` rather than only the actual - Allow more than one `Action` to be executed rather than a single one w/ last one wins I'd be happy to send a PR once a design is agreed.
That's an awesome idea! :+1: .... disappointed now that I didn't come up with it :sweat_smile: Scenario-wise, having support for multiple listeners, dynamically added, would make it easier for code to interact with a `LoggingLevelSwitch` that it doesn't "own". We could follow `ChangeToken`'s registration style, and do: ```csharp IDisposable OnChange(Action<LogEventLevel> listener); ``` where disposing the result would deregister the listener? Synchronization is interesting; a lock would need to cover both adding/removing listeners, and changing the level, so that listeners always "know" the correct level (interleavings of changing the level and adding listeners shouldn't result in listeners being stale/missing a change). For that to work, * Either `OnChange` would need to immediately call the callback with the current value, when added, or * We'd need an `ILevelChangeListener` with `OnRegistered(level)` and `OnChanged(level)` Last thought ... calling callbacks under a lock is good to avoid; we probably could, here, but not sure it's worth the substantial effort involved. "The callback will be invoked under a lock" might be worth noting in the XDOC for OnChange? Any reason not to make it a straight Event (or an Observable as you've all but suggested above). [Some notes on Observable vs Events](https://stackoverflow.com/questions/24572366/should-iobservable-be-preferred-over-events-when-exposing-notifications-in-a-lib) Need to give it some thought - probably no reason; events might be a bit simpler of those two. I think explicit callbacks are nice to work with in a lot of cases, and are used as much as the other two, but could just be me, there :-) I'd love to dig into possibilities here further, but I think it's stalled so I'll close it now as stale. Feel free to jump in if you're considering picking this back up :-)
2023-05-08T07:05:00Z
0.1
['Serilog.Tests.Core.LoggingLevekSwitchTests.MinimumLevelChanged_Should_Work']
[]
serilog/serilog
serilog__serilog-1906
2994fabb55549d4a681f573c5a8196b6b15d882d
diff --git a/src/Serilog/Capturing/PropertyValueConverter.cs b/src/Serilog/Capturing/PropertyValueConverter.cs index 6f5167283..3b62b5206 100644 --- a/src/Serilog/Capturing/PropertyValueConverter.cs +++ b/src/Serilog/Capturing/PropertyValueConverter.cs @@ -35,6 +35,7 @@ partial class PropertyValueConverter : ILogEventPropertyFactory, ILogEventProper }; readonly IDestructuringPolicy[] _destructuringPolicies; + readonly Type[] _dictionaryTypes; readonly IScalarConversionPolicy[] _scalarConversionPolicies; readonly DepthLimiter _depthLimiter; readonly int _maximumStringLength; @@ -46,6 +47,7 @@ public PropertyValueConverter( int maximumStringLength, int maximumCollectionCount, IEnumerable<Type> additionalScalarTypes, + IEnumerable<Type> additionalDictionaryTypes, IEnumerable<IDestructuringPolicy> additionalDestructuringPolicies, bool propagateExceptions) { @@ -77,6 +79,7 @@ public PropertyValueConverter( }) .ToArray(); + _dictionaryTypes = additionalDictionaryTypes.ToArray(); _depthLimiter = new(maximumDestructuringDepth, this); } @@ -344,17 +347,26 @@ string TruncateIfNecessary(string text) return text; } - static bool TryGetDictionary(object value, Type valueType, [NotNullWhen(true)] out IDictionary? dictionary) + bool TryGetDictionary(object value, Type valueType, [NotNullWhen(true)] out IDictionary? dictionary) { - if (value is IDictionary idictionary && valueType.IsConstructedGenericType) + if (value is IDictionary idictionary) { - var definition = valueType.GetGenericTypeDefinition(); - if ((definition == typeof(Dictionary<,>) || definition == typeof(System.Collections.ObjectModel.ReadOnlyDictionary<,>)) && - IsValidDictionaryKeyType(valueType.GenericTypeArguments[0])) + if (_dictionaryTypes.Contains(valueType)) { dictionary = idictionary; return true; } + + if (valueType.IsConstructedGenericType) + { + var definition = valueType.GetGenericTypeDefinition(); + if ((definition == typeof(Dictionary<,>) || definition == typeof(System.Collections.ObjectModel.ReadOnlyDictionary<,>)) && + IsValidDictionaryKeyType(valueType.GenericTypeArguments[0])) + { + dictionary = idictionary; + return true; + } + } } dictionary = null; diff --git a/src/Serilog/Configuration/LoggerDestructuringConfiguration.cs b/src/Serilog/Configuration/LoggerDestructuringConfiguration.cs index 29d936d8b..ca1b45cfd 100644 --- a/src/Serilog/Configuration/LoggerDestructuringConfiguration.cs +++ b/src/Serilog/Configuration/LoggerDestructuringConfiguration.cs @@ -21,6 +21,7 @@ public class LoggerDestructuringConfiguration { readonly LoggerConfiguration _loggerConfiguration; readonly Action<Type> _addScalar; + readonly Action<Type> _addDictionaryType; readonly Action<IDestructuringPolicy> _addPolicy; readonly Action<int> _setMaximumDepth; readonly Action<int> _setMaximumStringLength; @@ -29,6 +30,7 @@ public class LoggerDestructuringConfiguration internal LoggerDestructuringConfiguration( LoggerConfiguration loggerConfiguration, Action<Type> addScalar, + Action<Type> addDictionaryType, Action<IDestructuringPolicy> addPolicy, Action<int> setMaximumDepth, Action<int> setMaximumStringLength, @@ -36,6 +38,7 @@ internal LoggerDestructuringConfiguration( { _loggerConfiguration = Guard.AgainstNull(loggerConfiguration); _addScalar = Guard.AgainstNull(addScalar); + _addDictionaryType = Guard.AgainstNull(addDictionaryType); _addPolicy = Guard.AgainstNull(addPolicy); _setMaximumDepth = Guard.AgainstNull(setMaximumDepth); _setMaximumStringLength = Guard.AgainstNull(setMaximumStringLength); @@ -97,6 +100,19 @@ public LoggerConfiguration With<TDestructuringPolicy>() return With(new TDestructuringPolicy()); } + /// <summary> + /// Capture instances of the specified type as dictionaries. + /// By default, only concrete instantiations of are considered dictionary-like. + /// </summary> + /// <typeparam name="T">Type of dictionary.</typeparam> + /// <returns>Configuration object allowing method chaining.</returns> + public LoggerConfiguration AsDictionary<T>() + where T : IDictionary + { + _addDictionaryType(typeof(T)); + return _loggerConfiguration; + } + /// <summary> /// When destructuring objects, transform instances of the specified type with /// the provided function. diff --git a/src/Serilog/LoggerConfiguration.cs b/src/Serilog/LoggerConfiguration.cs index 7940cb27d..d6e7f1d15 100644 --- a/src/Serilog/LoggerConfiguration.cs +++ b/src/Serilog/LoggerConfiguration.cs @@ -24,6 +24,7 @@ public class LoggerConfiguration readonly List<ILogEventEnricher> _enrichers = new(); readonly List<ILogEventFilter> _filters = new(); readonly List<Type> _additionalScalarTypes = new(); + readonly HashSet<Type> _additionalDictionaryTypes = new(); readonly List<IDestructuringPolicy> _additionalDestructuringPolicies = new(); readonly Dictionary<string, LoggingLevelSwitch> _overrides = new(); LogEventLevel _minimumLevel = LogEventLevel.Information; @@ -102,6 +103,7 @@ public LoggerDestructuringConfiguration Destructure return new( this, _additionalScalarTypes.Add, + type => _additionalDictionaryTypes.Add(type), _additionalDestructuringPolicies.Add, depth => _maximumDestructuringDepth = depth, length => _maximumStringLength = length, @@ -152,6 +154,7 @@ public Logger CreateLogger() _maximumStringLength, _maximumCollectionCount, _additionalScalarTypes, + _additionalDictionaryTypes, _additionalDestructuringPolicies, auditing); var processor = new MessageTemplateProcessor(converter);
diff --git a/test/Serilog.ApprovalTests/Serilog.approved.txt b/test/Serilog.ApprovalTests/Serilog.approved.txt index ecb422542..c42f5f578 100644 --- a/test/Serilog.ApprovalTests/Serilog.approved.txt +++ b/test/Serilog.ApprovalTests/Serilog.approved.txt @@ -14,6 +14,8 @@ namespace Serilog.Configuration } public class LoggerDestructuringConfiguration { + public Serilog.LoggerConfiguration AsDictionary<T>() + where T : System.Collections.IDictionary { } public Serilog.LoggerConfiguration AsScalar(System.Type scalarType) { } public Serilog.LoggerConfiguration AsScalar<TScalar>() { } public Serilog.LoggerConfiguration ByTransforming<TValue>(System.Func<TValue, object> transformation) { } diff --git a/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs b/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs index 0224ae3db..939c7f9ab 100644 --- a/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs +++ b/test/Serilog.Tests/Capturing/PropertyValueConverterTests.cs @@ -6,12 +6,12 @@ namespace Serilog.Tests.Capturing; public class PropertyValueConverterTests { readonly PropertyValueConverter _converter = - new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); + new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); [Fact] public async Task MaximumDepthIsEffectiveAndThreadSafe() { - var converter = new PropertyValueConverter(3, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); + var converter = new PropertyValueConverter(3, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); var barrier = new Barrier(participantCount: 3); diff --git a/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs b/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs index 4051ac018..43a67e4ac 100644 --- a/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs +++ b/test/Serilog.Tests/Core/LogEventPropertyCapturingTests.cs @@ -167,7 +167,7 @@ static IEnumerable<LogEventProperty> Capture(string messageTemplate, params obje { var mt = new MessageTemplateParser().Parse(messageTemplate); var binder = new PropertyBinder( - new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false)); + new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false)); return binder.ConstructProperties(mt, properties).Select(p => new LogEventProperty(p.Name, p.Value)); } } diff --git a/test/Serilog.Tests/Core/MessageTemplateTests.cs b/test/Serilog.Tests/Core/MessageTemplateTests.cs index 3dc11d659..148a4536a 100755 --- a/test/Serilog.Tests/Core/MessageTemplateTests.cs +++ b/test/Serilog.Tests/Core/MessageTemplateTests.cs @@ -134,7 +134,7 @@ static string Render(string messageTemplate, params object[] properties) static string Render(IFormatProvider? formatProvider, string messageTemplate, params object[] properties) { var mt = new MessageTemplateParser().Parse(messageTemplate); - var binder = new PropertyBinder(new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false)); + var binder = new PropertyBinder(new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false)); var props = binder.ConstructProperties(mt, properties); var output = new StringBuilder(); var writer = new StringWriter(output); diff --git a/test/Serilog.Tests/Events/LogEventPropertyValueTests.cs b/test/Serilog.Tests/Events/LogEventPropertyValueTests.cs index decbf0b63..3f407b13d 100644 --- a/test/Serilog.Tests/Events/LogEventPropertyValueTests.cs +++ b/test/Serilog.Tests/Events/LogEventPropertyValueTests.cs @@ -17,7 +17,7 @@ namespace Serilog.Tests.Events; public class LogEventPropertyValueTests { readonly PropertyValueConverter _converter = - new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); + new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); [Fact] public void AnEnumIsConvertedToANonStringScalarValue() diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index ec3b820a0..9d8d0ed7d 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -205,6 +205,23 @@ public void ReadonlyDictionariesAreDestructuredViaDictionaryValue() Assert.Equal(1.2, (double)f.Properties.ADictionary.nums[0]); } + private class MyDictionary : Dictionary<string, object> { } + + [Fact] + public void CustomDictionariesAreDestructuredViaDictionaryValue_When_AsDictionary_Applied() + { + var dict = new MyDictionary { + { "hello", "world" }, + { "nums", new[] { 1.2 } } + }; + + var e = DelegatingSink.GetLogEvent(l => l.Information("Value is {ADictionary}", dict), cfg => cfg.Destructure.AsDictionary<MyDictionary>()); + var f = FormatJson(e); + + Assert.Equal("world", (string)f.Properties.ADictionary["hello"]); + Assert.Equal(1.2, (double)f.Properties.ADictionary.nums[0]); + } + [Fact] public void PropertyTokensWithFormatStringsAreIncludedAsRenderings() { diff --git a/test/Serilog.Tests/Support/DelegatingSink.cs b/test/Serilog.Tests/Support/DelegatingSink.cs index 19013adfc..89cff9de2 100644 --- a/test/Serilog.Tests/Support/DelegatingSink.cs +++ b/test/Serilog.Tests/Support/DelegatingSink.cs @@ -14,13 +14,17 @@ public void Emit(LogEvent logEvent) _write(logEvent); } - public static LogEvent GetLogEvent(Action<ILogger> writeAction) + public static LogEvent GetLogEvent(Action<ILogger> writeAction, Func<LoggerConfiguration, LoggerConfiguration>? configure = null) { LogEvent? result = null; - var l = new LoggerConfiguration() + var configuration = new LoggerConfiguration() .MinimumLevel.Verbose() - .WriteTo.Sink(new DelegatingSink(le => result = le)) - .CreateLogger(); + .WriteTo.Sink(new DelegatingSink(le => result = le)); + + if (configure != null) + configuration = configure(configuration); + + var l = configuration.CreateLogger(); writeAction(l); Assert.NotNull(result);
Destructure.AsDictionary<T>() to override default dictionaries-are-enumerables behavior ### Description Instances of `Dictionary<string, T>` are destructured as objects, this is also [documented](https://github.com/serilog/serilog/wiki/Structured-Data#collections). But it's inheritors does not behave the same. I understand that class can implement multiple `IDictionary<string, T>` so such interfaces are not handled as objects. But class can not inherit from multiple `Dictionary<string, T>` so I don't think this limitation applies here. ### Reproduction This works: ```csharp Serilog.Log.Logger.Information("{@Instance}", new Dictionary<string, string> { {"TestKey", "TestValue"} }); ``` populating **Instance** property as `{TestKey: 'TestValue'}` But this doesn't: ```csharp public class MyDictionary: Dictionary<string, string> {} Serilog.Log.Logger.Information("{@Instance}", new MyDictionary { {"TestKey", "TestValue"} }); ``` and populates **Instance** with `[{Key: 'TestKey', Value: 'TestValue'}]` ### Relevant package, tooling and runtime versions Serilog 2.10.0, .NET 5.0, Windows 10
Thanks for the note - this is by design, subclassing/inheritance isn't taken into account by destructuring rules. There are some APIs for getting around this, but `Destructure.AsDictionary<MyDictionary>()` also might be worth considering as an addition. @nblumhardt thanks for the reply. I don't understand the reasoning for not considering subclasses, but agree that `Destructure.AsDictionary<MyDictionary>()` would solve this issue. Would you propose to close it or update to track suggested new method? ``` var fruit = new Dictionary<string, int> { { "Apple", 1 }, { "Pear", 5 } }; Log.ForContext("Test my fruit", fruit , destructureObjects: true) .Information("example"); ``` `Destructure.AsDictionary<T>` sounds like a reasonable addition; let's keep this open to track :+1: Hi folks. If you're set on `Destructure.AsDictionary<T>` as a solution, I would like to take a stab at an implementation. Sounds good to me! :+1: Thanks @octos4murai. @nblumhardt, what are your thoughts on the following possible implementations: ### A ```csharp public LoggerConfiguration AsDictionary<T, TKey, TValue>() where T : IDictionary<TKey, TValue> => ByTransforming<T>(customDict => customDict.ToDictionary(customDict => customDict.Key, cd => cd.Value)); ``` - Simple and clean implementation - Requires the user to specify the key and value types when using `AsDictionary()` - Sample Usage: `Destructure.AsDictionary<MyDictionary<string, int>, string, int>()` ### B ```csharp public LoggerConfiguration AsDictionary<T>() where T : IDictionary => ByTransforming<T>(customDict => { Type[] argTypes = customDict.GetType().GetGenericArguments(); Type keyType = argTypes[0]; Type valType = argTypes[1]; // Create a standard Dictionary with the same key and value types as T dynamic dict = Activator.CreateInstance(typeof(Dictionary<, >).MakeGenericType(keyType, valType)); foreach (var key in customDict.Keys) { dict.Add( (dynamic)Convert.ChangeType(key, keyType), (dynamic)Convert.ChangeType(customDict[key], valType) ); } return dict; }); ``` - Use of dynamic type may increase chances of runtime errors - Able to glean the key and value type from the Dictionary when using `AsDictionary()` - Sample Usage: `Destructure.AsDictionary<MyDictionary<string, int>>()` Hi! Both of these options would require additional allocations and copying; instead, we can create an `IDestructuringPolicy` that detects instances of the type and converts them directly into `DictionaryValue` (no intermediate `Dictionary` step.) Let me know if this makes sense - should be some example `IDestructuringPolicy` impls out there/already in the codebase. It'd be cool to see this one move forward, but at present it seems to have stagnated so I'll close the ticket as stale. Please chime in if you're interested in picking it back up at any point, or if anyone following along wants to take a shot at it :-)
2023-05-07T07:57:20Z
0.1
['Serilog.Tests.Formatting.Json.JsonFormatterTests.CustomDictionariesAreDestructuredViaDictionaryValue_When_AsDictionary_Applied']
[]
serilog/serilog
serilog__serilog-1903
33de1c86d93e655298e6863f7720f5b6afc49833
diff --git a/src/Serilog/Capturing/PropertyBinder.cs b/src/Serilog/Capturing/PropertyBinder.cs index da6a0cbd6..1799a40bb 100644 --- a/src/Serilog/Capturing/PropertyBinder.cs +++ b/src/Serilog/Capturing/PropertyBinder.cs @@ -52,9 +52,6 @@ public EventProperty[] ConstructProperties(MessageTemplate messageTemplate, obje EventProperty[] ConstructPositionalProperties(MessageTemplate template, object?[] messageTemplateParameters, PropertyToken[] positionalProperties) { - if (positionalProperties.Length != messageTemplateParameters.Length) - SelfLog.WriteLine("Positional property count does not match parameter count: {0}", template); - var result = new EventProperty[messageTemplateParameters.Length]; foreach (var property in positionalProperties) { @@ -77,6 +74,9 @@ EventProperty[] ConstructPositionalProperties(MessageTemplate template, object?[ } } + if (result.Length != messageTemplateParameters.Length) + SelfLog.WriteLine("Positional property count does not match parameter count: {0}", template); + if (next != result.Length) Array.Resize(ref result, next);
diff --git a/test/Serilog.Tests/Capturing/GetablePropertyFinderTests.cs b/test/Serilog.Tests/Capturing/GettablePropertyFinderTests.cs similarity index 98% rename from test/Serilog.Tests/Capturing/GetablePropertyFinderTests.cs rename to test/Serilog.Tests/Capturing/GettablePropertyFinderTests.cs index 8ec43d58b..38a3a09df 100644 --- a/test/Serilog.Tests/Capturing/GetablePropertyFinderTests.cs +++ b/test/Serilog.Tests/Capturing/GettablePropertyFinderTests.cs @@ -1,6 +1,6 @@ namespace Serilog.Tests.Capturing; -public class GetablePropertyFinderTests +public class GettablePropertyFinderTests { [Fact] public void GetPropertiesRecursiveIntegerTypeYieldNoResult() diff --git a/test/Serilog.Tests/Debugging/SelfLogTests.cs b/test/Serilog.Tests/Debugging/SelfLogTests.cs index 05c3af5fc..5c6efbf0b 100644 --- a/test/Serilog.Tests/Debugging/SelfLogTests.cs +++ b/test/Serilog.Tests/Debugging/SelfLogTests.cs @@ -25,6 +25,47 @@ public void MessagesAreWrittenWhenOutputIsSet() Assert.Equal(Messages.Count, count); } + [Fact] + public void SelfLogReportsErrorWhenPositionalParameterCountIsMismatched() + { + Messages = new(); + SelfLog.Enable(m => + { + Messages.Add(m); + }); + + using var logger = new LoggerConfiguration() + .WriteTo.Logger(new SilentLogger()) + .CreateLogger(); + + // ReSharper disable once StructuredMessageTemplateProblem + logger.Information("{0}{1}", "hello"); + + SelfLog.Disable(); + + Assert.Single(Messages); + } + + [Fact] + public void SelfLogDoesNotReportErrorWhenPositionalParameterIsRepeated() + { + Messages = new(); + SelfLog.Enable(m => + { + Messages.Add(m); + }); + + using var logger = new LoggerConfiguration() + .WriteTo.Logger(new SilentLogger()) + .CreateLogger(); + + logger.Information("{0}{0}", "hello"); + + SelfLog.Disable(); + + Assert.Empty(Messages); + } + [Fact] public void WritingToUndeclaredSinkWritesToSelfLog() {
Repeated placeholders within a message template cause selfLog to incorrectly log a message **Description** When passing a placeholder into a message template more than once, it updates a sink correctly but selfLog writes the line 'Positional property count does not match parameter count'. **Reproduction** Log.Information("{0}, {0}", "hello"); PropertyBinder.ConstructPositionalProperties() (line 62) compares the number of placeholders to the number of values provided to populate them. In this case there is a repeated placeholder so it's comparing 2 and 1, resulting in the update to selfLog. **Expected behavior** Compare number of unique placeholders with provided values. **Relevant package, tooling and runtime versions** v2.9.0 (netCore 3.0) **Additional context** Repeated placeholders within a message template cause selfLog to incorrectly log a message **Description** When passing a placeholder into a message template more than once, it updates a sink correctly but selfLog writes the line 'Positional property count does not match parameter count'. **Reproduction** Log.Information("{0}, {0}", "hello"); PropertyBinder.ConstructPositionalProperties() (line 62) compares the number of placeholders to the number of values provided to populate them. In this case there is a repeated placeholder so it's comparing 2 and 1, resulting in the update to selfLog. **Expected behavior** Compare number of unique placeholders with provided values. **Relevant package, tooling and runtime versions** v2.9.0 (netCore 3.0) **Additional context**
Thanks for the note 👍 I think the check here is deliberately simplistic for performance reasons, but if we do the more expensive check only when the parameter count differs, we could at least reduce the false-positive rate, and hopefully won't incur any additional overhead in the hot path. If anyone's interested in taking a look, we'd need some benchmarks along with this fix. Hi, @57r480 @nblumhardt. I have checked the function `ConstructPositionalProperties` in `PropertyBinder`, and it seems that there is a simple way to solve this situation. In this function, the variable `result` records the relations between the placeholders and the log objects, which are not repeated. Therefore, the comparison can be modified to the length of `result` and the length of log objects, and placed after the construction of `result` (Line 89). The advantage of this solution is that there is no need to add additional logic, so it has little impact on performance. The disadvantage is that it may change the outputs of `SelfLog` in some cases, for example. ```csharp log.Information("{0}{1}", "hello"); ``` Serilog (v2.9.0) firstly outputs "Positional property count does not match parameter count" then outputs "Unassigned positional value...", while this solution outputs "Unassigned positional value...". Since it has a breaking change, I don't know whether it is acceptable. Hi, @nblumhardt Did I miss something? Hi! Sorry, @iskcal - I haven't had a chance to dig in deeply yet. So, logging like ```cs Log.Warning("Processing failed for {Mode}. Check if {Mode} is enabled in 'there'", mode); Log.Warning("Processing failed for {Mode}. Check if {0} is enabled in 'there'", mode); ``` will not be possible right now due to performance reasons? Or is it a different issue? @STeeL835 both are invalid templates (see https://messagetemplates.org), so this is a different issue (the template being discussed in this thread is valid but not properly processed). Thanks for the note 👍 I think the check here is deliberately simplistic for performance reasons, but if we do the more expensive check only when the parameter count differs, we could at least reduce the false-positive rate, and hopefully won't incur any additional overhead in the hot path. If anyone's interested in taking a look, we'd need some benchmarks along with this fix. Hi, @57r480 @nblumhardt. I have checked the function `ConstructPositionalProperties` in `PropertyBinder`, and it seems that there is a simple way to solve this situation. In this function, the variable `result` records the relations between the placeholders and the log objects, which are not repeated. Therefore, the comparison can be modified to the length of `result` and the length of log objects, and placed after the construction of `result` (Line 89). The advantage of this solution is that there is no need to add additional logic, so it has little impact on performance. The disadvantage is that it may change the outputs of `SelfLog` in some cases, for example. ```csharp log.Information("{0}{1}", "hello"); ``` Serilog (v2.9.0) firstly outputs "Positional property count does not match parameter count" then outputs "Unassigned positional value...", while this solution outputs "Unassigned positional value...". Since it has a breaking change, I don't know whether it is acceptable. Hi, @nblumhardt Did I miss something? Hi! Sorry, @iskcal - I haven't had a chance to dig in deeply yet. So, logging like ```cs Log.Warning("Processing failed for {Mode}. Check if {Mode} is enabled in 'there'", mode); Log.Warning("Processing failed for {Mode}. Check if {0} is enabled in 'there'", mode); ``` will not be possible right now due to performance reasons? Or is it a different issue? @STeeL835 both are invalid templates (see https://messagetemplates.org), so this is a different issue (the template being discussed in this thread is valid but not properly processed).
2023-05-03T01:32:09Z
0.1
['Serilog.Tests.Debugging.SelfLogTests.SelfLogReportsErrorWhenPositionalParameterCountIsMismatched', 'Serilog.Tests.Capturing.GettablePropertyFinderTests.GetPropertiesRecursiveIntegerTypeYieldNoResult', 'Serilog.Tests.Debugging.SelfLogTests.SelfLogDoesNotReportErrorWhenPositionalParameterIsRepeated']
[]
serilog/serilog
serilog__serilog-1897
883e20895c83a3a3a1eeac9356d9056c06371bf5
diff --git a/src/Serilog/Capturing/PropertyValueConverter.cs b/src/Serilog/Capturing/PropertyValueConverter.cs index 52afdd36c..b1024c434 100644 --- a/src/Serilog/Capturing/PropertyValueConverter.cs +++ b/src/Serilog/Capturing/PropertyValueConverter.cs @@ -346,12 +346,15 @@ string TruncateIfNecessary(string text) static bool TryGetDictionary(object value, Type valueType, [NotNullWhen(true)] out IDictionary? dictionary) { - if (valueType.IsConstructedGenericType && - valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && - IsValidDictionaryKeyType(valueType.GenericTypeArguments[0])) + if (value is IDictionary && valueType.IsConstructedGenericType) { - dictionary = (IDictionary)value; - return true; + var definition = valueType.GetGenericTypeDefinition(); + if ((definition == typeof(Dictionary<,>) || definition == typeof(System.Collections.ObjectModel.ReadOnlyDictionary<,>)) && + IsValidDictionaryKeyType(valueType.GenericTypeArguments[0])) + { + dictionary = (IDictionary)value; + return true; + } } dictionary = null;
diff --git a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs index 5138276b1..2584bf84a 100644 --- a/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs +++ b/test/Serilog.Tests/Formatting/Json/JsonFormatterTests.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using System.Collections.ObjectModel; namespace Serilog.Tests.Formatting.Json; @@ -188,6 +189,22 @@ public void DictionariesAreDestructuredViaDictionaryValue() Assert.Equal(1.2, (double)f.Properties.ADictionary.nums[0]); } + [Fact] + public void ReadonlyDictionariesAreDestructuredViaDictionaryValue() + { + var dict = new ReadOnlyDictionary<string, object>(new Dictionary<string, object> + { + { "hello", "world" }, + { "nums", new[] { 1.2 } } + }); + + var e = DelegatingSink.GetLogEvent(l => l.Information("Value is {ADictionary}", dict)); + var f = FormatJson(e); + + Assert.Equal("world", (string)f.Properties.ADictionary["hello"]); + Assert.Equal(1.2, (double)f.Properties.ADictionary.nums[0]); + } + [Fact] public void PropertyTokensWithFormatStringsAreIncludedAsRenderings() {
Destructure `IReadOnlyDictionary<...>` the same way as `IDictionary<...>` **Is your feature request related to a problem? Please describe.** `IReadOnlyDictionary` is destructured as a collection of `KeyValuePair`, which, at least from my point of view, is unwanted. **Describe the solution you'd like** `IReadOnlyDictionary` is destructured the same way as `IDictionary`, meaning `{ "Key1Name": "Value1", "Key2Name": "Value2" }` **Describe alternatives you've considered** No alternatives. **Additional context** ``` using var logger = new LoggerConfiguration().WriteTo.Console().CreateLogger(); var dictionary = new Dictionary<string, object> { ["Text" ] = "alpha", ["Number"] = 3.14, ["Object"] = new { Child = "new" }, }; logger.Information("Dictionary: {@Dictionary}", dictionary); // Would be nice to have the same results also for this: logger.Information("IReadonlyDictionary: {@IReadonlyDictionary}", dictionary.AsReadOnly()); ``` Results in: ``` Dictionary: {"Text": "alpha", "Number": 3.14, "Object": {"Child": "new"}} IReadonlyDictionary: [{"Key": "Text", "Value": "alpha", "$type": "KeyValuePair`2"}, {"Key": "Number", "Value": 3.14, "$type": "KeyValuePair`2"}, {"Key": "Object", "Value": {"Child": "new"}, "$type": "KeyValuePair`2"}] ```
Hi @pavel-faltynek - thanks for the note. The destructuring mechanism works on implementation type, not through interfaces, so this is deliberate though tricky. Does the `AsReadOnly()` method have a well-known concrete implementation type?
2023-04-29T05:43:26Z
0.1
['Serilog.Tests.Formatting.Json.JsonFormatterTests.ReadonlyDictionariesAreDestructuredViaDictionaryValue']
['Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedEventsIncludeTimestamp', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ASequencePropertySerializesAsArrayValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ABooleanPropertySerializesAsBooleanValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ACharPropertySerializesAsStringValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedDateOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.JsonFormattedTimeOnly', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AStructureSerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.PropertyTokensWithFormatStringsAreIncludedAsRenderings', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.SequencesOfSequencesAreSerialized', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADecimalSerializesAsNumericValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.DictionariesAreDestructuredViaDictionaryValue', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.PropertyTokensWithoutFormatStringsAreNotIncludedAsRenderings', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.ADictionaryWithScalarKeySerializesAsAnObject', 'Serilog.Tests.Formatting.Json.JsonFormatterTests.AnIntegerPropertySerializesAsIntegerValue']
serilog/serilog
serilog__serilog-1890
883e20895c83a3a3a1eeac9356d9056c06371bf5
diff --git a/src/Serilog/Configuration/LoggerSinkConfiguration.cs b/src/Serilog/Configuration/LoggerSinkConfiguration.cs index ff6a71852..a1d043d60 100644 --- a/src/Serilog/Configuration/LoggerSinkConfiguration.cs +++ b/src/Serilog/Configuration/LoggerSinkConfiguration.cs @@ -142,8 +142,28 @@ public LoggerConfiguration Logger( /// events passed through the sink.</param> /// <returns>Configuration object allowing method chaining.</returns> /// <exception cref="ArgumentNullException">When <paramref name="logger"/> is <code>null</code></exception> + [EditorBrowsable(EditorBrowsableState.Never)] + public LoggerConfiguration Logger( + ILogger logger, + LogEventLevel restrictedToMinimumLevel) + => Logger(logger, attemptDispose: false, restrictedToMinimumLevel); + + /// <summary> + /// Write log events to a sub-logger, where further processing may occur. Events through + /// the sub-logger will be constrained by filters and enriched by enrichers that are + /// active in the parent. A sub-logger cannot be used to log at a more verbose level, but + /// a less verbose level is possible. + /// </summary> + /// <param name="logger">The sub-logger.</param> + /// <param name="attemptDispose">Whether to shut down automatically the sub-logger + /// when the parent logger is disposed.</param> + /// <param name="restrictedToMinimumLevel">The minimum level for + /// events passed through the sink.</param> + /// <returns>Configuration object allowing method chaining.</returns> + /// <exception cref="ArgumentNullException">When <paramref name="logger"/> is <code>null</code></exception> public LoggerConfiguration Logger( ILogger logger, + bool attemptDispose = false, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) { Guard.AgainstNull(logger); @@ -154,7 +174,7 @@ public LoggerConfiguration Logger( "and may be removed completely in a future version."); } - var secondarySink = new SecondaryLoggerSink(logger, attemptDispose: false); + var secondarySink = new SecondaryLoggerSink(logger, attemptDispose: attemptDispose); return Sink(secondarySink, restrictedToMinimumLevel); }
diff --git a/test/Serilog.ApprovalTests/Serilog.approved.txt b/test/Serilog.ApprovalTests/Serilog.approved.txt index 088733f46..7910898ec 100644 --- a/test/Serilog.ApprovalTests/Serilog.approved.txt +++ b/test/Serilog.ApprovalTests/Serilog.approved.txt @@ -68,7 +68,8 @@ namespace Serilog.Configuration public class LoggerSinkConfiguration { public Serilog.LoggerConfiguration Conditional(System.Func<Serilog.Events.LogEvent, bool> condition, System.Action<Serilog.Configuration.LoggerSinkConfiguration> configureSink) { } - public Serilog.LoggerConfiguration Logger(Serilog.ILogger logger, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0) { } + public Serilog.LoggerConfiguration Logger(Serilog.ILogger logger, Serilog.Events.LogEventLevel restrictedToMinimumLevel) { } + public Serilog.LoggerConfiguration Logger(Serilog.ILogger logger, bool attemptDispose = false, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0) { } public Serilog.LoggerConfiguration Logger(System.Action<Serilog.LoggerConfiguration> configureLogger, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } public Serilog.LoggerConfiguration Sink(Serilog.Core.ILogEventSink logEventSink, Serilog.Events.LogEventLevel restrictedToMinimumLevel) { } public Serilog.LoggerConfiguration Sink(Serilog.Core.ILogEventSink logEventSink, Serilog.Events.LogEventLevel restrictedToMinimumLevel = 0, Serilog.Core.LoggingLevelSwitch? levelSwitch = null) { } diff --git a/test/Serilog.Tests/Core/ChildLoggerDisposalTests.cs b/test/Serilog.Tests/Core/ChildLoggerDisposalTests.cs new file mode 100644 index 000000000..0d557e7c9 --- /dev/null +++ b/test/Serilog.Tests/Core/ChildLoggerDisposalTests.cs @@ -0,0 +1,76 @@ +namespace Serilog.Tests.Core; + +public class ChildLoggerDisposalTests +{ + [Fact] + public void ByDefaultChildLoggerIsNotDisposedOnOuterDisposal() + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child) + .CreateLogger(); + outer.Dispose(); + Assert.False(child.IsDisposed); + } + + [Fact] + public void ViaLegacyOverloadChildLoggerIsNotDisposedOnOuterDisposal() + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child, Information) + .CreateLogger(); + outer.Dispose(); + Assert.False(child.IsDisposed); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void WhenExplicitlyConfiguredChildLoggerShouldBeDisposedAccordingToConfiguration(bool attemptDispose) + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child, attemptDispose) + .CreateLogger(); + outer.Dispose(); + Assert.Equal(attemptDispose, child.IsDisposed); + } + +#if FEATURE_ASYNCDISPOSABLE + [Fact] + public async Task ByDefaultChildLoggerIsNotAsyncDisposedOnOuterDisposal() + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child) + .CreateLogger(); + await outer.DisposeAsync(); + Assert.False(child.IsDisposedAsync); + } + + [Fact] + public async Task ViaLegacyOverloadChildLoggerIsNotAsyncDisposedOnOuterDisposal() + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child, Information) + .CreateLogger(); + await outer.DisposeAsync(); + Assert.False(child.IsDisposedAsync); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task WhenExplicitlyConfiguredChildLoggerShouldBeAsyncDisposedAccordingToConfiguration(bool attemptDispose) + { + var child = new DisposableLogger(); + var outer = new LoggerConfiguration() + .WriteTo.Logger(child, attemptDispose) + .CreateLogger(); + await outer.DisposeAsync(); + Assert.Equal(attemptDispose, child.IsDisposedAsync); + } +#endif +}
An ability to dispose nested loggers **Is your feature request related to a problem? Please describe.** I have a quite complex logging pipeline having at least two levels of nesting via `configuration.WriteTo.Logger(nestedLogger)`. The problem is, I can't dispose all of it in one go, because nested loggers are _not_ disposed when parent logger is. **Describe the solution you'd like** I would like to be able to specify that I want nested logger to be disposed with the pipeline, i.e.: ``` configuration.WriteTo.Logger(nestedLogger, dispose: true) ``` This can be easily accomplished by passing the flag down to `SecondaryLoggerSink`. **Describe alternatives you've considered** - `WriteTo.Logger(Action<LoggerConfiguration>)` which creates logger internally and disposes of it. I was able to replace only on of my usages with this one, because in other cases the logger is already created. - `WriteTo.Sink(logger)` (using the fact that `Serilog.Core.Logger` is actually a `ILogEventSink`). This way the events pushed to logger are not copied so they can (and will be, in my case) modified by nested logger's enrichment. Also, feels hack-ish and requires access to `Logger` instead of `ILogger`. - `WriteTo.Logger(lc => lc.WriteTo.Sink(logger))`. This, probably, will work (and I might settle for this in a short-term), but, same as above, requires access to `Logger` and feels even more hack-ish. BTW, I'd add a simple overload in my own code, but both `SecondaryLoggerSink` and `LogEvent.Copy` are `internal`.
I think I can take this one myself, but I'd like to get an approval for the approach beforehand. Thanks for the suggestion, will need to loop back around and give it some thought :+1: I think the approach is sound; if anyone's interested in picking this up please jump in, otherwise given the lack of activity this should probably be closed as stale now. I'll give it a try around the week end.
2023-04-08T14:19:28Z
0.1
['Serilog.Tests.Core.ChildLoggerDisposalTests.ByDefaultChildLoggerIsNotDisposedOnOuterDisposal', 'Serilog.Tests.Core.ChildLoggerDisposalTests.ViaLegacyOverloadChildLoggerIsNotDisposedOnOuterDisposal', 'Serilog.Tests.Core.ChildLoggerDisposalTests.WhenExplicitlyConfiguredChildLoggerShouldBeDisposedAccordingToConfiguration', 'Serilog.Tests.Core.ChildLoggerDisposalTests.ByDefaultChildLoggerIsNotAsyncDisposedOnOuterDisposal', 'Serilog.Tests.Core.ChildLoggerDisposalTests.ViaLegacyOverloadChildLoggerIsNotAsyncDisposedOnOuterDisposal', 'Serilog.Tests.Core.ChildLoggerDisposalTests.WhenExplicitlyConfiguredChildLoggerShouldBeAsyncDisposedAccordingToConfiguration']
[]
dotnet/efcore
dotnet__efcore-27428
9d513828ea6d57fd7f9fa3cedeca131f79ae6989
diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs index e4dd55a2566..9f78f7f7162 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Threading; namespace Microsoft.Data.Sqlite @@ -157,17 +158,17 @@ private bool ReclaimLeakedConnections() { var leakedConnectionsFound = false; + List<SqliteConnectionInternal> leakedConnections; lock (_connections) { - foreach (var connection in _connections) - { - if (connection.Leaked) - { - Return(connection); + leakedConnections = _connections.Where(c => c.Leaked).ToList(); + } - leakedConnectionsFound = true; - } - } + foreach (var connection in leakedConnections) + { + leakedConnectionsFound = true; + + Return(connection); } return leakedConnectionsFound;
diff --git a/test/Microsoft.Data.Sqlite.Tests/SqliteConnectionFactoryTest.cs b/test/Microsoft.Data.Sqlite.Tests/SqliteConnectionFactoryTest.cs index 764f5766b23..ddb65e0edab 100644 --- a/test/Microsoft.Data.Sqlite.Tests/SqliteConnectionFactoryTest.cs +++ b/test/Microsoft.Data.Sqlite.Tests/SqliteConnectionFactoryTest.cs @@ -4,6 +4,7 @@ using System; using System.Data; using System.IO; +using System.Runtime.CompilerServices; using SQLitePCL; using Xunit; @@ -218,6 +219,26 @@ public void EnableExtensions_doesnt_bleed_across_connections() Assert.Equal(disabledMessage, ex.Message); } + [Fact] + public void Clear_works_when_connection_leaked() + { + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + LeakConnection(); + GC.Collect(); + + SqliteConnection.ClearPool(connection); + + [MethodImpl(MethodImplOptions.NoInlining)] + static void LeakConnection() + { + // Don't add using! + var connection = new SqliteConnection(ConnectionString); + connection.Open(); + } + } + public void Dispose() { SqliteConnection.ClearAllPools();
Exception from SQLite provider when application is shutting down I hope I'm posting this in the right location. I have been running this problem down for several days now and I'm not sure what is going on. I've checked all my various libraries and 3rd party packages to see if there might be an issue there. The problem is that the issue is happening when my code is no longer running. In a nutshell, my issue is happening here: ``` using System; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeatherWire_Personal { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new WWMonitor()); } **//- <------ Exception is thrown HERE** } } ``` It's at the point above that a "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute." exception is thrown. No tasks show in the debugger. I'm not sure what collection it is talking about since no collections in my code are being iterated at this point. So...I disable "Enable Just My Code" in the debugger options, then set a breakpoint for that curly bracket. I kick off a debugging session again, then close down the application. When I hit the breakpoint there are no "Tasks" and no "Locals" shown. With "Source Link" enabled I <F11> the debugger I get: <!DOCTYPE html> <HTML> <head> </head> <body> <!--StartFragment-->   | Name | Value | Type -- | -- | -- | --   | Message | "Collection was modified; enumeration operation may not execute." | string   | Source | "System.Private.CoreLib" | string   | StackTrace | " at System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() in /_/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs:line 361" | string <!--EndFragment--> </body> </HTML> Yesterday I ran the application from OUTSIDE Visual Studio 2022 from the DEBUG directory. When I clicked the close button the application appeared to shut down without issue, but looking in the Windows Application Log I saw: ``` Application: WeatherWire_Personal.exe CoreCLR Version: 5.0.1221.52207 .NET Version: 5.0.12 Description: The process was terminated due to an unhandled exception. Exception Info: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.Generic.List`1.Enumerator.MoveNextRare() at Microsoft.Data.Sqlite.SqliteConnectionPool.ReclaimLeakedConnections() at Microsoft.Data.Sqlite.SqliteConnectionPool.Clear() at Microsoft.Data.Sqlite.SqliteConnectionFactory.ReleasePool(SqliteConnectionPool pool, Boolean clearing) at Microsoft.Data.Sqlite.SqliteConnectionPoolGroup.Clear() at Microsoft.Data.Sqlite.SqliteConnectionFactory.ClearPools() at Microsoft.Data.Sqlite.SqliteConnectionFactory.<.ctor>b__7_1(Object _, EventArgs _) at System.AppContext.OnProcessExit() ``` ...then immediately after... ``` Faulting application name: WeatherWire_Personal.exe, version: 0.1.1.0, time stamp: 0x61732c02 Faulting module name: KERNELBASE.dll, version: 10.0.19041.1387, time stamp: 0x0b9a844a Exception code: 0xe0434352 Fault offset: 0x0000000000034f69 Faulting process id: 0xa208 Faulting application start time: 0x01d802880e12fd2f Faulting application path: P:\Development\WeatherWire\WeatherWire_Personal\bin\Debug\net5.0-windows\WeatherWire_Personal.exe Faulting module path: C:\WINDOWS\System32\KERNELBASE.dll Report Id: d9c0925c-d9ae-40aa-b747-62bb35d2d0ea Faulting package full name: Faulting package-relative application ID: ``` I checked that I closed and even DISPOSE() my Sqlite Database connections. I'm totally at a loss if this is something with Visual Studio, .Net 5, or what. It doesn't appear to be code that I'm running, although I haven't ruled it out. It's just that the exception is being thrown after all my code stops running. I'd appreciate any guidance on where to look next that anyone has. -Joe
Some more investigation... I started working on commenting anything out that I thought might be an issue, working my way back up the main program loop...so to speak. Something strange: ``` //- Check the command line arguments to see if we need to process anything string[]? args = Environment.GetCommandLineArgs(); if (args.Length > 0) { CheckCommandLine(args, applog, _configDBPath, _msgDBPath, _nwwsClient); } else { applog.Debug("No command line options present when app was started."); } Application.Exit(); //- Display Splash Screen SplashScreen frmSplash = new SplashScreen(applog, _cfgHelper, _nwwsClient, _AssemblyVersion, _configDBPath, _msgDBPath, true); frmSplash.ShowDialog(); ``` After the "Application.Exit()" statement, the application continues on running the SplashScreen. I was under the impression that Application.Exit is supposed to close down all the forms and then exit the application from the "Main()" method. In other words, anything after "Application.Exit();" is just unreachable code. If I use: ``` Application.Exit(); Environment.Exit(0); ``` ...the program shuts down there, as expected. Looking at the documentation for Application.Exit() I see: > Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. I'm no expert but am I to understand that "Application.Exit()" will kill off all message pumps, close all forms, but then the application continues to anything following it? -Joe Same thing happens if I use: ``` Application.Exit(); this.Close(); ``` I know that the Application.Exit() closes the form that is currently running the code....but I would have expected the "this.Close()" would at least throw an exception. @dataweasel Application.Exit() is a Winforms API which terminates the Winforms application/resources (e.g. closing windows), but the .NET program itself continues running. Environment.Exit is the thing that actually terminates the .NET process, and also triggers the Sqlite connection pool clearing code which you see above. Microsoft.Data.Sqlite and Winforms are oblivious of each other. Regardless, the stack trace you posted above does seem to indicate a bug. A few questions: * Which version of Microsoft.Data.Sqlite are you using? * Does the exception happen reliably every time? Or only from time to time? If it's the former, can you submit a minimal code repro which reproduces it? From a cursory look at SqliteConnectionPool nothing obvious pops up. [We do access _connections.Count without locking](https://github.com/dotnet/efcore/blob/main/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs#L38), but that shouldn't cause any exceptions (we may want to consider locking around it just in case though). /cc @bricelam @roji - I am using the latest Microsoft.Data.Sqlite from Nuget (so...6.0.1?). It does happen reliably every time...but I think I might have figured out my problem. I think I had a stray Sqlite connection still open when the program went to exit. I did a full code review and found a class where I had opened a Sqlite connection and did not have a close at the end of the method. When the close wasn't there I would get this exception 100% of the time. When I added the close, the problem went away. I then commented out the close and the exception returned. I will try to get a minimal code repro for you. I'm looking at the following: 1. Program Start 2. Open connection to Sqlite DB. 3. Instance a class that also opens a connection to a different Sqlite database but does not close it. 4. Exit main program I'll let you know if this repros. -Joe @dataweasel thanks for the additional. Even if you forgot the Close, I'm still very interested in looking into this, as it may indicate an internal bug which could have other effects. So a repro would be much appreciated. That's an interesting bug, Whenever the pool attempts to [reclaim](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs#L156) a connection, while enumerating the list, it might call [Return](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs#L166) on a leaked connection. While returning the connection to the pool, in some cases it might [dispose](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs#L88) them. And while disposing the connection, it's [removed](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionPool.cs#L150) from the `_connections` list. That way, the list is changed while it's already enumerated. I quickly tried this with a Console Application and leaving the connection open didn't cause an issue. I'm not doing much work with the DB connections (just opening the connection to a file with no tables or data) so I'm not sure if that has anything to do with it. My application where this was failing was a Windows Form app (.Net 5). Still working on it. Managed to reproduce in a console app. ```csharp using Microsoft.Data.Sqlite; Test(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); static void Test() { var connection = new SqliteConnection("Data Source=hello.db"); connection.Open(); } ``` This works: ``` using System; using Microsoft.Data.Sqlite; namespace SqliteDbTest { internal class Program { private static SqliteConnection dbConn01 = null; static void Main(string[] args) { DBOpen(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } static void DBOpen() { string strDB01File = @"c:\temp\db01.sqlite"; dbConn01 = new SqliteConnection($"Data Source={strDB01File};"); dbConn01.Open(); } } } ``` This breaks: ``` using System; using Microsoft.Data.Sqlite; namespace SqliteDbTest { internal class Program { static void Main(string[] args) { DBOpen(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } static void DBOpen() { string strDB01File = @"c:\temp\db01.sqlite"; var dbConn01 = new SqliteConnection($"Data Source={strDB01File};"); dbConn01.Open(); } } } ``` Changing to var instead of a declaration is the difference? -Joe > Changing to var instead of a declaration is the difference? Kind of, in your case it's the static field - the point is for the GC to collect `SqliteConnection`. > Kind of, in your case it's the static field - the point is for the GC to collect `SqliteConnection`. Okay...I am starting to see it now. It's now how it is being used or even that it is "open" when the program is ending. When GC attempts to dispose of it (from a pool or something) it's disposing of the connection object, which changes the collection of connections while it is being enumerated. Did I get that right? That's why the stack trace has the "ReclaimLeakedConnections()" and such. I'm still learning. Thanks for the insights. > When GC attempts to dispose of it (from a pool or something) it's disposing of the connection object, which changes the collection of connections while it is being enumerated. Not exactly. SQLite has a [mechanism](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionInternal.cs#L101) to detect leaked connections, which is mostly determined by `WeakReference<SqliteConnection?>` going 'stale' (which does happen whenever `SqliteConnection` is GC'ed), Also, SQLite has a [mechanism](https://github.com/dotnet/efcore/blob/41e6aaaf6216de904530de11b0bfd4af43fb13f7/src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs#L31) to clear the pool whenever an app is closing. Combining both of them leads to the issue you've encountered. Thanks for looking into this @vonzshik - yeah, ReclaimLeakedConnections iterates over _connections, but calls return inside which mutates them. So not a concurrency issue - just a plain old mutate-within-iteration bug. Should be fixable by copying _connections before iterating.
2022-02-10T18:46:32Z
0.2
['Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Clear_works_when_connection_leaked']
['Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Internal_connections_are_reused_across_connections', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.EnableExtensions_doesnt_bleed_across_connections', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.ReadUncommitted_doesnt_bleed_across_connections', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Internal_connections_are_not_reused_after_clearing_pool', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Internal_connections_are_not_reused_when_pooling_is_disabled', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Functions_dont_bleed_across_connections', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Internal_connections_are_not_reused_after_clearing_pool_when_open', 'Microsoft.Data.Sqlite.SqliteConnectionFactoryTest.Internal_connections_are_reused_after_reopen']
dotnet/efcore
dotnet__efcore-28261
e62e76779de4a44d24a7c0b15f9946ce76bfba83
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosRegexTranslator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosRegexTranslator.cs index 51e735e7681..bf765963620 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosRegexTranslator.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosRegexTranslator.cs @@ -19,8 +19,6 @@ public class CosmosRegexTranslator : IMethodCallTranslator private static readonly MethodInfo IsMatchWithRegexOptions = typeof(Regex).GetRuntimeMethod(nameof(Regex.IsMatch), new[] { typeof(string), typeof(string), typeof(RegexOptions) })!; - private const RegexOptions SupportedOptions = RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace; - private readonly ISqlExpressionFactory _sqlExpressionFactory; /// <summary> @@ -53,48 +51,49 @@ public CosmosRegexTranslator(ISqlExpressionFactory sqlExpressionFactory) var (input, pattern) = (arguments[0], arguments[1]); var typeMapping = ExpressionExtensions.InferTypeMapping(input, pattern); + (input, pattern) = ( + _sqlExpressionFactory.ApplyTypeMapping(input, typeMapping), + _sqlExpressionFactory.ApplyTypeMapping(pattern, typeMapping)); - if (method == IsMatch) + if (method == IsMatch || arguments[2] is SqlConstantExpression { Value: RegexOptions.None }) { - return _sqlExpressionFactory.Function( - "RegexMatch", - new[] { - _sqlExpressionFactory.ApplyTypeMapping(input, typeMapping), - _sqlExpressionFactory.ApplyTypeMapping(pattern, typeMapping) - }, - typeof(bool)); + return _sqlExpressionFactory.Function("RegexMatch", new[] { input, pattern }, typeof(bool)); } - else if (arguments[2] is SqlConstantExpression { Value: RegexOptions regexOptions }) + + if (arguments[2] is SqlConstantExpression { Value: RegexOptions regexOptions }) { - string modifier = ""; + var modifier = ""; + if (regexOptions.HasFlag(RegexOptions.Multiline)) { + regexOptions &= ~RegexOptions.Multiline; modifier += "m"; } + if (regexOptions.HasFlag(RegexOptions.Singleline)) { + regexOptions &= ~RegexOptions.Singleline; modifier += "s"; } + if (regexOptions.HasFlag(RegexOptions.IgnoreCase)) { + regexOptions &= ~RegexOptions.IgnoreCase; modifier += "i"; } + if (regexOptions.HasFlag(RegexOptions.IgnorePatternWhitespace)) { + regexOptions &= ~RegexOptions.IgnorePatternWhitespace; modifier += "x"; } - return (regexOptions & ~SupportedOptions) == 0 + return regexOptions == 0 ? _sqlExpressionFactory.Function( "RegexMatch", - new[] - { - _sqlExpressionFactory.ApplyTypeMapping(input, typeMapping), - _sqlExpressionFactory.ApplyTypeMapping(pattern, typeMapping), - _sqlExpressionFactory.Constant(modifier) - }, + new[] { input, pattern, _sqlExpressionFactory.Constant(modifier) }, typeof(bool)) - : null; + : null; // TODO: Report unsupported RegexOption, #26410 } return null;
diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs index 7529b91fa3d..a67e1e4ced6 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs @@ -1235,7 +1235,7 @@ await AssertQuery( AssertSql( @"SELECT c FROM root c -WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", """"))"); +WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T""))"); } [ConditionalTheory] @@ -1313,15 +1313,19 @@ FROM root c WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", ""ix""))"); } - [Fact] - public virtual void Regex_IsMatch_MethodCall_With_Unsupported_Option() - => Assert.Throws<InvalidOperationException>(() => - Fixture.CreateContext().Customers.Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.RightToLeft)).ToList()); + [ConditionalTheory] + [MemberData(nameof(IsAsyncData))] + public virtual Task Regex_IsMatch_MethodCall_With_Unsupported_Option(bool async) + => AssertTranslationFailed(() => AssertQuery( + async, + ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.RightToLeft)))); - [Fact] - public virtual void Regex_IsMatch_MethodCall_With_Any_Unsupported_Option() - => Assert.Throws<InvalidOperationException>(() => - Fixture.CreateContext().Customers.Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase | RegexOptions.RightToLeft)).ToList()); + [ConditionalTheory] + [MemberData(nameof(IsAsyncData))] + public virtual Task Regex_IsMatch_MethodCall_With_Any_Unsupported_Option(bool async) + => AssertTranslationFailed(() => AssertQuery( + async, + ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase | RegexOptions.RightToLeft)))); [ConditionalTheory] [MemberData(nameof(IsAsyncData))]
Cosmos: Fixup to Regex.IsMatch translation Fixup to https://github.com/dotnet/efcore/pull/28121 * ~Throw a detailed exception for unsupported options when translating Regex.IsMatch (see discussion below)~ * "Constantize" regex options via EvaluatableFilter (https://github.com/dotnet/efcore/pull/28121#discussion_r886897927) * Avoid generating empty options parameter if RegexOptions.None is specified (https://github.com/dotnet/efcore/pull/28121#discussion_r886896534)
Depend on #26410, right? Not really blocked, the method translator should throw exception from itself. Don't we avoid doing that since it would block client eval? Depends if we want to do client eval of certain things. OK, I'll bring this up in design, possibly with a proposal for #26410. If you think we would need #26410 for this, we can wait till we put that one in plan. Just to figure out how we see things... If we're OK with throwing in method translators, #26410 becomes much less important, maybe even closeable (note it's already in the milestone). I still think that ideally we just do #26410, e.g. by having translator return some NotTranslatableExpression (which wraps details); and then we don't have to discuss throwing because that always allows client eval and provides nicer exceptions. But we can discuss all that. I'll prepare a PR for this @Marusyk sure, but we'll need to decide what we want to do with unsupported options (design discussion pending). Design decision: we'll do #26410 at some point, but for now it should be fine to just return null for unsupported options, so the user will just get the generic "cannot translate" exception. @Marusyk this should unblock you for working on this issue. So, should I return the previous version with [HashSet](https://github.com/dotnet/efcore/pull/28121/files/b8cba0c574c3295aa622a7cc71a954a446f43e83#diff-ddd4f5b756ddfba1b854430190d2fe812fc0bed705ff3263e9d05074a9d24a46R22)? > "Constantize" regex options via EvaluatableFilter I'm not sure that understand this task. Do I need to implement CosmosEvaluatableExpressionFilter? > So, should I return the previous version with [HashSet](https://github.com/dotnet/efcore/pull/28121/files/b8cba0c574c3295aa622a7cc71a954a446f43e83#diff-ddd4f5b756ddfba1b854430190d2fe812fc0bed705ff3263e9d05074a9d24a46R22)? Nope, I don't see any reason for doing so. The current code does the right thing (for now) - if there's any unsupported option, it just returns null. > Do I need to implement CosmosEvaluatableExpressionFilter? Yeah, @smitpatel can probably offer some more assistance if needed. @Marusyk do you intend to work on this? Unfortunately, I don't have time to investigate EvaluatableExpressionFilter.
2022-06-17T16:47:08Z
0.2
[]
['Microsoft.EntityFrameworkCore.Query.NorthwindFunctionsQueryCosmosTest.Regex_IsMatch_MethodCall_With_Unsupported_Option', 'Microsoft.EntityFrameworkCore.Query.NorthwindFunctionsQueryCosmosTest.Regex_IsMatch_MethodCall_With_Any_Unsupported_Option']
dotnet/efcore
dotnet__efcore-34832
67254af14db19dbf17f04b0b3cae3881d09ccee0
diff --git a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs index 2cd011ba677..5bdf3af9087 100644 --- a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs +++ b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs @@ -76,6 +76,7 @@ private static readonly Regex PartExtractor private byte? _compatibilityLevel; private EngineEdition? _engineEdition; + private string? _version; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -125,6 +126,7 @@ public override DatabaseModel Create(DbConnection connection, DatabaseModelFacto _compatibilityLevel = GetCompatibilityLevel(connection); _engineEdition = GetEngineEdition(connection); + _version = GetVersion(connection); databaseModel.DatabaseName = connection.Database; databaseModel.DefaultSchema = GetDefaultSchema(connection); @@ -191,6 +193,14 @@ static EngineEdition GetEngineEdition(DbConnection connection) return result != null ? (EngineEdition)Convert.ToInt32(result) : 0; } + static string? GetVersion(DbConnection connection) + { + using var command = connection.CreateCommand(); + command.CommandText = "SELECT @@VERSION;"; + var result = command.ExecuteScalar(); + return result as string; + } + static byte GetCompatibilityLevel(DbConnection connection) { using var command = connection.CreateCommand(); @@ -542,12 +552,11 @@ FROM [sys].[tables] AS [t] var tableFilterBuilder = new StringBuilder( $""" [t].[is_ms_shipped] = 0 -AND NOT EXISTS (SELECT * - FROM [sys].[extended_properties] AS [ep] - WHERE [ep].[major_id] = [t].[object_id] - AND [ep].[minor_id] = 0 - AND [ep].[class] = 1 - AND [ep].[name] = N'microsoft_database_tools_support' +AND [t].[object_id] NOT IN (SELECT [ep].[major_id] + FROM [sys].[extended_properties] AS [ep] + WHERE [ep].[minor_id] = 0 + AND [ep].[class] = 1 + AND [ep].[name] = N'microsoft_database_tools_support' ) AND [t].[name] <> '{HistoryRepository.DefaultTableName}' """); @@ -1466,7 +1475,7 @@ private bool SupportsTriggers() => IsFullFeaturedEngineEdition(); private bool IsFullFeaturedEngineEdition() - => _engineEdition is not EngineEdition.SqlDataWarehouse and not EngineEdition.SqlOnDemand and not EngineEdition.DynamicsTdsEndpoint; + => _engineEdition is not EngineEdition.SqlDataWarehouse and not EngineEdition.SqlOnDemand and not EngineEdition.DynamicsTdsEndpoint && _version != "Microsoft SQL Kusto"; private static string DisplayName(string? schema, string name) => (!string.IsNullOrEmpty(schema) ? schema + "." : "") + name; diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs index e3f3fcdb838..e97f68487e8 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs @@ -136,12 +136,11 @@ IF EXISTS FROM [sys].[objects] o WHERE [o].[type] = 'U' AND [o].[is_ms_shipped] = 0 - AND NOT EXISTS (SELECT * - FROM [sys].[extended_properties] AS [ep] - WHERE [ep].[major_id] = [o].[object_id] - AND [ep].[minor_id] = 0 - AND [ep].[class] = 1 - AND [ep].[name] = N'microsoft_database_tools_support' + AND [o].[object_id] NOT IN (SELECT [ep].[major_id] + FROM [sys].[extended_properties] AS [ep] + WHERE [ep].[minor_id] = 0 + AND [ep].[class] = 1 + AND [ep].[name] = N'microsoft_database_tools_support' ) ) SELECT 1 ELSE SELECT 0");
diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs index 9cec3c4e613..766a1a61654 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs @@ -6202,12 +6202,11 @@ IF EXISTS FROM [sys].[objects] o WHERE [o].[type] = 'U' AND [o].[is_ms_shipped] = 0 - AND NOT EXISTS (SELECT * - FROM [sys].[extended_properties] AS [ep] - WHERE [ep].[major_id] = [o].[object_id] - AND [ep].[minor_id] = 0 - AND [ep].[class] = 1 - AND [ep].[name] = N'microsoft_database_tools_support' + AND [o].[object_id] NOT IN (SELECT [ep].[major_id] + FROM [sys].[extended_properties] AS [ep] + WHERE [ep].[minor_id] = 0 + AND [ep].[class] = 1 + AND [ep].[name] = N'microsoft_database_tools_support' ) ) SELECT 1 ELSE SELECT 0 @@ -6454,12 +6453,11 @@ IF EXISTS FROM [sys].[objects] o WHERE [o].[type] = 'U' AND [o].[is_ms_shipped] = 0 - AND NOT EXISTS (SELECT * - FROM [sys].[extended_properties] AS [ep] - WHERE [ep].[major_id] = [o].[object_id] - AND [ep].[minor_id] = 0 - AND [ep].[class] = 1 - AND [ep].[name] = N'microsoft_database_tools_support' + AND [o].[object_id] NOT IN (SELECT [ep].[major_id] + FROM [sys].[extended_properties] AS [ep] + WHERE [ep].[minor_id] = 0 + AND [ep].[class] = 1 + AND [ep].[name] = N'microsoft_database_tools_support' ) ) SELECT 1 ELSE SELECT 0
Scaffolding against Azure Data Explorer with SQL Server emulation doesn't work using connection string of kusto like mention here trying to scaffold via dotnet ef dbcontext scaffold got this error looks like OBJECT_SCHEMA_NAME method is not supported in kusto integration https://learn.microsoft.com/en-us/azure/data-explorer/sql-server-emulation-overview and i see the fix can be by modifying SupportsSequences() by detecting kusto fix: https://github.com/dotnet/efcore/pull/34832/files ```Microsoft.Data.SqlClient.SqlException (0x80131904): Request is invalid and cannot be processed: Semantic error: OTR0001: Scalar SQL function 'OBJECT_SCHEMA_NAME' is not supported. [line:position=2:5] RequestId: TDS;906c6b05-c363-4ff3-9eea-0d7a2ef3fbff;10 Time: 2024-10-06T10:30:49.8561434Z at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs:line 2010 at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) in /_/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs:line 770 at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs:line 1421 at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs:line 2637 at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData() in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs:line 1142 at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData() in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs:line 258 at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs:line 5171 at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs:line 4984 at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs:line 4663 at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs:line 4544 at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) in /_/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs:line 2043 at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) ClientConnectionId:906c6b05-c363-4ff3-9eea-0d7a2ef3fbff Error Number:40000,State:1,Class:16 Request is invalid and cannot be processed: Semantic error: OTR0001: Scalar SQL function 'OBJECT_SCHEMA_NAME' is not supported. [line:position=2:5] RequestId: TDS;906c6b05-c363-4ff3-9eea-0d7a2ef3fbff;10 Time: 2024-10-06T10:30:49.8561434Z```
null
2024-10-06T10:50:47Z
0.1
[]
[]
dotnet/efcore
dotnet__efcore-34052
41e511f4affc20b5ef16ce1c9999e796d3ba8db9
diff --git a/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs b/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs index 7214fd81382..5e5ecf8127d 100644 --- a/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs +++ b/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; +using Microsoft.EntityFrameworkCore.SqlServer.Internal; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore; @@ -11,13 +12,13 @@ namespace Microsoft.EntityFrameworkCore; /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and -/// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> +/// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> public static class SqlServerDbContextOptionsExtensions { /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database, but without initially setting any + /// Configures the context to connect to a SQL Server database, but without initially setting any /// <see cref="DbConnection" /> or connection string. /// </summary> /// <remarks> @@ -28,52 +29,56 @@ public static class SqlServerDbContextOptionsExtensions /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </para> /// </remarks> /// <param name="optionsBuilder">The builder being used to configure the context.</param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder UseSqlServer( this DbContextOptionsBuilder optionsBuilder, Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) { - ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(GetOrCreateExtension(optionsBuilder)); - + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = extension + .WithEngineType(SqlServerEngineType.SqlServer); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); } /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <param name="optionsBuilder">The builder being used to configure the context.</param> /// <param name="connectionString">The connection string of the database to connect to.</param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder UseSqlServer( this DbContextOptionsBuilder optionsBuilder, string? connectionString, Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) { - var extension = (SqlServerOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnectionString(connectionString); + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.SqlServer) + .WithConnectionString(connectionString); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); } // Note: Decision made to use DbConnection not SqlConnection: Issue #772 /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <param name="optionsBuilder">The builder being used to configure the context.</param> @@ -83,7 +88,7 @@ public static DbContextOptionsBuilder UseSqlServer( /// state then EF will open and close the connection as needed. The caller owns the connection and is /// responsible for its disposal. /// </param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder UseSqlServer( this DbContextOptionsBuilder optionsBuilder, @@ -93,11 +98,11 @@ public static DbContextOptionsBuilder UseSqlServer( // Note: Decision made to use DbConnection not SqlConnection: Issue #772 /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <param name="optionsBuilder">The builder being used to configure the context.</param> @@ -111,7 +116,7 @@ public static DbContextOptionsBuilder UseSqlServer( /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still /// owns the connection and is responsible for its disposal. /// </param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder UseSqlServer( this DbContextOptionsBuilder optionsBuilder, @@ -121,14 +126,16 @@ public static DbContextOptionsBuilder UseSqlServer( { Check.NotNull(connection, nameof(connection)); - var extension = (SqlServerOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnection(connection, contextOwnsConnection); + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.SqlServer) + .WithConnection(connection, contextOwnsConnection); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); } /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database, but without initially setting any + /// Configures the context to connect to a SQL Server database, but without initially setting any /// <see cref="DbConnection" /> or connection string. /// </summary> /// <remarks> @@ -139,12 +146,12 @@ public static DbContextOptionsBuilder UseSqlServer( /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </para> /// </remarks> /// <param name="optionsBuilder">The builder being used to configure the context.</param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( this DbContextOptionsBuilder<TContext> optionsBuilder, @@ -154,17 +161,17 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( (DbContextOptionsBuilder)optionsBuilder, sqlServerOptionsAction); /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <typeparam name="TContext">The type of context to be configured.</typeparam> /// <param name="optionsBuilder">The builder being used to configure the context.</param> /// <param name="connectionString">The connection string of the database to connect to.</param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( this DbContextOptionsBuilder<TContext> optionsBuilder, @@ -176,11 +183,11 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( // Note: Decision made to use DbConnection not SqlConnection: Issue #772 /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <typeparam name="TContext">The type of context to be configured.</typeparam> @@ -191,7 +198,7 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( /// state then EF will open and close the connection as needed. The caller owns the connection and is /// responsible for its disposal. /// </param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( this DbContextOptionsBuilder<TContext> optionsBuilder, @@ -203,11 +210,11 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( // Note: Decision made to use DbConnection not SqlConnection: Issue #772 /// <summary> - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a SQL Server database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </remarks> /// <typeparam name="TContext">The type of context to be configured.</typeparam> @@ -222,7 +229,7 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still /// owns the connection and is responsible for its disposal. /// </param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <returns>The options builder so that further configuration can be chained.</returns> public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( this DbContextOptionsBuilder<TContext> optionsBuilder, @@ -233,9 +240,509 @@ public static DbContextOptionsBuilder<TContext> UseSqlServer<TContext>( => (DbContextOptionsBuilder<TContext>)UseSqlServer( (DbContextOptionsBuilder)optionsBuilder, connection, contextOwnsConnection, sqlServerOptionsAction); - private static SqlServerOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.Options.FindExtension<SqlServerOptionsExtension>() - ?? new SqlServerOptionsExtension(); + /// <summary> + /// Configures the context to connect to a Azure SQL database, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSql( + this DbContextOptionsBuilder optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = extension + .WithEngineType(SqlServerEngineType.AzureSql); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSql( + this DbContextOptionsBuilder optionsBuilder, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.AzureSql) + .WithConnectionString(connectionString); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. The caller owns the connection and is + /// responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSql( + this DbContextOptionsBuilder optionsBuilder, + DbConnection connection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + => UseAzureSql(optionsBuilder, connection, false, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. + /// </param> + /// <param name="contextOwnsConnection"> + /// If <see langword="true" />, then EF will take ownership of the connection and will + /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still + /// owns the connection and is responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSql( + this DbContextOptionsBuilder optionsBuilder, + DbConnection connection, + bool contextOwnsConnection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + Check.NotNull(connection, nameof(connection)); + + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.AzureSql) + .WithConnection(connection, contextOwnsConnection); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + /// <summary> + /// Configures the context to connect to a Azure SQL database, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSql<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSql( + (DbContextOptionsBuilder)optionsBuilder, sqlServerOptionsAction); + + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSql<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSql( + (DbContextOptionsBuilder)optionsBuilder, connectionString, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. The caller owns the connection and is + /// responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSql<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + DbConnection connection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSql( + (DbContextOptionsBuilder)optionsBuilder, connection, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. + /// </param> + /// <param name="contextOwnsConnection"> + /// If <see langword="true" />, then EF will take ownership of the connection and will + /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still + /// owns the connection and is responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSql<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + DbConnection connection, + bool contextOwnsConnection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSql( + (DbContextOptionsBuilder)optionsBuilder, connection, contextOwnsConnection, sqlServerOptionsAction); + + /// <summary> + /// Configures the context to connect to a Azure Synapse database, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSynapse( + this DbContextOptionsBuilder optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = extension + .WithEngineType(SqlServerEngineType.AzureSynapse); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSynapse( + this DbContextOptionsBuilder optionsBuilder, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.AzureSynapse) + .WithConnectionString(connectionString); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. The caller owns the connection and is + /// responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSynapse( + this DbContextOptionsBuilder optionsBuilder, + DbConnection connection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + => UseAzureSynapse(optionsBuilder, connection, false, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. + /// </param> + /// <param name="contextOwnsConnection"> + /// If <see langword="true" />, then EF will take ownership of the connection and will + /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still + /// owns the connection and is responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder UseAzureSynapse( + this DbContextOptionsBuilder optionsBuilder, + DbConnection connection, + bool contextOwnsConnection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + Check.NotNull(connection, nameof(connection)); + + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder); + extension = (SqlServerOptionsExtension)extension + .WithEngineType(SqlServerEngineType.AzureSynapse) + .WithConnection(connection, contextOwnsConnection); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + /// <summary> + /// Configures the context to connect to a Azure Synapse database, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSynapse<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSynapse( + (DbContextOptionsBuilder)optionsBuilder, sqlServerOptionsAction); + + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSynapse<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSynapse( + (DbContextOptionsBuilder)optionsBuilder, connectionString, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. The caller owns the connection and is + /// responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSynapse<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + DbConnection connection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSynapse( + (DbContextOptionsBuilder)optionsBuilder, connection, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// <summary> + /// Configures the context to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </remarks> + /// <typeparam name="TContext">The type of context to be configured.</typeparam> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="connection"> + /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. + /// </param> + /// <param name="contextOwnsConnection"> + /// If <see langword="true" />, then EF will take ownership of the connection and will + /// dispose it in the same way it would dispose a connection created by EF. If <see langword="false" />, then the caller still + /// owns the connection and is responsible for its disposal. + /// </param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> UseAzureSynapse<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + DbConnection connection, + bool contextOwnsConnection, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)UseAzureSynapse( + (DbContextOptionsBuilder)optionsBuilder, connection, contextOwnsConnection, sqlServerOptionsAction); + + /// <summary> + /// Configures the context to connect to any of SQL Server, Azure SQL, Azure Synapse databases, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder ConfigureSqlEngine( + this DbContextOptionsBuilder optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + { + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder)); + return ApplyConfiguration(optionsBuilder, sqlServerOptionsAction); + } + + /// <summary> + /// Configures the context to connect to any of SQL Server, Azure SQL, Azure Synapse databases, but without initially setting any + /// <see cref="DbConnection" /> or connection string. + /// </summary> + /// <remarks> + /// <para> + /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect + /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. + /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <param name="optionsBuilder">The builder being used to configure the context.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <returns>The options builder so that further configuration can be chained.</returns> + public static DbContextOptionsBuilder<TContext> ConfigureSqlEngine<TContext>( + this DbContextOptionsBuilder<TContext> optionsBuilder, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder<TContext>)ConfigureSqlEngine( + (DbContextOptionsBuilder)optionsBuilder, sqlServerOptionsAction); + + private static T GetOrCreateExtension<T>(DbContextOptionsBuilder optionsBuilder) + where T : RelationalOptionsExtension, new() + => optionsBuilder.Options.FindExtension<T>() + ?? new T(); private static DbContextOptionsBuilder ApplyConfiguration( DbContextOptionsBuilder optionsBuilder, @@ -245,7 +752,7 @@ private static DbContextOptionsBuilder ApplyConfiguration( sqlServerOptionsAction?.Invoke(new SqlServerDbContextOptionsBuilder(optionsBuilder)); - var extension = (SqlServerOptionsExtension)GetOrCreateExtension(optionsBuilder).ApplyDefaults(optionsBuilder.Options); + var extension = GetOrCreateExtension<SqlServerOptionsExtension>(optionsBuilder).ApplyDefaults(optionsBuilder.Options); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); return optionsBuilder; diff --git a/src/EFCore.SqlServer/Extensions/SqlServerServiceCollectionExtensions.cs b/src/EFCore.SqlServer/Extensions/SqlServerServiceCollectionExtensions.cs index 12f2d4cf882..87f220451ed 100644 --- a/src/EFCore.SqlServer/Extensions/SqlServerServiceCollectionExtensions.cs +++ b/src/EFCore.SqlServer/Extensions/SqlServerServiceCollectionExtensions.cs @@ -15,7 +15,7 @@ namespace Microsoft.Extensions.DependencyInjection; /// <summary> -/// SQL Server specific extension methods for <see cref="IServiceCollection" />. +/// SQL Server, Azure SQL, Azure Synapse specific extension methods for <see cref="IServiceCollection" />. /// </summary> public static class SqlServerServiceCollectionExtensions { @@ -45,14 +45,14 @@ public static class SqlServerServiceCollectionExtensions /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and - /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server and Azure SQL databases with EF Core</see> + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> /// for more information and examples. /// </para> /// </remarks> /// <typeparam name="TContext">The type of context to be registered.</typeparam> /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> /// <param name="connectionString">The connection string of the database to connect to.</param> - /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server specific configuration.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> /// <param name="optionsAction">An optional action to configure the <see cref="DbContextOptions" /> for the context.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> public static IServiceCollection AddSqlServer<TContext>( @@ -91,6 +91,157 @@ public static IServiceCollection AddSqlServer<TContext>( /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] public static IServiceCollection AddEntityFrameworkSqlServer(this IServiceCollection serviceCollection) + => AddEntityFrameworkSqlEngine(serviceCollection); + + /// <summary> + /// Registers the given Entity Framework <see cref="DbContext" /> as a service in the <see cref="IServiceCollection" /> + /// and configures it to connect to a Azure SQL database. + /// </summary> + /// <remarks> + /// <para> + /// This method is a shortcut for configuring a <see cref="DbContext" /> to use Azure SQL. It does not support all options. + /// Use <see cref="O:EntityFrameworkServiceCollectionExtensions.AddDbContext" /> and related methods for full control of + /// this process. + /// </para> + /// <para> + /// Use this method when using dependency injection in your application, such as with ASP.NET Core. + /// For applications that don't use dependency injection, consider creating <see cref="DbContext" /> + /// instances directly with its constructor. The <see cref="DbContext.OnConfiguring" /> method can then be + /// overridden to configure the Azure SQL provider and connection string. + /// </para> + /// <para> + /// To configure the <see cref="DbContextOptions{TContext}" /> for the context, either override the + /// <see cref="DbContext.OnConfiguring" /> method in your derived context, or supply + /// an optional action to configure the <see cref="DbContextOptions" /> for the context. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-di">Using DbContext with dependency injection</see> for more information and examples. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <typeparam name="TContext">The type of context to be registered.</typeparam> + /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <param name="optionsAction">An optional action to configure the <see cref="DbContextOptions" /> for the context.</param> + /// <returns>The same service collection so that multiple calls can be chained.</returns> + public static IServiceCollection AddAzureSql<TContext>( + this IServiceCollection serviceCollection, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null, + Action<DbContextOptionsBuilder>? optionsAction = null) + where TContext : DbContext + => serviceCollection.AddDbContext<TContext>( + (_, options) => + { + optionsAction?.Invoke(options); + options.UseAzureSql(connectionString, sqlServerOptionsAction); + }); + + /// <summary> + /// <para> + /// Adds the services required by the Microsoft Azure SQL database provider for Entity Framework + /// to an <see cref="IServiceCollection" />. + /// </para> + /// <para> + /// Warning: Do not call this method accidentally. It is much more likely you need + /// to call <see cref="AddAzureSql{TContext}" />. + /// </para> + /// </summary> + /// <remarks> + /// Calling this method is no longer necessary when building most applications, including those that + /// use dependency injection in ASP.NET or elsewhere. + /// It is only needed when building the internal service provider for use with + /// the <see cref="DbContextOptionsBuilder.UseInternalServiceProvider" /> method. + /// This is not recommend other than for some advanced scenarios. + /// </remarks> + /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> + /// <returns> + /// The same service collection so that multiple calls can be chained. + /// </returns> + [EditorBrowsable(EditorBrowsableState.Never)] + public static IServiceCollection AddEntityFrameworkAzureSql(this IServiceCollection serviceCollection) + => AddEntityFrameworkSqlEngine(serviceCollection); + + /// <summary> + /// Registers the given Entity Framework <see cref="DbContext" /> as a service in the <see cref="IServiceCollection" /> + /// and configures it to connect to a Azure Synapse database. + /// </summary> + /// <remarks> + /// <para> + /// This method is a shortcut for configuring a <see cref="DbContext" /> to use Azure Synapse. It does not support all options. + /// Use <see cref="O:EntityFrameworkServiceCollectionExtensions.AddDbContext" /> and related methods for full control of + /// this process. + /// </para> + /// <para> + /// Use this method when using dependency injection in your application, such as with ASP.NET Core. + /// For applications that don't use dependency injection, consider creating <see cref="DbContext" /> + /// instances directly with its constructor. The <see cref="DbContext.OnConfiguring" /> method can then be + /// overridden to configure the Azure Synapse provider and connection string. + /// </para> + /// <para> + /// To configure the <see cref="DbContextOptions{TContext}" /> for the context, either override the + /// <see cref="DbContext.OnConfiguring" /> method in your derived context, or supply + /// an optional action to configure the <see cref="DbContextOptions" /> for the context. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-di">Using DbContext with dependency injection</see> for more information and examples. + /// </para> + /// <para> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://aka.ms/efcore-docs-sqlserver">Accessing SQL Server, Azure SQL, Azure Synapse databases with EF Core</see> + /// for more information and examples. + /// </para> + /// </remarks> + /// <typeparam name="TContext">The type of context to be registered.</typeparam> + /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> + /// <param name="connectionString">The connection string of the database to connect to.</param> + /// <param name="sqlServerOptionsAction">An optional action to allow additional SQL Server, Azure SQL, Azure Synapse specific configuration.</param> + /// <param name="optionsAction">An optional action to configure the <see cref="DbContextOptions" /> for the context.</param> + /// <returns>The same service collection so that multiple calls can be chained.</returns> + public static IServiceCollection AddAzureSynapse<TContext>( + this IServiceCollection serviceCollection, + string? connectionString, + Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null, + Action<DbContextOptionsBuilder>? optionsAction = null) + where TContext : DbContext + => serviceCollection.AddDbContext<TContext>( + (_, options) => + { + optionsAction?.Invoke(options); + options.UseAzureSynapse(connectionString, sqlServerOptionsAction); + }); + + /// <summary> + /// <para> + /// Adds the services required by the Microsoft Azure Synapse database provider for Entity Framework + /// to an <see cref="IServiceCollection" />. + /// </para> + /// <para> + /// Warning: Do not call this method accidentally. It is much more likely you need + /// to call <see cref="AddAzureSynapse{TContext}" />. + /// </para> + /// </summary> + /// <remarks> + /// Calling this method is no longer necessary when building most applications, including those that + /// use dependency injection in ASP.NET or elsewhere. + /// It is only needed when building the internal service provider for use with + /// the <see cref="DbContextOptionsBuilder.UseInternalServiceProvider" /> method. + /// This is not recommend other than for some advanced scenarios. + /// </remarks> + /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> + /// <returns> + /// The same service collection so that multiple calls can be chained. + /// </returns> + [EditorBrowsable(EditorBrowsableState.Never)] + public static IServiceCollection AddEntityFrameworkAzureSynapse(this IServiceCollection serviceCollection) + => AddEntityFrameworkSqlEngine(serviceCollection); + + private static IServiceCollection AddEntityFrameworkSqlEngine(IServiceCollection serviceCollection) { new EntityFrameworkRelationalServicesBuilder(serviceCollection) .TryAdd<LoggingDefinitions, SqlServerLoggingDefinitions>() diff --git a/src/EFCore.SqlServer/Infrastructure/Internal/ISqlServerSingletonOptions.cs b/src/EFCore.SqlServer/Infrastructure/Internal/ISqlServerSingletonOptions.cs index f5f661d65d3..47728ddbc9d 100644 --- a/src/EFCore.SqlServer/Infrastructure/Internal/ISqlServerSingletonOptions.cs +++ b/src/EFCore.SqlServer/Infrastructure/Internal/ISqlServerSingletonOptions.cs @@ -17,7 +17,7 @@ public interface ISqlServerSingletonOptions : ISingletonOptions /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - int CompatibilityLevel { get; } + public SqlServerEngineType EngineType { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -25,5 +25,21 @@ public interface ISqlServerSingletonOptions : ISingletonOptions /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - int? CompatibilityLevelWithoutDefault { get; } + public int SqlServerCompatibilityLevel { get; } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public int AzureSqlCompatibilityLevel { get; } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public int AzureSynapseCompatibilityLevel { get; } } diff --git a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerEngineType.cs b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerEngineType.cs new file mode 100644 index 00000000000..63f9c9816f4 --- /dev/null +++ b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerEngineType.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; + +/// <summary> +/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to +/// the same compatibility standards as public APIs. It may be changed or removed without notice in +/// any release. You should only use it directly in your code with extreme caution and knowing that +/// doing so can result in application failures when updating to a new Entity Framework Core release. +/// </summary> +public enum SqlServerEngineType +{ + /// <summary> + /// Unknown SQL engine type. + /// </summary> + Unknown = 0, + + /// <summary> + /// SQL Server. + /// </summary> + SqlServer = 1, + + /// <summary> + /// Azure SQL. + /// </summary> + AzureSql = 2, + + /// <summary> + /// Azure Synapse. + /// </summary> + AzureSynapse = 3, +} diff --git a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerOptionsExtension.cs b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerOptionsExtension.cs index ccf3d1961b9..2fb912637a7 100644 --- a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerOptionsExtension.cs +++ b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerOptionsExtension.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text; +using Microsoft.EntityFrameworkCore.SqlServer.Internal; namespace Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; @@ -14,8 +15,11 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; public class SqlServerOptionsExtension : RelationalOptionsExtension, IDbContextOptionsExtension { private DbContextOptionsExtensionInfo? _info; - private int? _compatibilityLevel; - private bool? _azureSql; + private SqlServerEngineType _engineType; + private bool _legacyAzureSql; + private int? _sqlServerCompatibilityLevel; + private int? _azureSqlCompatibilityLevel; + private int? _azureSynapseCompatibilityLevel; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -29,7 +33,30 @@ public class SqlServerOptionsExtension : RelationalOptionsExtension, IDbContextO // SQL Server 2017 (14.x): compatibility level 140, start date 2017-09-29, mainstream end date 2022-10-11, extended end date 2027-10-12 // SQL Server 2016 (13.x): compatibility level 130, start date 2016-06-01, mainstream end date 2021-07-13, extended end date 2026-07-14 // SQL Server 2014 (12.x): compatibility level 120, start date 2014-06-05, mainstream end date 2019-07-09, extended end date 2024-07-09 - public static readonly int DefaultCompatibilityLevel = 150; + public static readonly int SqlServerDefaultCompatibilityLevel = 150; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + // See https://learn.microsoft.com/sql/t-sql/statements/alter-database-transact-sql-compatibility-level + // SQL Server 2022 (16.x): compatibility level 160, start date 2022-11-16, mainstream end date 2028-01-11, extended end date 2033-01-11 + // SQL Server 2019 (15.x): compatibility level 150, start date 2019-11-04, mainstream end date 2025-02-28, extended end date 2030-01-08 + // SQL Server 2017 (14.x): compatibility level 140, start date 2017-09-29, mainstream end date 2022-10-11, extended end date 2027-10-12 + // SQL Server 2016 (13.x): compatibility level 130, start date 2016-06-01, mainstream end date 2021-07-13, extended end date 2026-07-14 + // SQL Server 2014 (12.x): compatibility level 120, start date 2014-06-05, mainstream end date 2019-07-09, extended end date 2024-07-09 + public static readonly int AzureSqlDefaultCompatibilityLevel = 150; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + // See https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-scoped-configuration-transact-sql + public static readonly int AzureSynapseDefaultCompatibilityLevel = 30; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -52,8 +79,11 @@ public SqlServerOptionsExtension() protected SqlServerOptionsExtension(SqlServerOptionsExtension copyFrom) : base(copyFrom) { - _compatibilityLevel = copyFrom._compatibilityLevel; - _azureSql = copyFrom._azureSql; + _engineType = copyFrom._engineType; + _legacyAzureSql = copyFrom._legacyAzureSql; + _sqlServerCompatibilityLevel = copyFrom._sqlServerCompatibilityLevel; + _azureSqlCompatibilityLevel = copyFrom._azureSqlCompatibilityLevel; + _azureSynapseCompatibilityLevel = copyFrom._azureSynapseCompatibilityLevel; } /// <summary> @@ -80,8 +110,64 @@ protected override RelationalOptionsExtension Clone() /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual int CompatibilityLevel - => _compatibilityLevel ?? DefaultCompatibilityLevel; + public virtual SqlServerEngineType EngineType + => _engineType; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual bool LegacyAzureSql + => _legacyAzureSql; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual int SqlServerCompatibilityLevel + => _sqlServerCompatibilityLevel ?? SqlServerDefaultCompatibilityLevel; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual int AzureSqlCompatibilityLevel + => _azureSqlCompatibilityLevel ?? AzureSqlDefaultCompatibilityLevel; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual int AzureSynapseCompatibilityLevel + => _azureSynapseCompatibilityLevel ?? AzureSynapseDefaultCompatibilityLevel; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual SqlServerOptionsExtension WithEngineType(SqlServerEngineType engineType) + { + if (EngineType != SqlServerEngineType.Unknown && EngineType != engineType) + { + throw new InvalidOperationException(SqlServerStrings.AlreadyConfiguredEngineType(engineType, EngineType)); + } + + var clone = (SqlServerOptionsExtension)Clone(); + + clone._engineType = engineType; + + return clone; + } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -89,8 +175,15 @@ public virtual int CompatibilityLevel /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual int? CompatibilityLevelWithoutDefault - => _compatibilityLevel; + public virtual SqlServerOptionsExtension WithLegacyAzureSql(bool enable) + { + var clone = (SqlServerOptionsExtension)Clone(); + + clone._engineType = SqlServerEngineType.SqlServer; + clone._legacyAzureSql = enable; + + return clone; + } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -98,11 +191,11 @@ public virtual int? CompatibilityLevelWithoutDefault /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual SqlServerOptionsExtension WithCompatibilityLevel(int? compatibilityLevel) + public virtual SqlServerOptionsExtension WithSqlServerCompatibilityLevel(int? sqlServerCompatibilityLevel) { var clone = (SqlServerOptionsExtension)Clone(); - clone._compatibilityLevel = compatibilityLevel; + clone._sqlServerCompatibilityLevel = sqlServerCompatibilityLevel; return clone; } @@ -113,8 +206,14 @@ public virtual SqlServerOptionsExtension WithCompatibilityLevel(int? compatibili /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual bool IsAzureSql - => _azureSql ?? false; + public virtual SqlServerOptionsExtension WithAzureSqlCompatibilityLevel(int? azureSqlCompatibilityLevel) + { + var clone = (SqlServerOptionsExtension)Clone(); + + clone._azureSqlCompatibilityLevel = azureSqlCompatibilityLevel; + + return clone; + } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -122,11 +221,11 @@ public virtual bool IsAzureSql /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual SqlServerOptionsExtension WithAzureSql(bool enable) + public virtual SqlServerOptionsExtension WithAzureSynapseCompatibilityLevel(int? azureSynapseCompatibilityLevel) { var clone = (SqlServerOptionsExtension)Clone(); - clone._azureSql = enable; + clone._azureSynapseCompatibilityLevel = _azureSynapseCompatibilityLevel; return clone; } @@ -134,12 +233,8 @@ public virtual SqlServerOptionsExtension WithAzureSql(bool enable) /// <inheritdoc /> public virtual IDbContextOptionsExtension ApplyDefaults(IDbContextOptions options) { - if (!IsAzureSql) - { - return this; - } - - if (ExecutionStrategyFactory == null) + if (ExecutionStrategyFactory == null + && (EngineType == SqlServerEngineType.AzureSql || EngineType == SqlServerEngineType.AzureSynapse || LegacyAzureSql)) { return WithExecutionStrategyFactory(c => new SqlServerRetryingExecutionStrategy(c)); } @@ -154,7 +249,35 @@ public virtual IDbContextOptionsExtension ApplyDefaults(IDbContextOptions option /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override void ApplyServices(IServiceCollection services) - => services.AddEntityFrameworkSqlServer(); + { + switch (_engineType) + { + case SqlServerEngineType.SqlServer: + services.AddEntityFrameworkSqlServer(); + break; + case SqlServerEngineType.AzureSql: + services.AddEntityFrameworkAzureSql(); + break; + case SqlServerEngineType.AzureSynapse: + services.AddEntityFrameworkAzureSynapse(); + break; + } + } + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public override void Validate(IDbContextOptions options) + { + base.Validate(options); + if (EngineType == SqlServerEngineType.Unknown) + { + throw new InvalidOperationException(SqlServerStrings.InvalidEngineType($"{nameof(SqlServerDbContextOptionsExtensions.UseSqlServer)}/{nameof(SqlServerDbContextOptionsExtensions.UseAzureSql)}/{nameof(SqlServerDbContextOptionsExtensions.UseAzureSynapse)}")); + } + } private sealed class ExtensionInfo : RelationalExtensionInfo { @@ -168,12 +291,12 @@ public ExtensionInfo(IDbContextOptionsExtension extension) private new SqlServerOptionsExtension Extension => (SqlServerOptionsExtension)base.Extension; - public override bool IsDatabaseProvider - => true; - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is ExtensionInfo otherInfo - && Extension.CompatibilityLevel == otherInfo.Extension.CompatibilityLevel; + && Extension.EngineType == otherInfo.Extension.EngineType + && Extension.SqlServerCompatibilityLevel == otherInfo.Extension.SqlServerCompatibilityLevel + && Extension.AzureSqlCompatibilityLevel == otherInfo.Extension.AzureSqlCompatibilityLevel + && Extension.AzureSynapseCompatibilityLevel == otherInfo.Extension.AzureSynapseCompatibilityLevel; public override string LogFragment { @@ -185,11 +308,39 @@ public override string LogFragment builder.Append(base.LogFragment); - if (Extension._compatibilityLevel is int compatibilityLevel) + builder + .Append("EngineType=") + .Append(Extension._engineType) + .Append(' '); + + if (Extension._legacyAzureSql) { builder - .Append("CompatibilityLevel=") - .Append(compatibilityLevel); + .Append("LegacyAzureSql=") + .Append(Extension._legacyAzureSql) + .Append(' '); + } + + if (Extension._sqlServerCompatibilityLevel != null) + { + builder + .Append("SqlServerCompatibilityLevel=") + .Append(Extension._sqlServerCompatibilityLevel) + .Append(' '); + } + if (Extension._azureSqlCompatibilityLevel != null) + { + builder + .Append("AzureSqlCompatibilityLevel=") + .Append(Extension._azureSqlCompatibilityLevel) + .Append(' '); + } + if (Extension._azureSynapseCompatibilityLevel != null) + { + builder + .Append("AzureSynapseCompatibilityLevel=") + .Append(Extension._azureSynapseCompatibilityLevel) + .Append(' '); } _logFragment = builder.ToString(); @@ -201,11 +352,20 @@ public override string LogFragment public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) { - debugInfo["SqlServer"] = "1"; + debugInfo["EngineType"] = Extension.EngineType.ToString(); + debugInfo["LegacyAzureSql"] = Extension.LegacyAzureSql.ToString(); - if (Extension.CompatibilityLevel is int compatibilityLevel) + if (Extension.SqlServerCompatibilityLevel is int sqlServerCompatibilityLevel) + { + debugInfo["SqlServerCompatibilityLevel"] = sqlServerCompatibilityLevel.ToString(); + } + if (Extension.AzureSqlCompatibilityLevel is int azureSqlCompatibilityLevel) + { + debugInfo["AzureSqlCompatibilityLevel"] = azureSqlCompatibilityLevel.ToString(); + } + if (Extension.AzureSynapseCompatibilityLevel is int azureSynapseCompatibilityLevel) { - debugInfo["CompatibilityLevel"] = compatibilityLevel.ToString(); + debugInfo["AzureSynapseCompatibilityLevel"] = azureSynapseCompatibilityLevel.ToString(); } } } diff --git a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerSingletonOptions.cs b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerSingletonOptions.cs index cba62d8cd69..3af5096042c 100644 --- a/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerSingletonOptions.cs +++ b/src/EFCore.SqlServer/Infrastructure/Internal/SqlServerSingletonOptions.cs @@ -17,7 +17,7 @@ public class SqlServerSingletonOptions : ISqlServerSingletonOptions /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual int CompatibilityLevel { get; private set; } = SqlServerOptionsExtension.DefaultCompatibilityLevel; + public virtual SqlServerEngineType EngineType { get; private set; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -25,7 +25,23 @@ public class SqlServerSingletonOptions : ISqlServerSingletonOptions /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> - public virtual int? CompatibilityLevelWithoutDefault { get; private set; } + public virtual int SqlServerCompatibilityLevel { get; private set; } = SqlServerOptionsExtension.SqlServerDefaultCompatibilityLevel; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual int AzureSqlCompatibilityLevel { get; private set; } = SqlServerOptionsExtension.AzureSqlDefaultCompatibilityLevel; + + /// <summary> + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// </summary> + public virtual int AzureSynapseCompatibilityLevel { get; private set; } = SqlServerOptionsExtension.AzureSynapseDefaultCompatibilityLevel; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -38,8 +54,10 @@ public virtual void Initialize(IDbContextOptions options) var sqlServerOptions = options.FindExtension<SqlServerOptionsExtension>(); if (sqlServerOptions != null) { - CompatibilityLevel = sqlServerOptions.CompatibilityLevel; - CompatibilityLevelWithoutDefault = sqlServerOptions.CompatibilityLevelWithoutDefault; + EngineType = sqlServerOptions.EngineType; + SqlServerCompatibilityLevel = sqlServerOptions.SqlServerCompatibilityLevel; + AzureSqlCompatibilityLevel = sqlServerOptions.AzureSqlCompatibilityLevel; + AzureSynapseCompatibilityLevel = sqlServerOptions.AzureSynapseCompatibilityLevel; } } @@ -51,16 +69,34 @@ public virtual void Initialize(IDbContextOptions options) /// </summary> public virtual void Validate(IDbContextOptions options) { - var sqlserverOptions = options.FindExtension<SqlServerOptionsExtension>(); + var sqlServerOptions = options.FindExtension<SqlServerOptionsExtension>(); - if (sqlserverOptions != null - && (CompatibilityLevelWithoutDefault != sqlserverOptions.CompatibilityLevelWithoutDefault - || CompatibilityLevel != sqlserverOptions.CompatibilityLevel)) + if (sqlServerOptions != null) { - throw new InvalidOperationException( - CoreStrings.SingletonOptionChanged( - nameof(SqlServerDbContextOptionsExtensions.UseSqlServer), - nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); + if (EngineType == SqlServerEngineType.SqlServer + && (EngineType != sqlServerOptions.EngineType || SqlServerCompatibilityLevel != sqlServerOptions.SqlServerCompatibilityLevel)) + { + throw new InvalidOperationException( + CoreStrings.SingletonOptionChanged( + $"{nameof(SqlServerDbContextOptionsExtensions.UseSqlServer)}", + nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); + } + if (EngineType == SqlServerEngineType.AzureSql + && (EngineType != sqlServerOptions.EngineType || AzureSqlCompatibilityLevel != sqlServerOptions.AzureSqlCompatibilityLevel)) + { + throw new InvalidOperationException( + CoreStrings.SingletonOptionChanged( + $"{nameof(SqlServerDbContextOptionsExtensions.UseAzureSql)}", + nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); + } + if (EngineType == SqlServerEngineType.AzureSynapse + && (EngineType != sqlServerOptions.EngineType || AzureSynapseCompatibilityLevel != sqlServerOptions.AzureSynapseCompatibilityLevel)) + { + throw new InvalidOperationException( + CoreStrings.SingletonOptionChanged( + $"{nameof(SqlServerDbContextOptionsExtensions.UseAzureSynapse)}", + nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); + } } } } diff --git a/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs b/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs index c3f74d0bd91..863dcac7192 100644 --- a/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs +++ b/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs @@ -6,10 +6,13 @@ namespace Microsoft.EntityFrameworkCore.Infrastructure; /// <summary> -/// Allows SQL Server specific configuration to be performed on <see cref="DbContextOptions" />. +/// Allows SQL Server, Azure SQL, Azure Synapse specific configuration to be performed on <see cref="DbContextOptions" />. /// </summary> /// <remarks> -/// Instances of this class are returned from a call to <see cref="O:SqlServerDbContextOptionsExtensions.UseSqlServer" /> +/// Instances of this class are returned from a call to +/// <see cref="O:SqlServerDbContextOptionsExtensions.UseSqlServer" />, +/// <see cref="O:SqlServerDbContextOptionsExtensions.UseAzureSql" />, +/// <see cref="O:SqlServerDbContextOptionsExtensions.UseAzureSynapse" /> /// and it is not designed to be directly constructed in your application code. /// </remarks> public class SqlServerDbContextOptionsBuilder @@ -29,7 +32,7 @@ public SqlServerDbContextOptionsBuilder(DbContextOptionsBuilder optionsBuilder) /// </summary> /// <remarks> /// <para> - /// This strategy is specifically tailored to SQL Server (including Azure SQL). It is pre-configured with + /// This strategy is specifically tailored to SQL Server, Azure SQL, Azure Synapse. It is pre-configured with /// error numbers for transient errors that can be retried. /// </para> /// <para> @@ -48,7 +51,7 @@ public virtual SqlServerDbContextOptionsBuilder EnableRetryOnFailure() /// </summary> /// <remarks> /// <para> - /// This strategy is specifically tailored to SQL Server (including Azure SQL). It is pre-configured with + /// This strategy is specifically tailored to SQL Server, Azure SQL, Azure Synapse. It is pre-configured with /// error numbers for transient errors that can be retried. /// </para> /// <para> @@ -67,7 +70,7 @@ public virtual SqlServerDbContextOptionsBuilder EnableRetryOnFailure(int maxRetr /// </summary> /// <remarks> /// <para> - /// This strategy is specifically tailored to SQL Server (including Azure SQL). It is pre-configured with + /// This strategy is specifically tailored to SQL Server, Azure SQL, Azure Synapse. It is pre-configured with /// error numbers for transient errors that can be retried. /// </para> /// <para> @@ -87,7 +90,7 @@ public virtual SqlServerDbContextOptionsBuilder EnableRetryOnFailure(ICollection /// </summary> /// <remarks> /// <para> - /// This strategy is specifically tailored to SQL Server (including Azure SQL). It is pre-configured with + /// This strategy is specifically tailored to SQL Server, Azure SQL, Azure Synapse. It is pre-configured with /// error numbers for transient errors that can be retried, but additional error numbers can also be supplied. /// </para> /// <para> @@ -116,14 +119,45 @@ public virtual SqlServerDbContextOptionsBuilder EnableRetryOnFailure( /// </see> /// for more information and examples. /// </remarks> - /// <param name="compatibilityLevel"><see langword="false" /> to have null resource</param> - public virtual SqlServerDbContextOptionsBuilder UseCompatibilityLevel(int compatibilityLevel) - => WithOption(e => e.WithCompatibilityLevel(compatibilityLevel)); + /// <param name="sqlServerCompatibilityLevel"><see langword="false" /> to have null resource</param> + public virtual SqlServerDbContextOptionsBuilder UseSqlServerCompatibilityLevel(int sqlServerCompatibilityLevel) + => WithOption(e => e.WithSqlServerCompatibilityLevel(sqlServerCompatibilityLevel)); /// <summary> /// Configures the context to use defaults optimized for Azure SQL, including retries on errors. /// </summary> /// <param name="enable">Whether the defaults should be enabled.</param> + [Obsolete("Use UseAzureSql instead of UseSqlServer with UseAzureSqlDefaults.")] public virtual SqlServerDbContextOptionsBuilder UseAzureSqlDefaults(bool enable = true) - => WithOption(e => e.WithAzureSql(enable)); + => WithOption(e => e.WithLegacyAzureSql(enable)); + + /// <summary> + /// Sets the Azure SQL compatibility level that EF Core will use when interacting with the database. This allows configuring EF + /// Core to work with older (or newer) versions of Azure SQL. Defaults to <c>160</c>. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-scoped-configuration-transact-sql"> + /// Azure SQL documentation on compatibility level + /// </see> + /// for more information and examples. + /// </remarks> + /// <param name="azureSqlCompatibilityLevel"><see langword="false" /> to have null resource</param> + public virtual SqlServerDbContextOptionsBuilder UseAzureSqlCompatibilityLevel(int azureSqlCompatibilityLevel) + => WithOption(e => e.WithAzureSqlCompatibilityLevel(azureSqlCompatibilityLevel)); + + /// <summary> + /// Sets the Azure Synapse compatibility level that EF Core will use when interacting with the database. This allows configuring EF + /// Core to work with older (or newer) versions of Azure Synapse. Defaults to <c>30</c>. + /// </summary> + /// <remarks> + /// See <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see>, and + /// <see href="https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-scoped-configuration-transact-sql"> + /// Azure Synapse documentation on compatibility level + /// </see> + /// for more information and examples. + /// </remarks> + /// <param name="azureSynapseCompatibilityLevel"><see langword="false" /> to have null resource</param> + public virtual SqlServerDbContextOptionsBuilder UseAzureSynapseCompatibilityLevel(int azureSynapseCompatibilityLevel) + => WithOption(e => e.WithAzureSynapseCompatibilityLevel(azureSynapseCompatibilityLevel)); } diff --git a/src/EFCore.SqlServer/Properties/SqlServerStrings.Designer.cs b/src/EFCore.SqlServer/Properties/SqlServerStrings.Designer.cs index 44bf55728a3..a2394614e7c 100644 --- a/src/EFCore.SqlServer/Properties/SqlServerStrings.Designer.cs +++ b/src/EFCore.SqlServer/Properties/SqlServerStrings.Designer.cs @@ -23,6 +23,14 @@ public static class SqlServerStrings private static readonly ResourceManager _resourceManager = new ResourceManager("Microsoft.EntityFrameworkCore.SqlServer.Properties.SqlServerStrings", typeof(SqlServerStrings).Assembly); + /// <summary> + /// Cannot configure engine type '{newEngineType}', because engine type was already configured as '{oldEngineType}'. + /// </summary> + public static string AlreadyConfiguredEngineType(object? newEngineType, object? oldEngineType) + => string.Format( + GetString("AlreadyConfiguredEngineType", nameof(newEngineType), nameof(oldEngineType)), + newEngineType, oldEngineType); + /// <summary> /// To change the IDENTITY property of a column, the column needs to be dropped and recreated. /// </summary> @@ -207,6 +215,14 @@ public static string IndexTableRequired public static string InvalidColumnNameForFreeText => GetString("InvalidColumnNameForFreeText"); + /// <summary> + /// Engine type was not configured. Use one of {methods} to configure it. + /// </summary> + public static string InvalidEngineType(object? methods) + => string.Format( + GetString("InvalidEngineType", nameof(methods)), + methods); + /// <summary> /// The specified table '{table}' is not in a valid format. Specify tables using the format '[schema].[table]'. /// </summary> diff --git a/src/EFCore.SqlServer/Properties/SqlServerStrings.resx b/src/EFCore.SqlServer/Properties/SqlServerStrings.resx index ba817be851a..5b734aebd29 100644 --- a/src/EFCore.SqlServer/Properties/SqlServerStrings.resx +++ b/src/EFCore.SqlServer/Properties/SqlServerStrings.resx @@ -117,6 +117,9 @@ <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> + <data name="AlreadyConfiguredEngineType" xml:space="preserve"> + <value>Cannot configure engine type '{newEngineType}', because engine type was already configured as '{oldEngineType}'.</value> + </data> <data name="AlterIdentityColumn" xml:space="preserve"> <value>To change the IDENTITY property of a column, the column needs to be dropped and recreated.</value> </data> @@ -189,6 +192,9 @@ <data name="InvalidColumnNameForFreeText" xml:space="preserve"> <value>The expression passed to the 'propertyReference' parameter of the 'FreeText' method is not a valid reference to a property. The expression must represent a reference to a full-text indexed property on the object referenced in the from clause: 'from e in context.Entities where EF.Functions.FreeText(e.SomeProperty, textToSearchFor) select e'</value> </data> + <data name="InvalidEngineType" xml:space="preserve"> + <value>Engine type was not configured. Use one of {methods} to configure it.</value> + </data> <data name="InvalidTableToIncludeInScaffolding" xml:space="preserve"> <value>The specified table '{table}' is not in a valid format. Specify tables using the format '[schema].[table]'.</value> </data> diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs index 994ee50a4f8..67c7726df4a 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs @@ -19,7 +19,7 @@ public class SqlServerQuerySqlGenerator : QuerySqlGenerator { private readonly IRelationalTypeMappingSource _typeMappingSource; private readonly ISqlGenerationHelper _sqlGenerationHelper; - private readonly int _sqlServerCompatibilityLevel; + private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions; private bool _withinTable; @@ -37,7 +37,7 @@ public SqlServerQuerySqlGenerator( { _typeMappingSource = typeMappingSource; _sqlGenerationHelper = dependencies.SqlGenerationHelper; - _sqlServerCompatibilityLevel = sqlServerSingletonOptions.CompatibilityLevel; + _sqlServerSingletonOptions = sqlServerSingletonOptions; } /// <summary> @@ -520,18 +520,26 @@ private void GenerateJsonPath(IReadOnlyList<PathSegment> path) { Visit(arrayIndex); } - else if (_sqlServerCompatibilityLevel >= 140) - { - Sql.Append("' + CAST("); - Visit(arrayIndex); - Sql.Append(" AS "); - Sql.Append(_typeMappingSource.GetMapping(typeof(string)).StoreType); - Sql.Append(") + '"); - } else { - throw new InvalidOperationException( - SqlServerStrings.JsonValuePathExpressionsNotSupported(_sqlServerCompatibilityLevel)); + switch (_sqlServerSingletonOptions.EngineType) + { + case SqlServerEngineType.SqlServer when _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 140: + case SqlServerEngineType.AzureSql when _sqlServerSingletonOptions.AzureSqlCompatibilityLevel >= 140: + case SqlServerEngineType.AzureSynapse: + Sql.Append("' + CAST("); + Visit(arrayIndex); + Sql.Append(" AS "); + Sql.Append(_typeMappingSource.GetMapping(typeof(string)).StoreType); + Sql.Append(") + '"); + break; + case SqlServerEngineType.SqlServer: + throw new InvalidOperationException( + SqlServerStrings.JsonValuePathExpressionsNotSupported(_sqlServerSingletonOptions.SqlServerCompatibilityLevel)); + case SqlServerEngineType.AzureSql: + throw new InvalidOperationException( + SqlServerStrings.JsonValuePathExpressionsNotSupported(_sqlServerSingletonOptions.AzureSqlCompatibilityLevel)); + } } Sql.Append("]"); diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs index 9ce6e9d5425..c48965fc33f 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs @@ -20,7 +20,7 @@ public class SqlServerQueryableMethodTranslatingExpressionVisitor : RelationalQu private readonly SqlServerQueryCompilationContext _queryCompilationContext; private readonly IRelationalTypeMappingSource _typeMappingSource; private readonly ISqlExpressionFactory _sqlExpressionFactory; - private readonly int _sqlServerCompatibilityLevel; + private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions; private RelationalTypeMapping? _nvarcharMaxTypeMapping; @@ -40,8 +40,7 @@ public SqlServerQueryableMethodTranslatingExpressionVisitor( _queryCompilationContext = queryCompilationContext; _typeMappingSource = relationalDependencies.TypeMappingSource; _sqlExpressionFactory = relationalDependencies.SqlExpressionFactory; - - _sqlServerCompatibilityLevel = sqlServerSingletonOptions.CompatibilityLevel; + _sqlServerSingletonOptions = sqlServerSingletonOptions; } /// <summary> @@ -57,8 +56,7 @@ protected SqlServerQueryableMethodTranslatingExpressionVisitor( _queryCompilationContext = parentVisitor._queryCompilationContext; _typeMappingSource = parentVisitor._typeMappingSource; _sqlExpressionFactory = parentVisitor._sqlExpressionFactory; - - _sqlServerCompatibilityLevel = parentVisitor._sqlServerCompatibilityLevel; + _sqlServerSingletonOptions = parentVisitor._sqlServerSingletonOptions; } /// <summary> @@ -131,9 +129,15 @@ protected override Expression VisitExtension(Expression extensionExpression) IProperty? property, string tableAlias) { - if (_sqlServerCompatibilityLevel < 130) + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer && _sqlServerSingletonOptions.SqlServerCompatibilityLevel < 130) + { + AddTranslationErrorDetails(SqlServerStrings.CompatibilityLevelTooLowForScalarCollections(_sqlServerSingletonOptions.SqlServerCompatibilityLevel)); + + return null; + } + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel < 130) { - AddTranslationErrorDetails(SqlServerStrings.CompatibilityLevelTooLowForScalarCollections(_sqlServerCompatibilityLevel)); + AddTranslationErrorDetails(SqlServerStrings.CompatibilityLevelTooLowForScalarCollections(_sqlServerSingletonOptions.AzureSqlCompatibilityLevel)); return null; } diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlExpressionFactory.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlExpressionFactory.cs index df768474719..f84f3e1abb8 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlExpressionFactory.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlExpressionFactory.cs @@ -16,7 +16,6 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal; public class SqlServerSqlExpressionFactory : SqlExpressionFactory { private readonly IRelationalTypeMappingSource _typeMappingSource; - private readonly int _sqlServerCompatibilityLevel; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -25,12 +24,10 @@ public class SqlServerSqlExpressionFactory : SqlExpressionFactory /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SqlServerSqlExpressionFactory( - SqlExpressionFactoryDependencies dependencies, - ISqlServerSingletonOptions sqlServerSingletonOptions) + SqlExpressionFactoryDependencies dependencies) : base(dependencies) { _typeMappingSource = dependencies.TypeMappingSource; - _sqlServerCompatibilityLevel = sqlServerSingletonOptions.CompatibilityLevel; } /// <summary> diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs index 677fe36f4ed..402b615a13e 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs @@ -21,7 +21,7 @@ public class SqlServerSqlTranslatingExpressionVisitor : RelationalSqlTranslating private readonly SqlServerQueryCompilationContext _queryCompilationContext; private readonly ISqlExpressionFactory _sqlExpressionFactory; private readonly IRelationalTypeMappingSource _typeMappingSource; - private readonly int _sqlServerCompatibilityLevel; + private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions; private static readonly HashSet<string> DateTimeDataTypes = @@ -87,7 +87,7 @@ public SqlServerSqlTranslatingExpressionVisitor( _queryCompilationContext = queryCompilationContext; _sqlExpressionFactory = dependencies.SqlExpressionFactory; _typeMappingSource = dependencies.TypeMappingSource; - _sqlServerCompatibilityLevel = sqlServerSingletonOptions.CompatibilityLevel; + _sqlServerSingletonOptions = sqlServerSingletonOptions; } /// <summary> @@ -211,7 +211,9 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp // Translate non-aggregate string.Join to CONCAT_WS (for aggregate string.Join, see SqlServerStringAggregateMethodTranslator) if (method == StringJoinMethodInfo && methodCallExpression.Arguments[1] is NewArrayExpression newArrayExpression - && _sqlServerCompatibilityLevel >= 140) + && ((_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer && _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 140) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel >= 140) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSynapse))) { if (TranslationFailed(methodCallExpression.Arguments[0], Visit(methodCallExpression.Arguments[0]), out var delimiter)) { @@ -533,7 +535,13 @@ private static string EscapeLikePattern(string pattern) public override SqlExpression? GenerateGreatest(IReadOnlyList<SqlExpression> expressions, Type resultType) { // Docs: https://learn.microsoft.com/sql/t-sql/functions/logical-functions-greatest-transact-sql - if (_sqlServerCompatibilityLevel < 160) + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer + && _sqlServerSingletonOptions.SqlServerCompatibilityLevel < 160) + { + return null; + } + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql + && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel < 160) { return null; } @@ -555,7 +563,13 @@ private static string EscapeLikePattern(string pattern) public override SqlExpression? GenerateLeast(IReadOnlyList<SqlExpression> expressions, Type resultType) { // Docs: https://learn.microsoft.com/sql/t-sql/functions/logical-functions-least-transact-sql - if (_sqlServerCompatibilityLevel < 160) + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer + && _sqlServerSingletonOptions.SqlServerCompatibilityLevel < 160) + { + return null; + } + if (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql + && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel < 160) { return null; } diff --git a/src/EFCore.SqlServer/Query/Internal/Translators/SqlServerStringMethodTranslator.cs b/src/EFCore.SqlServer/Query/Internal/Translators/SqlServerStringMethodTranslator.cs index 49064a8293d..f8dd1a44713 100644 --- a/src/EFCore.SqlServer/Query/Internal/Translators/SqlServerStringMethodTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/Translators/SqlServerStringMethodTranslator.cs @@ -202,7 +202,9 @@ public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactor // an overload that accepts the characters to trim. if (method == TrimStartMethodInfoWithoutArgs || (method == TrimStartMethodInfoWithCharArrayArg && arguments[0] is SqlConstantExpression { Value: char[] { Length: 0 } }) - || (_sqlServerSingletonOptions.CompatibilityLevel >= 160 + || (((_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer && _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 160) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel >= 160) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSynapse)) && (method == TrimStartMethodInfoWithCharArg || method == TrimStartMethodInfoWithCharArrayArg))) { return ProcessTrimStartEnd(instance, arguments, "LTRIM"); @@ -210,7 +212,9 @@ public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactor if (method == TrimEndMethodInfoWithoutArgs || (method == TrimEndMethodInfoWithCharArrayArg && arguments[0] is SqlConstantExpression { Value: char[] { Length: 0 } }) - || (_sqlServerSingletonOptions.CompatibilityLevel >= 160 + || (((_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer && _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 160) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel >= 160) + || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSynapse)) && (method == TrimEndMethodInfoWithCharArg || method == TrimEndMethodInfoWithCharArrayArg))) { return ProcessTrimStartEnd(instance, arguments, "RTRIM");
diff --git a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs index 23375b644a6..68e7662ccef 100644 --- a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs @@ -270,7 +270,7 @@ public void GetContextInfo_returns_correct_info() Assert.Equal("Test", info.DatabaseName); Assert.Equal(@"(localdb)\mssqllocaldb", info.DataSource); - Assert.Equal("None", info.Options); + Assert.Equal("EngineType=SqlServer", info.Options); Assert.Equal("Microsoft.EntityFrameworkCore.SqlServer", info.ProviderName); } @@ -291,7 +291,7 @@ public void GetContextInfo_does_not_throw_if_DbConnection_cannot_be_created() Assert.Equal(DesignStrings.BadConnection(expected.Message), info.DatabaseName); Assert.Equal(DesignStrings.BadConnection(expected.Message), info.DataSource); - Assert.Equal("None", info.Options); + Assert.Equal("EngineType=SqlServer", info.Options); Assert.Equal("Microsoft.EntityFrameworkCore.SqlServer", info.ProviderName); } diff --git a/test/EFCore.SqlServer.FunctionalTests/LoggingSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/LoggingSqlServerTest.cs index c73b6d512ae..64c82f18cdb 100644 --- a/test/EFCore.SqlServer.FunctionalTests/LoggingSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/LoggingSqlServerTest.cs @@ -61,4 +61,7 @@ protected override string ProviderName protected override string ProviderVersion => typeof(SqlServerOptionsExtension).Assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; + + protected override string DefaultOptions + => "EngineType=SqlServer "; } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServer160Test.cs index ee806b4e0ab..c9f9b88881b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServer160Test.cs @@ -4904,6 +4904,6 @@ protected override string StoreName => "ComplexNavigations160"; public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(b => b.UseCompatibilityLevel(160)); + => base.AddOptions(builder).UseSqlServer(b => b.UseSqlServerCompatibilityLevel(160)); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsSharedTypeQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsSharedTypeQuerySqlServer160Test.cs index 83800b92c3b..d58c957f986 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsSharedTypeQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsSharedTypeQuerySqlServer160Test.cs @@ -8526,6 +8526,6 @@ protected override string StoreName => "ComplexNavigationsOwned160"; public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(b => b.UseCompatibilityLevel(160)); + => base.AddOptions(builder).UseSqlServer(b => b.UseSqlServerCompatibilityLevel(160)); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServer160Test.cs index c41575cf0ba..faaf2217203 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindDbFunctionsQuerySqlServer160Test.cs @@ -1467,6 +1467,6 @@ private void AssertSql(params string[] expected) public class Fixture160 : NorthwindQuerySqlServerFixture<NoopModelCustomizer> { public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(b => b.UseCompatibilityLevel(160)); + => base.AddOptions(builder).UseSqlServer(b => b.UseSqlServerCompatibilityLevel(160)); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindFunctionsQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindFunctionsQuerySqlServer160Test.cs index 555f1733719..6f0172d20f0 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindFunctionsQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindFunctionsQuerySqlServer160Test.cs @@ -3008,6 +3008,6 @@ protected override void ClearLog() public class Fixture160 : NorthwindQuerySqlServerFixture<NoopModelCustomizer> { public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(b => b.UseCompatibilityLevel(160)); + => base.AddOptions(builder).UseSqlServer(b => b.UseSqlServerCompatibilityLevel(160)); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrecompiledSqlPregenerationQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrecompiledSqlPregenerationQuerySqlServerTest.cs index b187615aee8..93022636239 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrecompiledSqlPregenerationQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrecompiledSqlPregenerationQuerySqlServerTest.cs @@ -258,7 +258,7 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build // TODO: Figure out if there's a nice way to continue using the retrying strategy var sqlServerOptionsBuilder = new SqlServerDbContextOptionsBuilder(builder); sqlServerOptionsBuilder - .UseCompatibilityLevel(120) + .UseSqlServerCompatibilityLevel(120) .ExecutionStrategy(d => new NonRetryingExecutionStrategy(d)); return builder; } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs index 5877a8c7c14..92b57f0d64d 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs @@ -1119,6 +1119,6 @@ protected override ITestStoreFactory TestStoreFactory // Compatibility level 120 (SQL Server 2014) doesn't support OPENJSON public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(o => o.UseCompatibilityLevel(120)); + => base.AddOptions(builder).UseSqlServer(o => o.UseSqlServerCompatibilityLevel(120)); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs index 09878bccedd..6d0e9f7bf9a 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs @@ -1991,7 +1991,7 @@ protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) - => base.AddOptions(builder).UseSqlServer(b => b.UseCompatibilityLevel(160)); + => base.AddOptions(builder).UseSqlServer(b => b.UseSqlServerCompatibilityLevel(160)); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs index d438844b951..26c498706f9 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs @@ -424,16 +424,16 @@ public class AzureSqlDatabase [InlineData(true)] [InlineData(false)] [ConditionalTheory] - public void Retry_on_failure_not_enabled_by_default_on_Azure_SQL(bool configured) + public void Retry_on_failure_not_enabled_by_default_on_Azure_SQL(bool useAzure) { - using var context = new NorthwindContext(configured); + using var context = new NorthwindContext(useAzure); Assert.IsType<SqlServerExecutionStrategy>(context.Database.CreateExecutionStrategy()); } - private class NorthwindContext(bool configured) : DbContext + private class NorthwindContext(bool useAzure) : DbContext { - private readonly bool _azureConfigured = configured; + private readonly bool _useAzure = useAzure; public DbSet<Customer> Customers { get; set; } @@ -444,9 +444,11 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) @"Server=test.database.windows.net:4040;Database=Test;ConnectRetryCount=0", a => { - if (_azureConfigured) + if (_useAzure) { +#pragma warning disable CS0618 // Type or member is obsolete a.UseAzureSqlDefaults(false); +#pragma warning restore CS0618 // Type or member is obsolete } }); @@ -460,10 +462,10 @@ public class NonDefaultAzureSqlDatabase [InlineData(true)] [InlineData(false)] [ConditionalTheory] - public void Retry_on_failure_enabled_if_Azure_SQL_configured(bool configured) + public void Retry_on_failure_enabled_if_Azure_SQL_configured(bool useAzure) { - using var context = new NorthwindContext(configured); - if (configured) + using var context = new NorthwindContext(useAzure); + if (useAzure) { Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); } @@ -473,24 +475,302 @@ public void Retry_on_failure_enabled_if_Azure_SQL_configured(bool configured) } } - private class NorthwindContext(bool azure) : DbContext + private class NorthwindContext(bool useAzure) : DbContext { - private readonly bool _isAzure = azure; + private readonly bool _useAzure = useAzure; public DbSet<Customer> Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder + { + optionsBuilder + .EnableServiceProviderCaching(false); + if (_useAzure) + { + optionsBuilder + .UseAzureSql(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); + } + else + { + optionsBuilder + .UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); + } + } + } + } + + public class ExplicitExecutionStrategies_SqlServer + { + [InlineData(true)] + [InlineData(false)] + [ConditionalTheory] + public void Retry_strategy_properly_handled(bool before) + { + using var context = new NorthwindContext(before); + if (before) + { + Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + else + { + Assert.IsType<DummyExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + } + + private class NorthwindContext(bool before) : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder .EnableServiceProviderCaching(false) - .UseSqlServer( - SqlServerNorthwindTestStoreFactory.NorthwindConnectionString, - a => + .UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString, + b => { - if (_isAzure) + if (before) { - a.UseAzureSqlDefaults(); + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + b.EnableRetryOnFailure(); + if (!before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); } }); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + public class ExplicitExecutionStrategies_AzureSql + { + [InlineData(true)] + [InlineData(false)] + [ConditionalTheory] + public void Retry_strategy_properly_handled(bool before) + { + using var context = new NorthwindContext(before); + if (before) + { + Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + else + { + Assert.IsType<DummyExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + } + + private class NorthwindContext(bool before) : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .EnableServiceProviderCaching(false) + .UseAzureSql(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString, + b => + { + if (before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + b.EnableRetryOnFailure(); + if (!before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + }); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + public class ExplicitExecutionStrategies_AzureSynapse + { + [InlineData(true)] + [InlineData(false)] + [ConditionalTheory] + public void Retry_strategy_properly_handled(bool before) + { + using var context = new NorthwindContext(before); + if (before) + { + Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + else + { + Assert.IsType<DummyExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + } + + private class NorthwindContext(bool before) : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .EnableServiceProviderCaching(false) + .UseAzureSynapse(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString, + b => + { + if (before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + b.EnableRetryOnFailure(); + if (!before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + }); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + public class ExplicitExecutionStrategies_ConfigureSqlEngine_AzureSql + { + [InlineData(true)] + [InlineData(false)] + [ConditionalTheory] + public void Retry_strategy_properly_handled(bool before) + { + using var context = new NorthwindContext(before); + if (before) + { + Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + else + { + Assert.IsType<DummyExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + } + + private class NorthwindContext(bool before) : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .EnableServiceProviderCaching(false) + .ConfigureSqlEngine( + b => + { + if (before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + b.EnableRetryOnFailure(); + if (!before) + { + b.ExecutionStrategy(_ => new DummyExecutionStrategy()); + } + }) + .UseAzureSql(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + + public class ConfigureTwoEngines + { + [Fact] + public void Throws_when_two_engines_used() + { + using var context = new NorthwindContext(); + Assert.Throws<InvalidOperationException>(() => { _ = context.Model; }); + } + + private class NorthwindContext : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .EnableServiceProviderCaching(false) + .UseSqlServer() + .UseAzureSql(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + + public class NoEngineConfigured + { + [Fact] + public void Throws_when_no_engine_configured() + { + using var context = new NorthwindContext(); + Assert.Throws<InvalidOperationException>(() => { _ = context.Model; }); + } + + private class NorthwindContext : DbContext + { + public DbSet<Customer> Customers { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .EnableServiceProviderCaching(false) + .ConfigureSqlEngine(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); + } + } + + public class AddConfigureDbContext + { + [Fact] + public void Does_not_throw_for_Add_Configure() + { + using var scope = new ServiceCollection() + .AddDbContext<NorthwindContext>(b => b.UseSqlServer()) + .ConfigureDbContext<NorthwindContext>(b => b.ConfigureSqlEngine(o => o.EnableRetryOnFailure())) + .BuildServiceProvider(validateScopes: true) + .CreateScope(); + + var serviceProvider = scope.ServiceProvider; + + var exception = Record.Exception(serviceProvider.GetRequiredService<NorthwindContext>); + Assert.Null(exception); + } + + [Fact] + public void Proper_execution_strategy() + { + using var scope = new ServiceCollection() + .AddDbContext<NorthwindContext>(b => b.UseSqlServer()) + .ConfigureDbContext<NorthwindContext>(b => b.ConfigureSqlEngine(o => o.EnableRetryOnFailure())) + .BuildServiceProvider(validateScopes: true) + .CreateScope(); + + var serviceProvider = scope.ServiceProvider; + + var context = serviceProvider.GetRequiredService<NorthwindContext>(); + Assert.IsType<SqlServerRetryingExecutionStrategy>(context.Database.CreateExecutionStrategy()); + } + + private class NorthwindContext : DbContext + { + public DbSet<Customer> Customers { get; set; } + + public NorthwindContext(DbContextOptions options) + : base(options) + { } protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureModel(modelBuilder); @@ -516,4 +796,12 @@ private static void ConfigureModel(ModelBuilder builder) b.HasKey(c => c.CustomerID); b.ToTable("Customers"); }); + + private class DummyExecutionStrategy : IExecutionStrategy + { + public bool RetriesOnFailure => true; + + public TResult Execute<TState, TResult>(TState state, Func<DbContext, TState, TResult> operation, Func<DbContext, TState, ExecutionResult<TResult>> verifySucceeded) => throw new NotImplementedException(); + public Task<TResult> ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken = default) => throw new NotImplementedException(); + } } diff --git a/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs b/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs index e1de681c655..38db2102555 100644 --- a/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs +++ b/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs @@ -52,13 +52,16 @@ public static IModel Instance } [ConditionalFact] - public void ApplyServices_adds_SQL_server_services() + public void ApplyServices_adds_correct_services() { var services = new ServiceCollection(); - new SqlServerOptionsExtension().ApplyServices(services); + new SqlServerOptionsExtension() + .WithEngineType(SqlServerEngineType.SqlServer) + .ApplyServices(services); Assert.Contains(services, sd => sd.ServiceType == typeof(ISqlServerConnection)); + Assert.Contains(services, sd => sd.ServiceType == typeof(ISqlServerSingletonOptions)); } private class ChangedRowNumberContext(bool setInternalServiceProvider) : DbContext
Introduce UseAzureSql/UseAzureSynapse as alternatives to UseSqlServer We're increasingly seeing T-SQL divergence, where certain features are not available e.g. on Azure Synapse (e.g. #33555), and some features are only available Azure SQL (e.g. the new JSON type, the new vector search capabilities). To account for this divergence, we'll allow users to specify which database is being targeted by providing UseAzureSql/UseAzureSynapse alternatives to UseSqlServer. Note: we'd need to duplicate all current variants of UseSqlServer.
So given the following engine editions: 2 = Standard (For Standard, Web, and Business Intelligence.) 3 = Enterprise (For Evaluation, Developer, and Enterprise editions.) 4 = Express (For Express, Express with Tools, and Express with Advanced Services) 5 = SQL Database 6 = Azure Synapse Analytics 8 = Azure SQL Managed Instance 9 = Azure SQL Edge (For all editions of Azure SQL Edge) 11 = Azure Synapse serverless SQL pool **UseSqlServer: 2, 3, 4, 8 (5, 9)** **UseAzureSql: 5, 8** (8 depending on [Update policy](https://learn.microsoft.com/en-us/azure/azure-sql/managed-instance/update-policy?view=azuresql&tabs=azure-portal) - default is SQL Server 2022 compatibility) **UseAzureSynapse: 6, 11** @ErikEJ are you suggesting we auto-detect based on the engine queried from the database, or something similar? Or allow the user to specify the engine edition directly? @roji No - just trying to clarify for myself (and maybe others) what the options will actually mean @roji Just was made aware of [this](https://learn.microsoft.com/en-us/azure/azure-sql/managed-instance/update-policy?view=azuresql&tabs=azure-portal), affecting Azure SQL Managed Instance @ErikEJ interesting, thanks - I wasn't aware of this... It seems to optionally bring SQL Managed Instance closer to SQL Azure in terms of the engine/features. Do you see this as changing the above proposal? @roji Yeah, just got this in a newsletter, seems like a brand new thing. It does not affect the above proposal, but I have made some small opdates to my list above. Removing the milestone and adding `needs-design` to revisit if we are doing the right thing here, and what the mappings should be. Thank you so much for working on this issue - it will be very helpful to users of Azure Synapse like me! The lack of support in Synapse for `ESCAPE` (in `LIKE` clauses) and `OFFSET` (for paging) make it harder to use EF for this particular variant of T-SQL.
2024-06-21T11:53:29Z
0.1
[]
[]