Redesigned the Collection framework to incorporate a more general variant of the ObservableCollection<> class; ParentingCollection class now makes use of this new inbetween class; ParentingCollection now has a cleaner way to dispose its members than the original InternalDispose() method

git-svn-id: file:///srv/devel/repo-conversion/nusu@37 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2007-07-10 19:25:18 +00:00
parent 4933604495
commit ba1cee917d
10 changed files with 218 additions and 163 deletions

View File

@ -65,6 +65,14 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Source\Collections\AcquiringCollection.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>AcquiringCollection</Name>
</Compile>
<Compile Include="Source\Collections\ItemEventArgs.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ItemEventArgs</Name>
</Compile>
<Compile Include="Source\Collections\ObservableCollection.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ObservableCollection</Name>

View File

@ -0,0 +1,109 @@
#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2007 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Nuclex.Support.Collections {
/// <summary>Generic collection of progressions</summary>
public class AcquiringCollection<ItemType> : Collection<ItemType> {
/// <summary>
/// Initializes a new instance of the ObservableCollection class that is empty.
/// </summary>
public AcquiringCollection() : base() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class as a wrapper
/// for the specified list.
/// </summary>
/// <param name="list">The list that is wrapped by the new collection.</param>
/// <exception cref="System.ArgumentNullException">
/// List is null.
/// </exception>
public AcquiringCollection(IList<ItemType> list) : base(list) { }
/// <summary>Removes all elements from the Collection</summary>
protected override void ClearItems() {
OnClearing();
base.ClearItems();
}
/// <summary>
/// Inserts an element into the ProgressionCollection at the specified index
/// </summary>
/// <param name="index">
/// The object to insert. The value can be null for reference types.
/// </param>
/// <param name="item">The zero-based index at which item should be inserted</param>
protected override void InsertItem(int index, ItemType item) {
base.InsertItem(index, item);
OnAdded(item);
}
/// <summary>
/// Removes the element at the specified index of the ProgressionCollection
/// </summary>
/// <param name="index">The zero-based index of the element to remove</param>
protected override void RemoveItem(int index) {
ItemType item = base[index];
base.RemoveItem(index);
OnRemoved(item);
}
/// <summary>Replaces the element at the specified index</summary>
/// <param name="index">
/// The new value for the element at the specified index. The value can be null
/// for reference types
/// </param>
/// <param name="item">The zero-based index of the element to replace</param>
protected override void SetItem(int index, ItemType item) {
ItemType oldItem = base[index];
base.SetItem(index, item);
OnRemoved(oldItem);
OnAdded(item);
}
/// <summary>Called when an item has been added to the collection</summary>
/// <param name="item">Item that has been added to the collection</param>
protected virtual void OnAdded(ItemType item) { }
/// <summary>Called when an item has been removed from the collection</summary>
/// <param name="item">Item that has been removed from the collection</param>
protected virtual void OnRemoved(ItemType item) { }
/// <summary>Called when the collection is being cleared</summary>
/// <remarks>
/// Instead of called the OnRemoved() method for each item in the collection when
/// it is being cleared, this variant only triggers the OnClearing() method
/// to allow the implementer some room for optimizations.
/// </remarks>
protected virtual void OnClearing() { }
}
} // namespace Nuclex.Support.Collections

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace Nuclex.Support.Collections {
/// <summary>
/// Arguments class for collections wanting to hand over an item in an event
/// </summary>
public class ItemEventArgs<ItemType> : EventArgs {
/// <summary>Initializes a new event arguments supplier</summary>
/// <param name="item">Item to be supplied to the event handler</param>
public ItemEventArgs(ItemType item) {
this.item = item;
}
/// <summary>Obtains the collection item the event arguments are carrying</summary>
public ItemType Item {
get { return this.item; }
}
/// <summary>Item to be passed to the event handler</summary>
private ItemType item;
}
} // namespace Nuclex.Support.Collections

View File

@ -31,6 +31,8 @@ namespace Nuclex.Support.Collections {
[TestFixture]
public class ObservableCollectionTest {
#region interface IObservableCollectionSubscriber
/// <summary>Interface used to test the observable collection.</summary>
public interface IObservableCollectionSubscriber {
@ -42,15 +44,17 @@ namespace Nuclex.Support.Collections {
/// <summary>Called when an item is added to the collection</summary>
/// <param name="sender">Collection to which an item is being added</param>
/// <param name="e">Contains the item that is being added</param>
void ItemAdded(object sender, ObservableCollection<int>.ItemEventArgs e);
void ItemAdded(object sender, ItemEventArgs<int> e);
/// <summary>Called when an item is removed from the collection</summary>
/// <param name="sender">Collection from which an item is being removed</param>
/// <param name="e">Contains the item that is being removed</param>
void ItemRemoved(object sender, ObservableCollection<int>.ItemEventArgs e);
void ItemRemoved(object sender, ItemEventArgs<int> e);
}
#endregion // interface IObservableCollectionSubscriber
/// <summary>Initialization routine executed before each test is run</summary>
[SetUp]
public void Setup() {
@ -61,11 +65,11 @@ namespace Nuclex.Support.Collections {
this.observedCollection = new ObservableCollection<int>();
this.observedCollection.Clearing += new EventHandler(this.mockedSubscriber.Clearing);
this.observedCollection.ItemAdded +=
new EventHandler<ObservableCollection<int>.ItemEventArgs>(
new EventHandler<ItemEventArgs<int>>(
this.mockedSubscriber.ItemAdded
);
this.observedCollection.ItemRemoved +=
new EventHandler<ObservableCollection<int>.ItemEventArgs>(
new EventHandler<ItemEventArgs<int>>(
this.mockedSubscriber.ItemRemoved
);
@ -102,11 +106,12 @@ namespace Nuclex.Support.Collections {
Method("ItemAdded").
WithAnyArguments();
this.observedCollection.Add(123);
Expect.Once.On(this.mockedSubscriber).
Method("ItemRemoved").
WithAnyArguments();
this.observedCollection.Add(123);
this.observedCollection.Remove(123);
this.mockery.VerifyAllExpectationsHaveBeenMet();

View File

@ -23,36 +23,13 @@ using System.Collections.ObjectModel;
namespace Nuclex.Support.Collections {
/// <summary>Generic collection of progressions</summary>
public class ObservableCollection<ItemType> : Collection<ItemType> {
#region class ItemEventArgs
/// <summary>Arguments class for events that need to pass a progression</summary>
public class ItemEventArgs : EventArgs {
/// <summary>Initializes a new event arguments supplier</summary>
/// <param name="item">Item to be supplied to the event handler</param>
public ItemEventArgs(ItemType item) {
this.item = item;
}
/// <summary>Obtains the collection item the event arguments are carrying</summary>
public ItemType Item {
get { return this.item; }
}
/// <summary>Item that's passed to the event handler</summary>
private ItemType item;
}
#endregion // class ItemEventArgs
/// <summary>Collection which fires events when items are added or removed</summary>
public class ObservableCollection<ItemType> : AcquiringCollection<ItemType> {
/// <summary>Raised when an item has been added to the collection</summary>
public event EventHandler<ItemEventArgs> ItemAdded;
public event EventHandler<ItemEventArgs<ItemType>> ItemAdded;
/// <summary>Raised when an item is removed from the collection</summary>
public event EventHandler<ItemEventArgs> ItemRemoved;
public event EventHandler<ItemEventArgs<ItemType>> ItemRemoved;
/// <summary>Raised the collection is about to be cleared</summary>
public event EventHandler Clearing;
@ -66,74 +43,25 @@ namespace Nuclex.Support.Collections {
/// for the specified list.
/// </summary>
/// <param name="list">The list that is wrapped by the new collection.</param>
/// <exception cref="System.ArgumentNullException">
/// List is null.
/// </exception>
/// <exception cref="System.ArgumentNullException">List is null.</exception>
public ObservableCollection(IList<ItemType> list) : base(list) { }
/// <summary>Removes all elements from the Collection</summary>
protected override void ClearItems() {
OnClearing();
base.ClearItems();
}
/// <summary>
/// Inserts an element into the ProgressionCollection at the specified index
/// </summary>
/// <param name="index">
/// The object to insert. The value can be null for reference types.
/// </param>
/// <param name="item">The zero-based index at which item should be inserted</param>
protected override void InsertItem(int index, ItemType item) {
base.InsertItem(index, item);
OnAdded(item);
}
/// <summary>
/// Removes the element at the specified index of the ProgressionCollection
/// </summary>
/// <param name="index">The zero-based index of the element to remove</param>
protected override void RemoveItem(int index) {
ItemType item = base[index];
base.RemoveItem(index);
OnRemoved(item);
}
/// <summary>Replaces the element at the specified index</summary>
/// <param name="index">
/// The new value for the element at the specified index. The value can be null
/// for reference types
/// </param>
/// <param name="item">The zero-based index of the element to replace</param>
protected override void SetItem(int index, ItemType item) {
ItemType oldItem = base[index];
base.SetItem(index, item);
OnRemoved(oldItem);
OnAdded(item);
}
/// <summary>Fires the 'ItemAdded' event</summary>
/// <param name="item">Item that has been added to the collection</param>
protected virtual void OnAdded(ItemType item) {
protected override void OnAdded(ItemType item) {
if(ItemAdded != null)
ItemAdded(this, new ItemEventArgs(item));
ItemAdded(this, new ItemEventArgs<ItemType>(item));
}
/// <summary>Fires the 'ItemRemoved' event</summary>
/// <param name="item">Item that has been removed from the collection</param>
protected virtual void OnRemoved(ItemType item) {
protected override void OnRemoved(ItemType item) {
if(ItemRemoved != null)
ItemRemoved(this, new ItemEventArgs(item));
ItemRemoved(this, new ItemEventArgs<ItemType>(item));
}
/// <summary>Fires the 'Clearing' event</summary>
protected virtual void OnClearing() {
protected override void OnClearing() {
if(Clearing != null)
Clearing(this, EventArgs.Empty);
}

View File

@ -33,7 +33,7 @@ namespace Nuclex.Support.Collections {
/// </remarks>
/// <typeparam name="ParentType">Type of the parent object to assign to items</typeparam>
/// <typeparam name="ItemType">Type of the items being managed in the collection</typeparam>
public class ParentingCollection<ParentType, ItemType> : Collection<ItemType>
public class ParentingCollection<ParentType, ItemType> : AcquiringCollection<ItemType>
where ItemType : Parentable<ParentType> {
/// <summary>Reparents all elements in the collection</summary>
@ -45,39 +45,19 @@ namespace Nuclex.Support.Collections {
base[index].SetParent(parent);
}
/// <summary>Clears all elements from the collection</summary>
protected override void ClearItems() {
for(int index = 0; index < Count; ++index)
base[index].SetParent(default(ParentType));
base.ClearItems();
}
/// <summary>Inserts a new element into the collection</summary>
/// <param name="index">Index at which to insert the element</param>
/// <param name="item">Item to be inserted</param>
protected override void InsertItem(int index, ItemType item) {
base.InsertItem(index, item);
/// <summary>Called when an item has been added to the collection</summary>
/// <param name="item">Item that has been added to the collection</param>
protected virtual void OnAdded(ItemType item) {
item.SetParent(this.parent);
}
/// <summary>Removes an element from the collection</summary>
/// <param name="index">Index of the element to remove</param>
protected override void RemoveItem(int index) {
base[index].SetParent(default(ParentType));
base.RemoveItem(index);
}
/// <summary>Takes over a new element that is directly assigned</summary>
/// <param name="index">Index of the element that was assigned</param>
/// <param name="item">New item</param>
protected override void SetItem(int index, ItemType item) {
base.SetItem(index, item);
item.SetParent(this.parent);
/// <summary>Called when an item has been removed from the collection</summary>
/// <param name="item">Item that has been removed from the collection</param>
protected virtual void OnRemoved(ItemType item) {
item.SetParent(default(ParentType));
}
/// <summary>Disposes the collection and optionally all items contained therein</summary>
/// <param name="disposeItems">Whether to try calling Dispose() on all items</param>
/// <remarks>
/// <para>
/// This method is intended to support collections that need to dispose of their
@ -95,25 +75,23 @@ namespace Nuclex.Support.Collections {
/// line with InternalDispose(true); in your custom Dispose() method.
/// </para>
/// </remarks>
protected void InternalDispose(bool disposeItems) {
protected void DisposeItems() {
if(disposeItems) {
// Dispose all the items in the collection that implement IDisposable,
// starting from the last item in the assumption that this is the fastest
// way to empty a list without causing excessive shiftings in the array.
for(int index = base.Count - 1; index >= 0; --index) {
// Dispose of all the items in the collection that implement IDisposable
foreach(ItemType item in this) {
IDisposable disposable = item as IDisposable;
IDisposable disposable = base[index] as IDisposable;
// If the item is disposable, we get rid of it
if(disposable != null)
disposable.Dispose();
base.RemoveAt(index);
}
// If the item is disposable, destroy it now
if(disposable != null)
disposable.Dispose();
}
// Remove all items from the collection
base.ClearItems();
}
/// <summary>Parent this collection currently belongs to</summary>

View File

@ -174,7 +174,7 @@ namespace Nuclex.Support.Collections {
// stream to contain the remainder of the data.
if(count > linearAvailable) {
if(count > (linearAvailable + this.startIndex))
throw new OverflowException("Data does not fit in Ringbuffer");
throw new OverflowException("Data does not fit in buffer");
this.ringBuffer.Position = this.endIndex;
this.ringBuffer.Write(buffer, offset, linearAvailable);
@ -197,7 +197,7 @@ namespace Nuclex.Support.Collections {
// to write cannot be fragmented. Example: |#####>-------<#####|
} else {
if(count > (this.startIndex - this.endIndex))
throw new OverflowException("Data does not fit in Ringbuffer");
throw new OverflowException("Data does not fit in buffer");
// Because the gap isn't fragmented, we can be sure that a single
// write call will suffice.
@ -241,9 +241,9 @@ namespace Nuclex.Support.Collections {
/// <remarks>
/// This field is required to differentiate between the ring buffer being
/// filled to the limit and being totally empty in the case that
/// the start index and the end index are the same.
/// the start index and the end index are the same.
/// </remarks>
bool empty;
private bool empty;
}

View File

@ -38,7 +38,7 @@ namespace Nuclex.Support.Scheduling {
asyncOperationProgressUpdated
);
this.childs = new List<WeightedProgression<OperationType>>();
this.children = new List<WeightedProgression<OperationType>>();
}
/// <summary>Initializes a new queue operation with default weights</summary>
@ -51,11 +51,11 @@ namespace Nuclex.Support.Scheduling {
// Construct a WeightedProgression with the default weight for each
// progression and wrap it in an ObservedProgression
foreach(OperationType operation in childs)
this.childs.Add(new WeightedProgression<OperationType>(operation));
this.children.Add(new WeightedProgression<OperationType>(operation));
// Since all progressions have a weight of 1.0, the total weight is
// equal to the number of progressions in our list
this.totalWeight = (float)this.childs.Count;
this.totalWeight = (float)this.children.Count;
}
@ -65,7 +65,7 @@ namespace Nuclex.Support.Scheduling {
// Construct an ObservedProgression around each of the WeightedProgressions
foreach(WeightedProgression<OperationType> operation in childs) {
this.childs.Add(operation);
this.children.Add(operation);
// Sum up the total weight
this.totalWeight += operation.Weight;
@ -74,8 +74,8 @@ namespace Nuclex.Support.Scheduling {
}
/// <summary>Provides access to the child operations of this queue</summary>
public IList<WeightedProgression<OperationType>> Childs {
get { return this.childs; }
public IList<WeightedProgression<OperationType>> Children {
get { return this.children; }
}
/// <summary>Launches the background operation</summary>
@ -89,7 +89,7 @@ namespace Nuclex.Support.Scheduling {
/// and launches the operation by calling its Begin() method.
/// </remarks>
private void beginCurrentOperation() {
OperationType operation = this.childs[this.currentOperationIndex].Progression;
OperationType operation = this.children[this.currentOperationIndex].Progression;
operation.AsyncEnded += this.asyncOperationEndedDelegate;
operation.AsyncProgressUpdated += this.asyncOperationProgressUpdatedDelegate;
@ -104,7 +104,7 @@ namespace Nuclex.Support.Scheduling {
/// counts up the accumulated progress of the queue.
/// </remarks>
private void endCurrentOperation() {
OperationType operation = this.childs[this.currentOperationIndex].Progression;
OperationType operation = this.children[this.currentOperationIndex].Progression;
// Disconnect from the operation's events
operation.AsyncEnded -= this.asyncOperationEndedDelegate;
@ -114,7 +114,7 @@ namespace Nuclex.Support.Scheduling {
operation.End();
// Add the operations weight to the total amount of completed weight in the queue
this.completedWeight += this.childs[this.currentOperationIndex].Weight;
this.completedWeight += this.children[this.currentOperationIndex].Weight;
// Trigger another progress update
OnAsyncProgressUpdated(this.completedWeight / this.totalWeight);
@ -139,7 +139,7 @@ namespace Nuclex.Support.Scheduling {
++this.currentOperationIndex;
// Execute the next operation unless we reached the end of the queue
if(this.currentOperationIndex < this.childs.Count) {
if(this.currentOperationIndex < this.children.Count) {
beginCurrentOperation();
return;
}
@ -159,7 +159,7 @@ namespace Nuclex.Support.Scheduling {
// Determine the completed weight of the currently executing operation
float currentOperationCompletedWeight =
e.Progress * this.childs[this.currentOperationIndex].Weight;
e.Progress * this.children[this.currentOperationIndex].Weight;
// Build the total normalized amount of progress for the queue
float progress =
@ -175,7 +175,7 @@ namespace Nuclex.Support.Scheduling {
/// <summary>Delegate to the asyncOperationProgressUpdated() method</summary>
private EventHandler<ProgressUpdateEventArgs> asyncOperationProgressUpdatedDelegate;
/// <summary>Operations being managed in the queue</summary>
private List<WeightedProgression<OperationType>> childs;
private List<WeightedProgression<OperationType>> children;
/// <summary>Summed weight of all operations in the queue</summary>
private float totalWeight;
/// <summary>Accumulated weight of the operations already completed</summary>

View File

@ -137,7 +137,7 @@ namespace Nuclex.Support.Tracking {
}
);
testSetProgression.Childs[0].Progression.ChangeProgress(0.5f);
testSetProgression.Children[0].Progression.ChangeProgress(0.5f);
this.mockery.VerifyAllExpectationsHaveBeenMet();
}
@ -164,7 +164,7 @@ namespace Nuclex.Support.Tracking {
}
);
testSetProgression.Childs[0].Progression.ChangeProgress(0.5f);
testSetProgression.Children[0].Progression.ChangeProgress(0.5f);
Expect.Once.On(mockedSubscriber).
Method("ProgressUpdated").
@ -175,7 +175,7 @@ namespace Nuclex.Support.Tracking {
}
);
testSetProgression.Childs[1].Progression.ChangeProgress(0.5f);
testSetProgression.Children[1].Progression.ChangeProgress(0.5f);
this.mockery.VerifyAllExpectationsHaveBeenMet();
}
@ -200,8 +200,8 @@ namespace Nuclex.Support.Tracking {
Method("Ended").
WithAnyArguments();
testSetProgression.Childs[0].Progression.End();
testSetProgression.Childs[1].Progression.End();
testSetProgression.Children[0].Progression.End();
testSetProgression.Children[1].Progression.End();
this.mockery.VerifyAllExpectationsHaveBeenMet();
}

View File

@ -32,7 +32,7 @@ namespace Nuclex.Support.Tracking {
/// <summary>Performs common initialization for the public constructors</summary>
private SetProgression() {
this.childs = new List<ObservedWeightedProgression<ProgressionType>>();
this.children = new List<ObservedWeightedProgression<ProgressionType>>();
}
/// <summary>Initializes a new set progression</summary>
@ -46,7 +46,7 @@ namespace Nuclex.Support.Tracking {
// Construct a WeightedProgression with the default weight for each
// progression and wrap it in an ObservedProgression
foreach(ProgressionType progression in childs) {
this.childs.Add(
this.children.Add(
new ObservedWeightedProgression<ProgressionType>(
new WeightedProgression<ProgressionType>(progression),
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
@ -57,7 +57,7 @@ namespace Nuclex.Support.Tracking {
// Since all progressions have a weight of 1.0, the total weight is
// equal to the number of progressions in our list
this.totalWeight = (float)this.childs.Count;
this.totalWeight = (float)this.children.Count;
}
@ -70,7 +70,7 @@ namespace Nuclex.Support.Tracking {
// Construct an ObservedProgression around each of the WeightedProgressions
foreach(WeightedProgression<ProgressionType> progression in childs) {
this.childs.Add(
this.children.Add(
new ObservedWeightedProgression<ProgressionType>(
progression,
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
@ -87,14 +87,14 @@ namespace Nuclex.Support.Tracking {
/// <summary>Immediately releases all resources owned by the object</summary>
public void Dispose() {
if(this.childs != null) {
if(this.children != null) {
// Dispose all the observed progressions, disconnecting the events from the
// actual progressions so the GC can more easily collect this class
for(int index = 0; index < this.childs.Count; ++index)
this.childs[index].Dispose();
for(int index = 0; index < this.children.Count; ++index)
this.children[index].Dispose();
this.childs = null;
this.children = null;
this.wrapper = null;
}
@ -102,7 +102,7 @@ namespace Nuclex.Support.Tracking {
}
/// <summary>Childs contained in the progression set</summary>
public IList<WeightedProgression<ProgressionType>> Childs {
public IList<WeightedProgression<ProgressionType>> Children {
get {
// The wrapper is constructed only when needed. Most of the time, users will
@ -113,7 +113,7 @@ namespace Nuclex.Support.Tracking {
// This doesn't need a lock because it's a stateless wrapper.
// If it is constructed twice, then so be it, no problem at all.
this.wrapper = new WeightedProgressionWrapperCollection<ProgressionType>(
this.childs
this.children
);
}
@ -131,9 +131,9 @@ namespace Nuclex.Support.Tracking {
// Calculate the sum of the progress reported by our child progressions,
// scaled to the weight each progression has assigned to it.
for(int index = 0; index < this.childs.Count; ++index) {
for(int index = 0; index < this.children.Count; ++index) {
totalProgress +=
this.childs[index].Progress * this.childs[index].WeightedProgression.Weight;
this.children[index].Progress * this.children[index].WeightedProgression.Weight;
}
// Calculate the actual combined progress
@ -151,8 +151,8 @@ namespace Nuclex.Support.Tracking {
// If there's still at least one progression going, don't report that
// the SetProgression has finished yet.
for(int index = 0; index < this.childs.Count; ++index)
if(!this.childs[index].WeightedProgression.Progression.Ended)
for(int index = 0; index < this.children.Count; ++index)
if(!this.children[index].WeightedProgression.Progression.Ended)
return;
// All child progressions have ended, so the set has now ended as well
@ -161,7 +161,7 @@ namespace Nuclex.Support.Tracking {
}
/// <summary>Progressions being managed in the set</summary>
private List<ObservedWeightedProgression<ProgressionType>> childs;
private List<ObservedWeightedProgression<ProgressionType>> children;
/// <summary>
/// Wrapper collection for exposing the child progressions under the
/// WeightedProgression interface