Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Support for ObservableCollection<T> and Collection<T> Range APIs from dotnet/runtime #6097

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

SkyeHoefling
Copy link

Fixes #1887

Description

Removes the CollectionChanged exceptions from ListCollectionVIew when the record count is not equal to 1. This PR is required to support dotnet/runtime#65101.

The change to dotnet/runtime as originally attempted in 2019 and it was discovered during preview builds that it broke WPF. I have spoken with both the .NET Team and the WPF Team and both teams are ready to accept this change. See dotnet/runtime#65101 for a complete detail of history and API changes.

Customer Impact

If this change is accepted it will allow developers to use AddRange() and RemoveRange() APIs on their ObservableCollection<T>. This will reduce the call stack from event invocations by N number of items that are being added to the collection. If an application is adding 5000 items to an ObservableCollection<T> currently it will invoke 5000 events, with this change it will only invoke 1 event.

If this change is not accepted, then dotnet/runtime#65101 will not be accepted as it will break just about every WPF application that uses ListCollectionView.

Regression

N/A

Testing

I had problems running the wpf project locally and wasn't able to test as I would have liked to. I wanted to submit this PR and discuss with the community if someone could give me some help testing or instructions. I think the testing is giving me issues because I need a custom build of .NET 7 and the SDK project, then I need a custom build of WPF and finally will be able to test.

Risk

As far as I understand this PR mitigates the risk of breaking changes from dotnet/runtime#65101. I think it is important once we get a build we can test with to use some large WPF projects as a test solution like the NuGet Package Explorer. That was the project that originally caught the issue from the first attempt in 2019

…ge() and RemoveRange() apis for ObservableCollection
@SkyeHoefling SkyeHoefling requested a review from a team as a code owner February 9, 2022 20:43
@ghost ghost added the PR metadata: Label to tag PRs, to facilitate with triage label Feb 9, 2022
@ghost ghost requested review from fabiant3, ryalanms and SamBent February 9, 2022 20:43
Copy link
Contributor

@SamBent SamBent left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All this does is remove the immediate NotSupportedException when ListCollectionView gets a range event. It doesn't add support for those events. To do that you'd need to

  • add logic to ProcessCollectionChanged to do the right thing for range events (currently it assumes one item)
  • add logic to methods it calls that also assume one item
  • make similar changes to all handlers of CollectionChanged (there are dozens)
  • make changes to secondary events and virtuals, e.g. ItemsControl.OnItemsChanged, ItemContainerGenerator.ItemsChanged
  • track the range event through transformations like shaping (sorting/filtering/grouping), live-shaping, cross-thread notifications, etc.

Without that work, range events will get handled by logic that isn't prepared for them, resulting in unexpected behavior - crashes, data loss or corruption, incorrect/undesired layout, etc. Better to throw NotSupportedException up front.

(Doing all that work is a huge project - probably months of work.)

@SamBent SamBent added the * NO MERGE * metadata: The PR is not ready for merge yet (see discussion for detailed reasons) label Feb 9, 2022
@airbreather
Copy link

To do that you'd need to

(lots of stuff)

Without that work, range events will get handled by logic that isn't prepared for them, resulting in unexpected behavior - crashes, data loss or corruption, incorrect/undesired layout, etc. Better to throw NotSupportedException up front.

(Doing all that work is a huge project - probably months of work.)

From my perspective as an outsider, I'm only really interested (near-term) in seeing the dotnet/runtime PR get unblocked. I'd really like to start using efficient versions of the "Range" APIs in other situations (Collection<T> is a really good abstraction for more than just WPF, of course). I get that this change, as it stands, cannot remove the blocker, and I completely support that decision.

But is a "full, proper" implementation really the only way to remove the blocker? Our .NET Framework 4.8 application has been using a subclass of ObservableCollection<T> that rewrites bulk CollectionChanged events as Reset for over a decade now, and I have yet to observe even the slightest imperfection in the behavior of the system (and believe me, we have pushed WPF to places that it was never designed to go, with black magic wizardry that dates back at least as early as .NET Framework 4.0, and I think even going back to .NET Framework 3.5 before I joined that team).

So this may be a bit of a naïve question, but would it not be sufficient to resolve this issue by doing something similar on the receiving end in ListCollectionView itself? "I got a change notification for multiple items, so I will pretend that it was a Reset"?

The main* downside that I can see to doing it that way is that ListCollectionView itself is INotifyCollectionChanged, and so if ListCollectionView starts raising Reset events for Range operations today, then that means "full, proper" support for Range operations tomorrow could have observable side-effects on external code that's written to expect a Reset event.

If that's the main downside to that idea, then I imagine that the "full, proper" support could include AppContext switch to bring back the Reset behavior to allow those applications to keep working?

If there's something more to it, then what other reasons might there be not to take that lighter approach?

*I can also concede that it would cause the overall system to show suboptimal performance in many important situations, such as when an AddRange adds 2 items to a 1,000,000-item list, especially when the ListCollectionView is doing live shaping and both items would be live-filtered out anyway.

Still, though, as annoying as it will be for someone who will find themselves in this situation, it would only affect new code, where some people (at worst) have to use a wrapper collection that modifies various calls to work around ListCollectionView's imperfections... hey, wait a second, that sounds familiar...

@robertmclaws
Copy link

Yes, Microsoft, please make this happen!

I have been trying to get this fixed since August 13, 2016. Throwing exceptions in an event handler is a really bad decision that should have never been allowed to happen. That single decision has been blocking people from making the right architectural decisions for over 15 years. And it has kept WPF from being the amazing platform it was supposed to be.

People know that major .NET version releases break things... that's what SemVer is for. We will fix our own applications... and we'll help fix the runtime too.

@SamBent We don't know each other, but I have been in the .NET world since the .NET 1.0 preview. I am asking you, one .NET expert to another, please stop allowing perfect to be the enemy of good, and unblock us. Once this fix is in, we have several people that will work through the codebase and make the required improvements. It will not take months, it will take weeks. We can get it into the .NET 7 release if you just let us. 🙏🙏🙏

@robertmclaws
Copy link

Also, please see this comment: dotnet/runtime#18087 (comment) MAUI is already working to get it integrated in the .NET 7 timeframe.

@weltkante
Copy link

weltkante commented May 4, 2022

This PR does not unblock the dotnet runtime changes. Without WPF handling ranges properly, as soon as the dotnet runtime changes go in, WPF will still be regressed and it'll (probably) have to be rolled back again.

The most you can hope to achieve with this PR is to hope that it "slips through the cracks" and nobody cares about fixing WPF anymore.

@airbreather
Copy link

airbreather commented May 4, 2022

This PR does not unblock the dotnet runtime changes.

But if the code were to be modified to address the issues that were identified in the review feedback further up the page, then it would, wouldn't it? If so, then something similar could be said about roughly any PR that doesn't pass an initial review.

@legistek
Copy link

legistek commented May 4, 2022

No offense intended to anyone, but this is a terrible idea to implement this as is. As was pointed out both here and at dotnet/runtime#18087 (comment), the issue that forced the original PR adding range support to Collection to be reverted will still exist and arguably be worse if this change is implemented.

The problem was that the methods (AddRange, etc.) being added to Collection were taking precedence over peoples' custom Collection and ObservableCollection extension methods (a very common workaround) of the same name.. In peoples' custom methods, they used Reset or just iterated - either way being WPF-safe - whereas the methods being proposed for Collection did not.

The same thing will happen again if you go down this route, the only difference being the exception will not throw. However, peoples' applications will still break because - at best - the notifications won't get handled properly. DataGrids and the like will add only one row, where multiple were intended, for example. Again, best case scenario.

@SamBent (who obviously knows WPF better than anyone else here) is 100% right that this absolutely will not work without a complete overhaul of how WPF handles INCC events. This is not about the perfect being the enemy of the good. This is about not breaking 20 years of legacy code. Please do not attempt this.

Adding the full range of INCC event handling to a built-in class is a worthy goal but neither Collection, nor ObservableCollection, nor certainly WPF itself, need to be messed with in order to do this. Make a new ObservableList class, make sure the modern frameworks support it, and make sure it warns the hell out of you if you try to use it with WPF.

@weltkante
Copy link

weltkante commented May 4, 2022

This PR does not unblock the dotnet runtime changes.

But if the code were to be modified to address the issues that were identified in the review feedback further up the page, then it would, wouldn't it? If so, then something similar could be said about roughly any PR that doesn't pass an initial review.

Well, yes, if you turn it into a PR that does something entirely else, namely implement the missing support, then yes that will solve the problem. My comment was just highlighting, that the PR does not attempt that, thus is not unblocking this issue. As far as this discussion is concerned the PR could as well be empty - all work is yet to be done.

@airbreather
Copy link

this absolutely will not work without a complete overhaul of how WPF handles INCC events. This is not about the perfect being the enemy of the good. This is about not breaking 20 years of legacy code. Please do not attempt this.

Can you please explain the flaw in my comment above, #6097 (comment)? As you say, a common workaround is to have the sender raise the INCC event with Reset (when it really wants to do something unsupported), so it seems to follow that it wouldn't be fundamentally broken for the receiver to act as if the event was raised with Reset in those cases, no?

@robertmclaws
Copy link

@legistek Creating an N+1 problem is not the solution here. Fixing WPF to do the right thing in a compatible way is the solution. You CAN fix WPF to maintain compatibility in the final .NET 7 release... but to do that you need to remove this exception so the people working to fix it can be unblocked.

@legistek
Copy link

legistek commented May 4, 2022

Hey @airbreather I thought your idea was really interesting on its own. All the potential downsides I can think of are things you allude to. Perhaps the biggest issue that would concern me is that depending on the size of the existing collection vs. the size of what's being added or removed, either iteration or reset could be horribly inefficient. Each developer who's faced this and made their own AddRange extension has had to decide which one to use for their unique situation.

But the real problem lies with #18087. If AddRange were to be re-added to Collection and peoples' extension methods were again to get usurped, then we're still forcing new and untested behavior - without warning - on code that was previously written and presumably optimized based on different assumptions. Will #18087 plus your idea break applications as badly as this PR? Probably not, but I could absolutely see it causing huge efficiency headaches, excessive database querying, etc. , if applications that were previously using one method (iteration vs. reset) suddenly and inadvertently wind up using the other.

On the other hand, if we instead had a totally opt-in ObservableList class, then your idea poses very little risk to legacy code and could indeed be a good interim step prior to full INCC support in WPF if that's eventually done. Either way, what's crucial is that we be able to choose whether to opt into range support rather than change a ubiquitous base class like Collection causing potentially severe side-effects that can only be detected at runtime. That's why #18087 is fatally flawed, and no modification to WPF - even full INCC support frankly - will change that.

@ThomasGoulet73
Copy link
Contributor

In my opinion, removing ValidateCollectionChangedEventArgs is the very last step here. There is code throughout this repo (Including ListCollectionView) that needs to be fixed before removing the validation.

Take this line of code for exemple:
https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Data/ListCollectionView.cs#L1748

It expects a single added item, which will silently break if you remove the validation without changing this code.

@dipeshmsft dipeshmsft self-assigned this Oct 16, 2023
@ghost ghost assigned SkyeHoefling Oct 16, 2023
@dotnet-policy-service
Copy link
Contributor

@SkyeHoefling please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the .NET Foundation ( “.NET Foundation” ) for Your contributions to
.NET Foundation open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to .NET Foundation under this Agreement.

“Project” means any of the projects owned or managed by .NET Foundation and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant .NET Foundation, and those who receive the Submission directly
or indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant .NET Foundation, and those who receive the Submission directly or
indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to .NET Foundation. You agree to notify .NET Foundation in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by .NET Foundation.

.NET Foundation dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
* NO MERGE * metadata: The PR is not ready for merge yet (see discussion for detailed reasons) PR metadata: Label to tag PRs, to facilitate with triage
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support Bulk Operations in ListCollectionView via ObservableCollection<T>
8 participants