首次上传

This commit is contained in:
hanqiangqiang
2026-06-15 10:56:30 +08:00
commit b0213b94d6
4160 changed files with 736101 additions and 0 deletions
@@ -0,0 +1,13 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// EventArgs sent during activation.
/// </summary>
public class ActivationEventArgs : EventArgs {
/// <summary>
/// Indicates whether the sender was initialized in addition to being activated.
/// </summary>
public bool WasInitialized;
}
}
@@ -0,0 +1,19 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Contains details about the success or failure of an item's activation through an <see cref="IConductor"/>.
/// </summary>
public class ActivationProcessedEventArgs : EventArgs {
/// <summary>
/// The item whose activation was processed.
/// </summary>
public object Item;
/// <summary>
/// Gets or sets a value indicating whether the activation was a success.
/// </summary>
/// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
public bool Success;
}
}
@@ -0,0 +1,194 @@
namespace Caliburn.Micro.Core {
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
/// <summary>
/// A base collection class that supports automatic UI thread marshalling.
/// </summary>
/// <typeparam name="T">The type of elements contained in the collection.</typeparam>
public class BindableCollection<T> : ObservableCollection<T>, IObservableCollection<T> {
/// <summary>
/// Initializes a new instance of the <see cref = "BindableCollection{T}" /> class.
/// </summary>
public BindableCollection() {
IsNotifying = true;
}
/// <summary>
/// Initializes a new instance of the <see cref = "BindableCollection{T}" /> class.
/// </summary>
/// <param name = "collection">The collection from which the elements are copied.</param>
public BindableCollection(IEnumerable<T> collection)
: base(collection) {
IsNotifying = true;
}
/// <summary>
/// Enables/Disables property change notification.
/// </summary>
public bool IsNotifying { get; set; }
/// <summary>
/// Notifies subscribers of the property change.
/// </summary>
/// <param name = "propertyName">Name of the property.</param>
public virtual void NotifyOfPropertyChange(string propertyName) {
if (IsNotifying)
Execute.OnUIThread(() => OnPropertyChanged(new PropertyChangedEventArgs(propertyName)));
}
/// <summary>
/// Raises a change notification indicating that all bindings should be refreshed.
/// </summary>
public void Refresh() {
Execute.OnUIThread(() => {
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
/// <summary>
/// Inserts the item to the specified position.
/// </summary>
/// <param name = "index">The index to insert at.</param>
/// <param name = "item">The item to be inserted.</param>
protected override sealed void InsertItem(int index, T item) {
Execute.OnUIThread(() => InsertItemBase(index, item));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "InsertItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <param name = "item">The item.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void InsertItemBase(int index, T item) {
base.InsertItem(index, item);
}
/// <summary>
/// Sets the item at the specified position.
/// </summary>
/// <param name = "index">The index to set the item at.</param>
/// <param name = "item">The item to set.</param>
protected override sealed void SetItem(int index, T item) {
Execute.OnUIThread(() => SetItemBase(index, item));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "SetItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <param name = "item">The item.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void SetItemBase(int index, T item) {
base.SetItem(index, item);
}
/// <summary>
/// Removes the item at the specified position.
/// </summary>
/// <param name = "index">The position used to identify the item to remove.</param>
protected override sealed void RemoveItem(int index) {
Execute.OnUIThread(() => RemoveItemBase(index));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "RemoveItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void RemoveItemBase(int index) {
base.RemoveItem(index);
}
/// <summary>
/// Clears the items contained by the collection.
/// </summary>
protected override sealed void ClearItems() {
Execute.OnUIThread(ClearItemsBase);
}
/// <summary>
/// Exposes the base implementation of the <see cref = "ClearItems" /> function.
/// </summary>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void ClearItemsBase() {
base.ClearItems();
}
/// <summary>
/// Raises the <see cref = "E:System.Collections.ObjectModel.ObservableCollection`1.CollectionChanged" /> event with the provided arguments.
/// </summary>
/// <param name = "e">Arguments of the event being raised.</param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) {
if (IsNotifying) {
base.OnCollectionChanged(e);
}
}
/// <summary>
/// Raises the PropertyChanged event with the provided arguments.
/// </summary>
/// <param name = "e">The event data to report in the event.</param>
protected override void OnPropertyChanged(PropertyChangedEventArgs e) {
if (IsNotifying) {
base.OnPropertyChanged(e);
}
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name = "items">The items.</param>
public virtual void AddRange(IEnumerable<T> items) {
Execute.OnUIThread(() => {
var previousNotificationSetting = IsNotifying;
IsNotifying = false;
var index = Count;
foreach (var item in items) {
InsertItemBase(index, item);
index++;
}
IsNotifying = previousNotificationSetting;
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
/// <summary>
/// Removes the range.
/// </summary>
/// <param name = "items">The items.</param>
public virtual void RemoveRange(IEnumerable<T> items) {
Execute.OnUIThread(() => {
var previousNotificationSetting = IsNotifying;
IsNotifying = false;
foreach (var item in items) {
var index = IndexOf(item);
if (index >= 0) {
RemoveItemBase(index);
}
}
IsNotifying = previousNotificationSetting;
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
}
}
@@ -0,0 +1,76 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// An implementation of <see cref="IConductor"/> that holds on to and activates only one item at a time.
/// </summary>
public partial class Conductor<T> : ConductorBaseWithActiveItem<T> where T: class {
/// <summary>
/// Activates the specified item.
/// </summary>
/// <param name="item">The item to activate.</param>
public override void ActivateItem(T item) {
if(item != null && item.Equals(ActiveItem)) {
if (IsActive) {
ScreenExtensions.TryActivate(item);
OnActivationProcessed(item, true);
}
return;
}
CloseStrategy.Execute(new[] { ActiveItem }, (canClose, items) => {
if(canClose)
ChangeActiveItem(item, true);
else OnActivationProcessed(item, false);
});
}
/// <summary>
/// Deactivates the specified item.
/// </summary>
/// <param name="item">The item to close.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
public override void DeactivateItem(T item, bool close) {
if (item == null || !item.Equals(ActiveItem)) {
return;
}
CloseStrategy.Execute(new[] { ActiveItem }, (canClose, items) => {
if(canClose)
ChangeActiveItem(default(T), close);
});
}
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name="callback">The implementor calls this action with the result of the close check.</param>
public override void CanClose(Action<bool> callback) {
CloseStrategy.Execute(new[] { ActiveItem }, (canClose, items) => callback(canClose));
}
/// <summary>
/// Called when activating.
/// </summary>
protected override void OnActivate() {
ScreenExtensions.TryActivate(ActiveItem);
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name="close">Inidicates whether this instance will be closed.</param>
protected override void OnDeactivate(bool close) {
ScreenExtensions.TryDeactivate(ActiveItem, close);
}
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>The collection of children.</returns>
public override IEnumerable<T> GetChildren() {
return new[] { ActiveItem };
}
}
}
@@ -0,0 +1,91 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// A base class for various implementations of <see cref="IConductor"/>.
/// </summary>
/// <typeparam name="T">The type that is being conducted.</typeparam>
public abstract class ConductorBase<T> : Screen, IConductor, IParent<T> where T : class {
ICloseStrategy<T> closeStrategy;
/// <summary>
/// Gets or sets the close strategy.
/// </summary>
/// <value>The close strategy.</value>
public ICloseStrategy<T> CloseStrategy {
get { return closeStrategy ?? (closeStrategy = new DefaultCloseStrategy<T>()); }
set { closeStrategy = value; }
}
void IConductor.ActivateItem(object item) {
ActivateItem((T) item);
}
void IConductor.DeactivateItem(object item, bool close) {
DeactivateItem((T) item, close);
}
IEnumerable IParent.GetChildren() {
return GetChildren();
}
/// <summary>
/// Occurs when an activation request is processed.
/// </summary>
public virtual event EventHandler<ActivationProcessedEventArgs> ActivationProcessed = delegate { };
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>The collection of children.</returns>
public abstract IEnumerable<T> GetChildren();
/// <summary>
/// Activates the specified item.
/// </summary>
/// <param name="item">The item to activate.</param>
public abstract void ActivateItem(T item);
/// <summary>
/// Deactivates the specified item.
/// </summary>
/// <param name="item">The item to close.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
public abstract void DeactivateItem(T item, bool close);
/// <summary>
/// Called by a subclass when an activation needs processing.
/// </summary>
/// <param name="item">The item on which activation was attempted.</param>
/// <param name="success">if set to <c>true</c> activation was successful.</param>
protected virtual void OnActivationProcessed(T item, bool success) {
if (item == null) {
return;
}
var handler = ActivationProcessed;
if (handler != null) {
handler(this, new ActivationProcessedEventArgs
{
Item = item,
Success = success
});
}
}
/// <summary>
/// Ensures that an item is ready to be activated.
/// </summary>
/// <param name="newItem">The item that is about to be activated.</param>
/// <returns>The item to be activated.</returns>
protected virtual T EnsureItem(T newItem) {
var node = newItem as IChild;
if (node != null && node.Parent != this)
node.Parent = this;
return newItem;
}
}
}
@@ -0,0 +1,44 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// A base class for various implementations of <see cref="IConductor"/> that maintain an active item.
/// </summary>
/// <typeparam name="T">The type that is being conducted.</typeparam>
public abstract class ConductorBaseWithActiveItem<T> : ConductorBase<T>, IConductActiveItem where T: class {
T activeItem;
/// <summary>
/// The currently active item.
/// </summary>
public T ActiveItem {
get { return activeItem; }
set { ActivateItem(value); }
}
/// <summary>
/// The currently active item.
/// </summary>
/// <value></value>
object IHaveActiveItem.ActiveItem {
get { return ActiveItem; }
set { ActiveItem = (T)value; }
}
/// <summary>
/// Changes the active item.
/// </summary>
/// <param name="newItem">The new item to activate.</param>
/// <param name="closePrevious">Indicates whether or not to close the previous active item.</param>
protected virtual void ChangeActiveItem(T newItem, bool closePrevious) {
ScreenExtensions.TryDeactivate(activeItem, closePrevious);
newItem = EnsureItem(newItem);
if(IsActive)
ScreenExtensions.TryActivate(newItem);
activeItem = newItem;
NotifyOfPropertyChange("ActiveItem");
OnActivationProcessed(activeItem, true);
}
}
}
@@ -0,0 +1,176 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
public partial class Conductor<T> {
/// <summary>
/// An implementation of <see cref="IConductor"/> that holds on many items.
/// </summary>
public partial class Collection {
/// <summary>
/// An implementation of <see cref="IConductor"/> that holds on to many items which are all activated.
/// </summary>
public class AllActive : ConductorBase<T> {
private readonly BindableCollection<T> items = new BindableCollection<T>();
private readonly bool openPublicItems;
/// <summary>
/// Initializes a new instance of the <see cref="Conductor&lt;T&gt;.Collection.AllActive"/> class.
/// </summary>
/// <param name="openPublicItems">if set to <c>true</c> opens public items that are properties of this class.</param>
public AllActive(bool openPublicItems)
: this() {
this.openPublicItems = openPublicItems;
}
/// <summary>
/// Initializes a new instance of the <see cref="Conductor&lt;T&gt;.Collection.AllActive"/> class.
/// </summary>
public AllActive() {
items.CollectionChanged += (s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
e.NewItems.OfType<IChild>().Apply(x => x.Parent = this);
break;
case NotifyCollectionChangedAction.Remove:
e.OldItems.OfType<IChild>().Apply(x => x.Parent = null);
break;
case NotifyCollectionChangedAction.Replace:
e.NewItems.OfType<IChild>().Apply(x => x.Parent = this);
e.OldItems.OfType<IChild>().Apply(x => x.Parent = null);
break;
case NotifyCollectionChangedAction.Reset:
items.OfType<IChild>().Apply(x => x.Parent = this);
break;
}
};
}
/// <summary>
/// Gets the items that are currently being conducted.
/// </summary>
public IObservableCollection<T> Items {
get { return items; }
}
/// <summary>
/// Called when activating.
/// </summary>
protected override void OnActivate() {
items.OfType<IActivate>().Apply(x => x.Activate());
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name="close">Inidicates whether this instance will be closed.</param>
protected override void OnDeactivate(bool close) {
items.OfType<IDeactivate>().Apply(x => x.Deactivate(close));
if (close) {
items.Clear();
}
}
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name="callback">The implementor calls this action with the result of the close check.</param>
public override void CanClose(Action<bool> callback) {
CloseStrategy.Execute(items.ToList(), (canClose, closable) => {
if (!canClose && closable.Any()) {
closable.OfType<IDeactivate>().Apply(x => x.Deactivate(true));
items.RemoveRange(closable);
}
callback(canClose);
});
}
/// <summary>
/// Called when initializing.
/// </summary>
protected override void OnInitialize() {
if (openPublicItems) {
GetType().GetProperties()
.Where(x => x.Name != "Parent" && typeof (T).IsAssignableFrom(x.PropertyType))
.Select(x => x.GetValue(this, null))
.Cast<T>()
.Apply(ActivateItem);
}
}
/// <summary>
/// Activates the specified item.
/// </summary>
/// <param name="item">The item to activate.</param>
public override void ActivateItem(T item) {
if (item == null) {
return;
}
item = EnsureItem(item);
if (IsActive) {
ScreenExtensions.TryActivate(item);
}
OnActivationProcessed(item, true);
}
/// <summary>
/// Deactivates the specified item.
/// </summary>
/// <param name="item">The item to close.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
public override void DeactivateItem(T item, bool close) {
if (item == null) {
return;
}
if (close) {
CloseStrategy.Execute(new[] {item}, (canClose, closable) => {
if (canClose)
CloseItemCore(item);
});
}
else {
ScreenExtensions.TryDeactivate(item, false);
}
}
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>The collection of children.</returns>
public override IEnumerable<T> GetChildren() {
return items;
}
private void CloseItemCore(T item) {
ScreenExtensions.TryDeactivate(item, true);
items.Remove(item);
}
/// <summary>
/// Ensures that an item is ready to be activated.
/// </summary>
/// <param name="newItem">The item that is about to be activated.</param>
/// <returns>The item to be activated.</returns>
protected override T EnsureItem(T newItem) {
var index = items.IndexOf(newItem);
if (index == -1) {
items.Add(newItem);
}
else {
newItem = items[index];
}
return base.EnsureItem(newItem);
}
}
}
}
}
@@ -0,0 +1,212 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
public partial class Conductor<T> {
/// <summary>
/// An implementation of <see cref="IConductor"/> that holds on many items.
/// </summary>
public partial class Collection {
/// <summary>
/// An implementation of <see cref="IConductor"/> that holds on many items but only activates one at a time.
/// </summary>
public class OneActive : ConductorBaseWithActiveItem<T> {
readonly BindableCollection<T> items = new BindableCollection<T>();
/// <summary>
/// Initializes a new instance of the <see cref="Conductor&lt;T&gt;.Collection.OneActive"/> class.
/// </summary>
public OneActive() {
items.CollectionChanged += (s, e) => {
switch(e.Action) {
case NotifyCollectionChangedAction.Add:
e.NewItems.OfType<IChild>().Apply(x => x.Parent = this);
break;
case NotifyCollectionChangedAction.Remove:
e.OldItems.OfType<IChild>().Apply(x => x.Parent = null);
break;
case NotifyCollectionChangedAction.Replace:
e.NewItems.OfType<IChild>().Apply(x => x.Parent = this);
e.OldItems.OfType<IChild>().Apply(x => x.Parent = null);
break;
case NotifyCollectionChangedAction.Reset:
items.OfType<IChild>().Apply(x => x.Parent = this);
break;
}
};
}
/// <summary>
/// Gets the items that are currently being conducted.
/// </summary>
public IObservableCollection<T> Items {
get { return items; }
}
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>The collection of children.</returns>
public override IEnumerable<T> GetChildren() {
return items;
}
/// <summary>
/// Activates the specified item.
/// </summary>
/// <param name="item">The item to activate.</param>
public override void ActivateItem(T item) {
if(item != null && item.Equals(ActiveItem)) {
if (IsActive) {
ScreenExtensions.TryActivate(item);
OnActivationProcessed(item, true);
}
return;
}
ChangeActiveItem(item, false);
}
/// <summary>
/// Deactivates the specified item.
/// </summary>
/// <param name="item">The item to close.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
public override void DeactivateItem(T item, bool close) {
if (item == null) {
return;
}
if (!close) {
ScreenExtensions.TryDeactivate(item, false);
}
else {
CloseStrategy.Execute(new[] { item }, (canClose, closable) => {
if (canClose) {
CloseItemCore(item);
}
});
}
}
void CloseItemCore(T item) {
if(item.Equals(ActiveItem)) {
var index = items.IndexOf(item);
var next = DetermineNextItemToActivate(items, index);
ChangeActiveItem(next, true);
}
else {
ScreenExtensions.TryDeactivate(item, true);
}
items.Remove(item);
}
/// <summary>
/// Determines the next item to activate based on the last active index.
/// </summary>
/// <param name="list">The list of possible active items.</param>
/// <param name="lastIndex">The index of the last active item.</param>
/// <returns>The next item to activate.</returns>
/// <remarks>Called after an active item is closed.</remarks>
protected virtual T DetermineNextItemToActivate(IList<T> list, int lastIndex) {
var toRemoveAt = lastIndex - 1;
if (toRemoveAt == -1 && list.Count > 1) {
return list[1];
}
if (toRemoveAt > -1 && toRemoveAt < list.Count - 1) {
return list[toRemoveAt];
}
return default(T);
}
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name="callback">The implementor calls this action with the result of the close check.</param>
public override void CanClose(Action<bool> callback) {
CloseStrategy.Execute(items.ToList(), (canClose, closable) => {
if(!canClose && closable.Any()) {
if(closable.Contains(ActiveItem)) {
var list = items.ToList();
var next = ActiveItem;
do {
var previous = next;
next = DetermineNextItemToActivate(list, list.IndexOf(previous));
list.Remove(previous);
} while(closable.Contains(next));
var previousActive = ActiveItem;
ChangeActiveItem(next, true);
items.Remove(previousActive);
var stillToClose = closable.ToList();
stillToClose.Remove(previousActive);
closable = stillToClose;
}
closable.OfType<IDeactivate>().Apply(x => x.Deactivate(true));
items.RemoveRange(closable);
}
callback(canClose);
});
}
/// <summary>
/// Called when activating.
/// </summary>
protected override void OnActivate() {
ScreenExtensions.TryActivate(ActiveItem);
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name="close">Inidicates whether this instance will be closed.</param>
protected override void OnDeactivate(bool close) {
if (close) {
items.OfType<IDeactivate>().Apply(x => x.Deactivate(true));
items.Clear();
}
else {
ScreenExtensions.TryDeactivate(ActiveItem, false);
}
}
/// <summary>
/// Ensures that an item is ready to be activated.
/// </summary>
/// <param name="newItem">The item that is about to be activated.</param>
/// <returns>The item to be activated.</returns>
protected override T EnsureItem(T newItem) {
if (newItem == null) {
newItem = DetermineNextItemToActivate(items, ActiveItem != null ? items.IndexOf(ActiveItem) : 0);
}
else {
var index = items.IndexOf(newItem);
if (index == -1)
items.Add(newItem);
else newItem = items[index];
}
return base.EnsureItem(newItem);
}
public void ClearItems()
{
items.Clear();
ChangeActiveItem(null, true);
}
}
}
}
}
@@ -0,0 +1,156 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// Extension methods for the <see cref="SimpleContainer"/>.
/// </summary>
public static class ContainerExtensions {
/// <summary>
/// Registers a singleton.
/// </summary>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>The container.</returns>
public static SimpleContainer Singleton<TImplementation>(this SimpleContainer container, string key = null) {
return Singleton<TImplementation, TImplementation>(container, key);
}
/// <summary>
/// Registers a singleton.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>The container.</returns>
public static SimpleContainer Singleton<TService, TImplementation>(this SimpleContainer container, string key = null)
where TImplementation : TService {
container.RegisterSingleton(typeof (TService), key, typeof (TImplementation));
return container;
}
/// <summary>
/// Registers an service to be created on each request.
/// </summary>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>The container.</returns>
public static SimpleContainer PerRequest<TImplementation>(this SimpleContainer container, string key = null) {
return PerRequest<TImplementation, TImplementation>(container, key);
}
/// <summary>
/// Registers an service to be created on each request.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>The container.</returns>
public static SimpleContainer PerRequest<TService, TImplementation>(this SimpleContainer container, string key = null)
where TImplementation : TService {
container.RegisterPerRequest(typeof (TService), key, typeof (TImplementation));
return container;
}
/// <summary>
/// Registers an instance with the container.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="instance">The instance.</param>
/// <returns>The container.</returns>
public static SimpleContainer Instance<TService>(this SimpleContainer container, TService instance) {
container.RegisterInstance(typeof (TService), null, instance);
return container;
}
/// <summary>
/// Registers a custom service handler with the container.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="handler">The handler.</param>
/// <returns>The container.</returns>
public static SimpleContainer Handler<TService>(this SimpleContainer container,
Func<SimpleContainer, object> handler) {
container.RegisterHandler(typeof (TService), null, handler);
return container;
}
/// <summary>
/// Registers all specified types in an assembly as singleton in the container.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="filter">The type filter.</param>
/// <returns>The container.</returns>
public static SimpleContainer AllTypesOf<TService>(this SimpleContainer container, Assembly assembly,
Func<Type, bool> filter = null) {
if (filter == null)
filter = type => true;
var serviceType = typeof (TService);
var types = from type in assembly.GetTypes()
where serviceType.IsAssignableFrom(type)
&& !type.IsAbstract()
&& !type.IsInterface()
&& filter(type)
select type;
foreach (var type in types) {
container.RegisterSingleton(typeof (TService), null, type);
}
return container;
}
/// <summary>
/// Requests an instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>The instance.</returns>
public static TService GetInstance<TService>(this SimpleContainer container, string key = null) {
return (TService) container.GetInstance(typeof (TService), key);
}
/// <summary>
/// Gets all instances of a particular type.
/// </summary>
/// <typeparam name="TService">The type to resolve.</typeparam>
/// <param name="container">The container.</param>
/// <returns>The resolved instances.</returns>
public static IEnumerable<TService> GetAllInstances<TService>(this SimpleContainer container) {
return container.GetAllInstances(typeof (TService)).Cast<TService>();
}
/// <summary>
/// Determines if a handler for the service/key has previously been registered.
/// </summary>
/// <typeparam name="TService">The service type.</typeparam>
/// <param name="container">The container.</param>
/// <param name="key">The key.</param>
/// <returns>True if a handler is registere; false otherwise.</returns>
public static bool HasHandler<TService>(this SimpleContainer container, string key = null) {
return container.HasHandler(typeof (TService), key);
}
/// <summary>
/// Unregisters any handlers for the service/key that have previously been registered.
/// </summary>
/// <typeparam name="TService">The service type.</typeparam>
/// <param name="container">The container.</param>
/// <param name = "key">The key.</param>
public static void UnregisterHandler<TService>(this SimpleContainer container, string key = null) {
container.UnregisterHandler(typeof(TService), key);
}
}
}
@@ -0,0 +1,65 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A result decorator which executes a coroutine when the wrapped result was cancelled.
/// </summary>
public class ContinueResultDecorator : ResultDecoratorBase {
static readonly ILog Log = LogManager.GetLog(typeof(ContinueResultDecorator));
readonly Func<IResult> coroutine;
/// <summary>
/// Initializes a new instance of the <see cref="ContinueResultDecorator"/> class.
/// </summary>
/// <param name="result">The result to decorate.</param>
/// <param name="coroutine">The coroutine to execute when <paramref name="result"/> was canceled.</param>
public ContinueResultDecorator(IResult result, Func<IResult> coroutine)
: base(result) {
if (coroutine == null)
throw new ArgumentNullException("coroutine");
this.coroutine = coroutine;
}
/// <summary>
/// Called when the execution of the decorated result has completed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="innerResult">The decorated result.</param>
/// <param name="args">The <see cref="ResultCompletionEventArgs" /> instance containing the event data.</param>
protected override void OnInnerResultCompleted(CoroutineExecutionContext context, IResult innerResult, ResultCompletionEventArgs args) {
if (args.Error != null || !args.WasCancelled) {
OnCompleted(new ResultCompletionEventArgs {Error = args.Error});
}
else {
Log.Info(string.Format("Executing coroutine because {0} was cancelled.", innerResult.GetType().Name));
Continue(context);
}
}
void Continue(CoroutineExecutionContext context) {
IResult continueResult;
try {
continueResult = coroutine();
}
catch (Exception ex) {
OnCompleted(new ResultCompletionEventArgs {Error = ex});
return;
}
try {
continueResult.Completed += ContinueCompleted;
IoC.BuildUp(continueResult);
continueResult.Execute(context);
}
catch (Exception ex) {
ContinueCompleted(continueResult, new ResultCompletionEventArgs {Error = ex});
}
}
void ContinueCompleted(object sender, ResultCompletionEventArgs args) {
((IResult)sender).Completed -= ContinueCompleted;
OnCompleted(new ResultCompletionEventArgs {Error = args.Error, WasCancelled = (args.Error == null)});
}
}
}
@@ -0,0 +1,82 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Manages coroutine execution.
/// </summary>
public static class Coroutine {
static readonly ILog Log = LogManager.GetLog(typeof(Coroutine));
/// <summary>
/// Creates the parent enumerator.
/// </summary>
public static Func<IEnumerator<IResult>, IResult> CreateParentEnumerator = inner => new SequentialResult(inner);
/// <summary>
/// Executes a coroutine.
/// </summary>
/// <param name="coroutine">The coroutine to execute.</param>
/// <param name="context">The context to execute the coroutine within.</param>
/// /// <param name="callback">The completion callback for the coroutine.</param>
public static void BeginExecute(IEnumerator<IResult> coroutine, CoroutineExecutionContext context = null, EventHandler<ResultCompletionEventArgs> callback = null) {
Log.Info("Executing coroutine.");
var enumerator = CreateParentEnumerator(coroutine);
IoC.BuildUp(enumerator);
if (callback != null) {
ExecuteOnCompleted(enumerator, callback);
}
ExecuteOnCompleted(enumerator, Completed);
enumerator.Execute(context ?? new CoroutineExecutionContext());
}
/// <summary>
/// Executes a coroutine asynchronous.
/// </summary>
/// <param name="coroutine">The coroutine to execute.</param>
/// <param name="context">The context to execute the coroutine within.</param>
/// <returns>A task that represents the asynchronous coroutine.</returns>
public static Task ExecuteAsync(IEnumerator<IResult> coroutine, CoroutineExecutionContext context = null) {
var taskSource = new TaskCompletionSource<object>();
BeginExecute(coroutine, context, (s, e) => {
if (e.Error != null)
taskSource.SetException(e.Error);
else if (e.WasCancelled)
taskSource.SetCanceled();
else
taskSource.SetResult(null);
});
return taskSource.Task;
}
static void ExecuteOnCompleted(IResult result, EventHandler<ResultCompletionEventArgs> handler) {
EventHandler<ResultCompletionEventArgs> onCompledted = null;
onCompledted = (s, e) => {
result.Completed -= onCompledted;
handler(s, e);
};
result.Completed += onCompledted;
}
/// <summary>
/// Called upon completion of a coroutine.
/// </summary>
public static event EventHandler<ResultCompletionEventArgs> Completed = (s, e) => {
if(e.Error != null) {
Log.Error(e.Error);
}
else if(e.WasCancelled) {
Log.Info("Coroutine execution cancelled.");
}
else {
Log.Info("Coroutine execution completed.");
}
};
}
}
@@ -0,0 +1,21 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// The context used during the execution of a Coroutine.
/// </summary>
public class CoroutineExecutionContext {
/// <summary>
/// The source from which the message originates.
/// </summary>
public object Source;
/// <summary>
/// The view associated with the target.
/// </summary>
public object View;
/// <summary>
/// The instance on which the action is invoked.
/// </summary>
public object Target;
}
}
@@ -0,0 +1,13 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// EventArgs sent during deactivation.
/// </summary>
public class DeactivationEventArgs : EventArgs {
/// <summary>
/// Indicates whether the sender was closed in addition to being deactivated.
/// </summary>
public bool WasClosed;
}
}
@@ -0,0 +1,47 @@
#define DEBUG
namespace Caliburn.Micro.Core {
using System;
using System.Diagnostics;
/// <summary>
/// A simple logger thats logs everything to the debugger.
/// </summary>
public class DebugLog : ILog {
private readonly string typeName;
/// <summary>
/// Initializes a new instance of the <see cref="DebugLog"/> class.
/// </summary>
/// <param name="type">The type.</param>
public DebugLog(Type type) {
typeName = type.FullName;
}
/// <summary>
/// Logs the message as info.
/// </summary>
/// <param name="format">A formatted message.</param>
/// <param name="args">Parameters to be injected into the formatted message.</param>
public void Info(string format, params object[] args) {
Debug.WriteLine("[{1}] INFO: {0}", string.Format(format, args), typeName);
}
/// <summary>
/// Logs the message as a warning.
/// </summary>
/// <param name="format">A formatted message.</param>
/// <param name="args">Parameters to be injected into the formatted message.</param>
public void Warn(string format, params object[] args) {
Debug.WriteLine("[{1}] WARN: {0}", string.Format(format, args), typeName);
}
/// <summary>
/// Logs the exception.
/// </summary>
/// <param name="exception">The exception.</param>
public void Error(Exception exception) {
Debug.WriteLine("[{1}] ERROR: {0}", exception, typeName);
}
}
}
@@ -0,0 +1,70 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// Used to gather the results from multiple child elements which may or may not prevent closing.
/// </summary>
/// <typeparam name="T">The type of child element.</typeparam>
public class DefaultCloseStrategy<T> : ICloseStrategy<T> {
readonly bool closeConductedItemsWhenConductorCannotClose;
/// <summary>
/// Creates an instance of the class.
/// </summary>
/// <param name="closeConductedItemsWhenConductorCannotClose">Indicates that even if all conducted items are not closable, those that are should be closed. The default is FALSE.</param>
public DefaultCloseStrategy(bool closeConductedItemsWhenConductorCannotClose = false) {
this.closeConductedItemsWhenConductorCannotClose = closeConductedItemsWhenConductorCannotClose;
}
/// <summary>
/// Executes the strategy.
/// </summary>
/// <param name="toClose">Items that are requesting close.</param>
/// <param name="callback">The action to call when all enumeration is complete and the close results are aggregated.
/// The bool indicates whether close can occur. The enumerable indicates which children should close if the parent cannot.</param>
public void Execute(IEnumerable<T> toClose, Action<bool, IEnumerable<T>> callback) {
using (var enumerator = toClose.GetEnumerator()) {
Evaluate(new EvaluationState(), enumerator, callback);
}
}
void Evaluate(EvaluationState state, IEnumerator<T> enumerator, Action<bool, IEnumerable<T>> callback) {
var guardPending = false;
do {
if (!enumerator.MoveNext()) {
callback(state.FinalResult, closeConductedItemsWhenConductorCannotClose ? state.Closable : new List<T>());
break;
}
var current = enumerator.Current;
var guard = current as IGuardClose;
if (guard != null) {
guardPending = true;
guard.CanClose(canClose => {
guardPending = false;
if (canClose) {
state.Closable.Add(current);
}
state.FinalResult = state.FinalResult && canClose;
if (state.GuardMustCallEvaluate) {
state.GuardMustCallEvaluate = false;
Evaluate(state, enumerator, callback);
}
});
state.GuardMustCallEvaluate = state.GuardMustCallEvaluate || guardPending;
} else {
state.Closable.Add(current);
}
} while (!guardPending);
}
class EvaluationState {
public readonly List<T> Closable = new List<T>();
public bool FinalResult = true;
public bool GuardMustCallEvaluate;
}
}
}
@@ -0,0 +1,91 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Default implementation for <see cref="IPlatformProvider"/> that does no platform enlightenment.
/// </summary>
public class DefaultPlatformProvider : IPlatformProvider {
/// <summary>
/// Indicates whether or not the framework is in design-time mode.
/// </summary>
public bool InDesignMode {
get { return true; }
}
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name="action">The action to execute.</param>
public void BeginOnUIThread(Action action) {
action();
}
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns></returns>
public Task OnUIThreadAsync(Action action) {
return Task.Factory.StartNew(action);
}
/// <summary>
/// Executes the action on the UI thread.
/// </summary>
/// <param name="action">The action to execute.</param>
public void OnUIThread(Action action) {
action();
}
/// <summary>
/// Used to retrieve the root, non-framework-created view.
/// </summary>
/// <param name="view">The view to search.</param>
/// <returns>
/// The root element that was not created by the framework.
/// </returns>
/// <remarks>
/// In certain instances the services create UI elements.
/// For example, if you ask the window manager to show a UserControl as a dialog, it creates a window to host the UserControl in.
/// The WindowManager marks that element as a framework-created element so that it can determine what it created vs. what was intended by the developer.
/// Calling GetFirstNonGeneratedView allows the framework to discover what the original element was.
/// </remarks>
public object GetFirstNonGeneratedView(object view) {
return view;
}
/// <summary>
/// Executes the handler the fist time the view is loaded.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="handler">The handler.</param>
/// <returns>true if the handler was executed immediately; false otherwise</returns>
public void ExecuteOnFirstLoad(object view, Action<object> handler) {
handler(view);
}
/// <summary>
/// Executes the handler the next time the view's LayoutUpdated event fires.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="handler">The handler.</param>
public void ExecuteOnLayoutUpdated(object view, Action<object> handler) {
handler(view);
}
/// <summary>
/// Get the close action for the specified view model.
/// </summary>
/// <param name="viewModel">The view model to close.</param>
/// <param name="views">The associated views.</param>
/// <param name="dialogResult">The dialog result.</param>
/// <returns>
/// An <see cref="Action" /> to close the view model.
/// </returns>
public Action GetViewCloseAction(object viewModel, ICollection<object> views, bool? dialogResult) {
return () => { };
}
}
}
@@ -0,0 +1,83 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A result that executes an <see cref="System.Action"/>.
/// </summary>
public class DelegateResult : IResult {
readonly Action toExecute;
/// <summary>
/// Initializes a new instance of the <see cref="DelegateResult"/> class.
/// </summary>
/// <param name="action">The action.</param>
public DelegateResult(Action action) {
toExecute = action;
}
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
var eventArgs = new ResultCompletionEventArgs();
try {
toExecute();
}
catch (Exception ex) {
eventArgs.Error = ex;
}
Completed(this, eventArgs);
}
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
/// <summary>
/// A result that executes a <see cref="System.Func&lt;TResult&gt;"/>
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public class DelegateResult<TResult> : IResult<TResult> {
readonly Func<TResult> toExecute;
/// <summary>
/// Initializes a new instance of the <see cref="DelegateResult&lt;TResult&gt;"/> class.
/// </summary>
/// <param name="action">The action.</param>
public DelegateResult(Func<TResult> action) {
toExecute = action;
}
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
var eventArgs = new ResultCompletionEventArgs();
try {
Result = toExecute();
}
catch (Exception ex) {
eventArgs.Error = ex;
}
Completed(this, eventArgs);
}
/// <summary>
/// Gets the result.
/// </summary>
public TResult Result { get; private set; }
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
}
@@ -0,0 +1,21 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// Extension methods for <see cref="IEnumerable&lt;T&gt;"/>
/// </summary>
public static class EnumerableExtensions {
/// <summary>
/// Applies the action to each element in the list.
/// </summary>
/// <typeparam name="T">The enumerable item's type.</typeparam>
/// <param name="enumerable">The elements to enumerate.</param>
/// <param name="action">The action to apply to each item in the list.</param>
public static void Apply<T>(this IEnumerable<T> enumerable, Action<T> action) {
foreach (var item in enumerable) {
action(item);
}
}
}
}
@@ -0,0 +1,170 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// Enables loosely-coupled publication of and subscription to events.
/// </summary>
public class EventAggregator : IEventAggregator {
static readonly ILog Log = LogManager.GetLog(typeof(EventAggregator));
readonly List<Handler> handlers = new List<Handler>();
/// <summary>
/// Processing of handler results on publication thread.
/// </summary>
public static Action<object, object> HandlerResultProcessing = (target, result) => { };
/// <summary>
/// Searches the subscribed handlers to check if we have a handler for
/// the message type supplied.
/// </summary>
/// <param name="messageType">The message type to check with</param>
/// <returns>True if any handler is found, false if not.</returns>
public bool HandlerExistsFor(Type messageType) {
return handlers.Any(handler => handler.Handles(messageType) & !handler.IsDead);
}
/// <summary>
/// Subscribes an instance to all events declared through implementations of <see cref = "IHandle{T}" />
/// </summary>
/// <param name = "subscriber">The instance to subscribe for event publication.</param>
public virtual void Subscribe(object subscriber) {
if (subscriber == null) {
throw new ArgumentNullException("subscriber");
}
lock(handlers) {
if (handlers.Any(x => x.Matches(subscriber))) {
return;
}
handlers.Add(new Handler(subscriber));
}
}
/// <summary>
/// Unsubscribes the instance from all events.
/// </summary>
/// <param name = "subscriber">The instance to unsubscribe.</param>
public virtual void Unsubscribe(object subscriber) {
if (subscriber == null) {
throw new ArgumentNullException("subscriber");
}
lock(handlers) {
var found = handlers.FirstOrDefault(x => x.Matches(subscriber));
if (found != null) {
handlers.Remove(found);
}
}
}
public virtual bool IsHandlerDead(object subscriber)
{
if (subscriber == null)
{
throw new ArgumentNullException("subscriber");
}
lock (handlers)
{
foreach (var @handler in handlers)
if (@handler.IsDead)
handlers.Remove(@handler);
if (handlers.Any(x => x.Matches(subscriber)))
return false;
return true;
}
}
/// <summary>
/// Publishes a message.
/// </summary>
/// <param name = "message">The message instance.</param>
/// <param name = "marshal">Allows the publisher to provide a custom thread marshaller for the message publication.</param>
public virtual void Publish(object message, Action<System.Action> marshal) {
if (message == null){
throw new ArgumentNullException("message");
}
if (marshal == null) {
throw new ArgumentNullException("marshal");
}
Handler[] toNotify;
lock (handlers) {
toNotify = handlers.ToArray();
}
marshal(() => {
var messageType = message.GetType();
var dead = toNotify
.Where(handler => !handler.Handle(messageType, message))
.ToList();
if(dead.Any()) {
lock(handlers) {
dead.Apply(x => handlers.Remove(x));
}
}
});
}
class Handler {
readonly object reference;
readonly Dictionary<Type, MethodInfo> supportedHandlers = new Dictionary<Type, MethodInfo>();
public bool IsDead {
//get { return reference.Target == null; }
get { return reference == null; }
}
public Handler(object handler) {
//reference = new WeakReference(handler);
reference = handler;
var interfaces = handler.GetType().GetInterfaces()
.Where(x => typeof(IHandle).IsAssignableFrom(x) && x.IsGenericType());
foreach(var @interface in interfaces) {
var type = @interface.GetGenericArguments()[0];
var method = @interface.GetMethod("Handle", new Type[] { type });
if (method != null) {
supportedHandlers[type] = method;
}
}
}
public bool Matches(object instance) {
return reference == instance;
}
public bool Handle(Type messageType, object message) {
//var target = reference.Target;
var target = reference;
if (target == null) {
Log.Info("Subscriber missing.");
return false;
}
foreach(var pair in supportedHandlers) {
if(pair.Key.IsAssignableFrom(messageType)) {
var result = pair.Value.Invoke(target, new[] { message });
if (result != null) {
HandlerResultProcessing(target, result);
}
}
}
return true;
}
public bool Handles(Type messageType) {
return supportedHandlers.Any(pair => pair.Key.IsAssignableFrom(messageType));
}
}
}
}
@@ -0,0 +1,56 @@
namespace Caliburn.Micro.Core {
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extensions for <see cref="IEventAggregator"/>.
/// </summary>
public static class EventAggregatorExtensions {
/// <summary>
/// Publishes a message on the current thread (synchrone).
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name = "message">The message instance.</param>
public static void PublishOnCurrentThread(this IEventAggregator eventAggregator, object message) {
eventAggregator.Publish(message, action => action());
}
/// <summary>
/// Publishes a message on a background thread (async).
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name = "message">The message instance.</param>
public static void PublishOnBackgroundThread(this IEventAggregator eventAggregator, object message) {
eventAggregator.Publish(message, action => Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default));
}
/// <summary>
/// Publishes a message on the UI thread.
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name = "message">The message instance.</param>
public static void PublishOnUIThread(this IEventAggregator eventAggregator, object message) {
eventAggregator.Publish(message, Execute.OnUIThread);
}
/// <summary>
/// Publishes a message on the UI thread asynchrone.
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name = "message">The message instance.</param>
public static void BeginPublishOnUIThread(this IEventAggregator eventAggregator, object message) {
eventAggregator.Publish(message, Execute.BeginOnUIThread);
}
/// <summary>
/// Publishes a message on the UI thread asynchrone.
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name="message">The message instance.</param>
public static Task PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message) {
Task task = null;
eventAggregator.Publish(message, action => task = action.OnUIThreadAsync());
return task;
}
}
}
@@ -0,0 +1,42 @@
namespace Caliburn.Micro.Core {
using System;
using System.Threading.Tasks;
/// <summary>
/// Enables easy marshalling of code to the UI thread.
/// </summary>
public static class Execute {
/// <summary>
/// Indicates whether or not the framework is in design-time mode.
/// </summary>
public static bool InDesignMode {
get {
return PlatformProvider.Current.InDesignMode;
}
}
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void BeginOnUIThread(this Action action) {
PlatformProvider.Current.BeginOnUIThread(action);
}
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name = "action">The action to execute.</param>
public static Task OnUIThreadAsync(this Action action) {
return PlatformProvider.Current.OnUIThreadAsync(action);
}
/// <summary>
/// Executes the action on the UI thread.
/// </summary>
/// <param name = "action">The action to execute.</param>
public static void OnUIThread(this Action action) {
PlatformProvider.Current.OnUIThread(action);
}
}
}
@@ -0,0 +1,29 @@
namespace Caliburn.Micro.Core {
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Extension for <see cref="Expression"/>.
/// </summary>
public static class ExpressionExtensions {
/// <summary>
/// Converts an expression into a <see cref="MemberInfo"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>The member info.</returns>
public static MemberInfo GetMemberInfo(this Expression expression) {
var lambda = (LambdaExpression) expression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression) {
var unaryExpression = (UnaryExpression) lambda.Body;
memberExpression = (MemberExpression) unaryExpression.Operand;
}
else {
memberExpression = (MemberExpression) lambda.Body;
}
return memberExpression.Member;
}
}
}
@@ -0,0 +1,73 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// Generic extension methods used by the framework.
/// </summary>
public static class ExtensionMethods {
/// <summary>
/// Get's the name of the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>The assembly's name.</returns>
public static string GetAssemblyName(this Assembly assembly) {
return assembly.FullName.Remove(assembly.FullName.IndexOf(','));
}
/// <summary>
/// Gets all the attributes of a particular type.
/// </summary>
/// <typeparam name="T">The type of attributes to get.</typeparam>
/// <param name="member">The member to inspect for attributes.</param>
/// <param name="inherit">Whether or not to search for inherited attributes.</param>
/// <returns>The list of attributes found.</returns>
public static IEnumerable<T> GetAttributes<T>(this MemberInfo member, bool inherit) {
#if WinRT || CORE
return member.GetCustomAttributes(inherit).OfType<T>();
#else
return Attribute.GetCustomAttributes(member, inherit).OfType<T>();
#endif
}
#if WinRT || CORE
/// <summary>
/// Gets a collection of the public types defined in this assembly that are visible outside the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A collection of the public types defined in this assembly that are visible outside the assembly.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static IEnumerable<Type> GetExportedTypes(this Assembly assembly) {
if (assembly == null)
throw new ArgumentNullException("assembly");
return assembly.ExportedTypes;
}
/// <summary>
/// Returns a value that indicates whether the specified type can be assigned to the current type.
/// </summary>
/// <param name="target">The target type</param>
/// <param name="type">The type to check.</param>
/// <returns>true if the specified type can be assigned to this type; otherwise, false.</returns>
public static bool IsAssignableFrom(this Type target, Type type) {
return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo());
}
#endif
/// <summary>
/// Gets the value for a key. If the key does not exist, return default(TValue);
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <param name="dictionary">The dictionary to call this method on.</param>
/// <param name="key">The key to look up.</param>
/// <returns>The key value. default(TValue) if this key is not in the dictionary.</returns>
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) {
TValue result;
return dictionary.TryGetValue(key, out result) ? result : default(TValue);
}
}
}
@@ -0,0 +1,23 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Denotes an instance which requires activation.
/// </summary>
public interface IActivate {
///<summary>
/// Indicates whether or not this instance is active.
///</summary>
bool IsActive { get; }
/// <summary>
/// Activates this instance.
/// </summary>
void Activate();
/// <summary>
/// Raised after activation occurs.
/// </summary>
event EventHandler<ActivationEventArgs> Activated;
}
}
@@ -0,0 +1,22 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Denotes a node within a parent/child hierarchy.
/// </summary>
public interface IChild {
/// <summary>
/// Gets or Sets the Parent
/// </summary>
object Parent { get; set; }
}
/// <summary>
/// Denotes a node within a parent/child hierarchy.
/// </summary>
/// <typeparam name="TParent">The type of parent.</typeparam>
public interface IChild<TParent> : IChild {
/// <summary>
/// Gets or Sets the Parent
/// </summary>
new TParent Parent { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Denotes an object that can be closed.
/// </summary>
public interface IClose {
/// <summary>
/// Tries to close this instance.
/// Also provides an opportunity to pass a dialog result to it's corresponding view.
/// </summary>
/// <param name="dialogResult">The dialog result.</param>
void TryClose(bool? dialogResult = null);
}
}
@@ -0,0 +1,18 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// Used to gather the results from multiple child elements which may or may not prevent closing.
/// </summary>
/// <typeparam name="T">The type of child element.</typeparam>
public interface ICloseStrategy<T> {
/// <summary>
/// Executes the strategy.
/// </summary>
/// <param name="toClose">Items that are requesting close.</param>
/// <param name="callback">The action to call when all enumeration is complete and the close results are aggregated.
/// The bool indicates whether close can occur. The enumerable indicates which children should close if the parent cannot.</param>
void Execute(IEnumerable<T> toClose, Action<bool, IEnumerable<T>> callback);
}
}
@@ -0,0 +1,32 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Denotes an instance which conducts other objects by managing an ActiveItem and maintaining a strict lifecycle.
/// </summary>
/// <remarks>Conducted instances can optin to the lifecycle by impelenting any of the follosing <see cref="IActivate"/>, <see cref="IDeactivate"/>, <see cref="IGuardClose"/>.</remarks>
public interface IConductor : IParent, INotifyPropertyChangedEx {
/// <summary>
/// Activates the specified item.
/// </summary>
/// <param name="item">The item to activate.</param>
void ActivateItem(object item);
/// <summary>
/// Deactivates the specified item.
/// </summary>
/// <param name="item">The item to close.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
void DeactivateItem(object item, bool close);
/// <summary>
/// Occurs when an activation request is processed.
/// </summary>
event EventHandler<ActivationProcessedEventArgs> ActivationProcessed;
}
/// <summary>
/// An <see cref="IConductor"/> that also implements <see cref="IHaveActiveItem"/>.
/// </summary>
public interface IConductActiveItem : IConductor, IHaveActiveItem { }
}
@@ -0,0 +1,24 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Denotes an instance which requires deactivation.
/// </summary>
public interface IDeactivate {
/// <summary>
/// Raised before deactivation.
/// </summary>
event EventHandler<DeactivationEventArgs> AttemptingDeactivation;
/// <summary>
/// Deactivates this instance.
/// </summary>
/// <param name="close">Indicates whether or not this instance is being closed.</param>
void Deactivate(bool close);
/// <summary>
/// Raised after deactivation.
/// </summary>
event EventHandler<DeactivationEventArgs> Deactivated;
}
}
@@ -0,0 +1,35 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Enables loosely-coupled publication of and subscription to events.
/// </summary>
public interface IEventAggregator {
/// <summary>
/// Searches the subscribed handlers to check if we have a handler for
/// the message type supplied.
/// </summary>
/// <param name="messageType">The message type to check with</param>
/// <returns>True if any handler is found, false if not.</returns>
bool HandlerExistsFor(Type messageType);
/// <summary>
/// Subscribes an instance to all events declared through implementations of <see cref = "IHandle{T}" />
/// </summary>
/// <param name = "subscriber">The instance to subscribe for event publication.</param>
void Subscribe(object subscriber);
/// <summary>
/// Unsubscribes the instance from all events.
/// </summary>
/// <param name = "subscriber">The instance to unsubscribe.</param>
void Unsubscribe(object subscriber);
/// <summary>
/// Publishes a message.
/// </summary>
/// <param name = "message">The message instance.</param>
/// <param name = "marshal">Allows the publisher to provide a custom thread marshaller for the message publication.</param>
void Publish(object message, Action<System.Action> marshal);
}
}
@@ -0,0 +1,14 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Denotes an instance which may prevent closing.
/// </summary>
public interface IGuardClose : IClose {
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name="callback">The implementer calls this action with the result of the close check.</param>
void CanClose(Action<bool> callback);
}
}
@@ -0,0 +1,19 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// A marker interface for classes that subscribe to messages.
/// </summary>
public interface IHandle {
}
/// <summary>
/// Denotes a class which can handle a particular type of message.
/// </summary>
/// <typeparam name = "TMessage">The type of message to handle.</typeparam>
public interface IHandle<TMessage> : IHandle { //don't use contravariance here
/// <summary>
/// Handles the message.
/// </summary>
/// <param name = "message">The message.</param>
void Handle(TMessage message);
}
}
@@ -0,0 +1,15 @@
namespace Caliburn.Micro.Core {
using System.Collections.Generic;
/// <summary>
/// Denotes a class which can handle a particular type of message and uses a Coroutine to do so.
/// </summary>
public interface IHandleWithCoroutine<TMessage> : IHandle { //don't use contravariance here
/// <summary>
/// Handle the message with a Coroutine.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>The coroutine to execute.</returns>
IEnumerable<IResult> Handle(TMessage message);
}
}
@@ -0,0 +1,15 @@
namespace Caliburn.Micro.Core {
using System.Threading.Tasks;
/// <summary>
/// Denotes a class which can handle a particular type of message and uses a Task to do so.
/// </summary>
public interface IHandleWithTask<TMessage> : IHandle { //don't use contravariance here
/// <summary>
/// Handle the message with a Task.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>The Task that represents the operation.</returns>
Task Handle(TMessage message);
}
}
@@ -0,0 +1,11 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Denotes an instance which maintains an active item.
/// </summary>
public interface IHaveActiveItem {
/// <summary>
/// The currently active item.
/// </summary>
object ActiveItem { get; set; }
}
}
@@ -0,0 +1,11 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Denotes an instance which has a display name.
/// </summary>
public interface IHaveDisplayName {
/// <summary>
/// Gets or Sets the Display Name
/// </summary>
string DisplayName { get; set; }
}
}
@@ -0,0 +1,28 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A logger.
/// </summary>
public interface ILog {
/// <summary>
/// Logs the message as info.
/// </summary>
/// <param name="format">A formatted message.</param>
/// <param name="args">Parameters to be injected into the formatted message.</param>
void Info(string format, params object[] args);
/// <summary>
/// Logs the message as a warning.
/// </summary>
/// <param name="format">A formatted message.</param>
/// <param name="args">Parameters to be injected into the formatted message.</param>
void Warn(string format, params object[] args);
/// <summary>
/// Logs the exception.
/// </summary>
/// <param name="exception">The exception.</param>
void Error(Exception exception);
}
}
@@ -0,0 +1,24 @@
namespace Caliburn.Micro.Core {
using System.ComponentModel;
/// <summary>
/// Extends <see cref = "INotifyPropertyChanged" /> such that the change event can be raised by external parties.
/// </summary>
public interface INotifyPropertyChangedEx : INotifyPropertyChanged {
/// <summary>
/// Enables/Disables property change notification.
/// </summary>
bool IsNotifying { get; set; }
/// <summary>
/// Notifies subscribers of the property change.
/// </summary>
/// <param name = "propertyName">Name of the property.</param>
void NotifyOfPropertyChange(string propertyName);
/// <summary>
/// Raises a change notification indicating that all bindings should be refreshed.
/// </summary>
void Refresh();
}
}
@@ -0,0 +1,22 @@
namespace Caliburn.Micro.Core {
using System.Collections.Generic;
using System.Collections.Specialized;
/// <summary>
/// Represents a collection that is observable.
/// </summary>
/// <typeparam name = "T">The type of elements contained in the collection.</typeparam>
public interface IObservableCollection<T> : IList<T>, INotifyPropertyChangedEx, INotifyCollectionChanged {
/// <summary>
/// Adds the range.
/// </summary>
/// <param name = "items">The items.</param>
void AddRange(IEnumerable<T> items);
/// <summary>
/// Removes the range.
/// </summary>
/// <param name = "items">The items.</param>
void RemoveRange(IEnumerable<T> items);
}
}
@@ -0,0 +1,31 @@
namespace Caliburn.Micro.Core {
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Interface used to define an object associated to a collection of children.
/// </summary>
public interface IParent {
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>
/// The collection of children.
/// </returns>
IEnumerable GetChildren();
}
/// <summary>
/// Interface used to define a specialized parent.
/// </summary>
/// <typeparam name="T">The type of children.</typeparam>
public interface IParent<out T> : IParent {
/// <summary>
/// Gets the children.
/// </summary>
/// <returns>
/// The collection of children.
/// </returns>
new IEnumerable<T> GetChildren();
}
}
@@ -0,0 +1,76 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Interface for platform specific operations that need enlightenment.
/// </summary>
public interface IPlatformProvider {
#region Execute
/// <summary>
/// Indicates whether or not the framework is in design-time mode.
/// </summary>
bool InDesignMode { get; }
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name="action">The action to execute.</param>
void BeginOnUIThread(Action action);
/// <summary>
/// Executes the action on the UI thread asynchronously.
/// </summary>
/// <param name = "action">The action to execute.</param>
Task OnUIThreadAsync(Action action);
/// <summary>
/// Executes the action on the UI thread.
/// </summary>
/// <param name = "action">The action to execute.</param>
void OnUIThread(Action action);
#endregion
#region ViewAware
/// <summary>
/// Used to retrieve the root, non-framework-created view.
/// </summary>
/// <param name="view">The view to search.</param>
/// <returns>The root element that was not created by the framework.</returns>
/// <remarks>In certain instances the services create UI elements.
/// For example, if you ask the window manager to show a UserControl as a dialog, it creates a window to host the UserControl in.
/// The WindowManager marks that element as a framework-created element so that it can determine what it created vs. what was intended by the developer.
/// Calling GetFirstNonGeneratedView allows the framework to discover what the original element was.
/// </remarks>
object GetFirstNonGeneratedView(object view);
/// <summary>
/// Executes the handler the fist time the view is loaded.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="handler">The handler.</param>
void ExecuteOnFirstLoad(object view, Action<object> handler);
/// <summary>
/// Executes the handler the next time the view's LayoutUpdated event fires.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="handler">The handler.</param>
void ExecuteOnLayoutUpdated(object view, Action<object> handler);
/// <summary>
/// Get the close action for the specified view model.
/// </summary>
/// <param name="viewModel">The view model to close.</param>
/// <param name="views">The associated views.</param>
/// <param name="dialogResult">The dialog result.</param>
/// <returns>An <see cref="Action"/> to close the view model.</returns>
Action GetViewCloseAction(object viewModel, ICollection<object> views, bool? dialogResult);
#endregion
}
}
@@ -0,0 +1,31 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Allows custom code to execute after the return of a action.
/// </summary>
public interface IResult {
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
void Execute(CoroutineExecutionContext context);
/// <summary>
/// Occurs when execution has completed.
/// </summary>
event EventHandler<ResultCompletionEventArgs> Completed;
}
/// <summary>
/// Allows custom code to execute after the return of a action.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public interface IResult<out TResult> : IResult
{
/// <summary>
/// Gets the result of the asynchronous operation.
/// </summary>
TResult Result { get; }
}
}
@@ -0,0 +1,8 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Denotes an instance which implements <see cref="IHaveDisplayName"/>, <see cref="IActivate"/>,
/// <see cref="IDeactivate"/>, <see cref="IGuardClose"/> and <see cref="INotifyPropertyChangedEx"/>
/// </summary>
public interface IScreen : IHaveDisplayName, IActivate, IDeactivate, IGuardClose, INotifyPropertyChangedEx {
}
}
@@ -0,0 +1,27 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Denotes a class which is aware of its view(s).
/// </summary>
public interface IViewAware {
/// <summary>
/// Attaches a view to this instance.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="context">The context in which the view appears.</param>
void AttachView(object view, object context = null);
/// <summary>
/// Gets a view previously attached to this instance.
/// </summary>
/// <param name="context">The context denoting which view to retrieve.</param>
/// <returns>The view.</returns>
object GetView(object context = null);
/// <summary>
/// Raised when a view is attached.
/// </summary>
event EventHandler<ViewAttachedEventArgs> ViewAttached;
}
}
@@ -0,0 +1,44 @@
namespace Caliburn.Micro.Core {
using System;
using System.Linq;
using System.Collections.Generic;
/// <summary>
/// Used by the framework to pull instances from an IoC container and to inject dependencies into certain existing classes.
/// </summary>
public static class IoC {
/// <summary>
/// Gets an instance by type and key.
/// </summary>
public static Func<Type, string, object> GetInstance = (service, key) => { throw new InvalidOperationException("IoC is not initialized."); };
/// <summary>
/// Gets all instances of a particular type.
/// </summary>
public static Func<Type, IEnumerable<object>> GetAllInstances = service => { throw new InvalidOperationException("IoC is not initialized."); };
/// <summary>
/// Passes an existing instance to the IoC container to enable dependencies to be injected.
/// </summary>
public static Action<object> BuildUp = instance => { throw new InvalidOperationException("IoC is not initialized."); };
/// <summary>
/// Gets an instance from the container.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="key">The key to look up.</param>
/// <returns>The resolved instance.</returns>
public static T Get<T>(string key = null) {
return (T)GetInstance(typeof(T), key);
}
/// <summary>
/// Gets all instances of a particular type.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <returns>The resolved instances.</returns>
public static IEnumerable<T> GetAll<T>() {
return GetAllInstances(typeof(T)).Cast<T>();
}
}
}
@@ -0,0 +1,21 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Used to manage logging.
/// </summary>
public static class LogManager {
static readonly ILog NullLogInstance = new NullLog();
/// <summary>
/// Creates an <see cref="ILog"/> for the provided type.
/// </summary>
public static Func<Type, ILog> GetLog = type => NullLogInstance;
class NullLog : ILog {
public void Info(string format, params object[] args) { }
public void Warn(string format, params object[] args) { }
public void Error(Exception exception) { }
}
}
}
@@ -0,0 +1,135 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
/// <summary>
/// Class for managing the list of rules for doing name transformation.
/// </summary>
public class NameTransformer : BindableCollection<NameTransformer.Rule> {
#if NET
private const RegexOptions options = RegexOptions.Compiled;
#else
private const RegexOptions options = RegexOptions.None;
#endif
bool useEagerRuleSelection = true;
/// <summary>
/// Flag to indicate if transformations from all matched rules are returned. Otherwise, transformations from only the first matched rule are returned.
/// </summary>
public bool UseEagerRuleSelection {
get { return useEagerRuleSelection; }
set { useEagerRuleSelection = value; }
}
/// <summary>
/// Adds a transform using a single replacement value and a global filter pattern.
/// </summary>
/// <param name = "replacePattern">Regular expression pattern for replacing text</param>
/// <param name = "replaceValue">The replacement value.</param>
/// <param name = "globalFilterPattern">Regular expression pattern for global filtering</param>
public void AddRule(string replacePattern, string replaceValue, string globalFilterPattern = null) {
AddRule(replacePattern, new[] { replaceValue }, globalFilterPattern);
}
/// <summary>
/// Adds a transform using a list of replacement values and a global filter pattern.
/// </summary>
/// <param name = "replacePattern">Regular expression pattern for replacing text</param>
/// <param name = "replaceValueList">The list of replacement values</param>
/// <param name = "globalFilterPattern">Regular expression pattern for global filtering</param>
public void AddRule(string replacePattern, IEnumerable<string> replaceValueList, string globalFilterPattern = null) {
Add(new Rule {
ReplacePattern = replacePattern,
ReplacementValues = replaceValueList,
GlobalFilterPattern = globalFilterPattern
});
}
/// <summary>
/// Gets the list of transformations for a given name.
/// </summary>
/// <param name = "source">The name to transform into the resolved name list</param>
/// <returns>The transformed names.</returns>
public IEnumerable<string> Transform(string source) {
return Transform(source, r => r);
}
/// <summary>
/// Gets the list of transformations for a given name.
/// </summary>
/// <param name = "source">The name to transform into the resolved name list</param>
/// <param name = "getReplaceString">A function to do a transform on each item in the ReplaceValueList prior to applying the regular expression transform</param>
/// <returns>The transformed names.</returns>
public IEnumerable<string> Transform(string source, Func<string, string> getReplaceString) {
var nameList = new List<string>();
var rules = this.Reverse();
foreach(var rule in rules) {
if(!string.IsNullOrEmpty(rule.GlobalFilterPattern) && !rule.GlobalFilterPatternRegex.IsMatch(source)) {
continue;
}
if(!rule.ReplacePatternRegex.IsMatch(source)) {
continue;
}
nameList.AddRange(
rule.ReplacementValues
.Select(getReplaceString)
.Select(repString => rule.ReplacePatternRegex.Replace(source, repString))
);
if (!useEagerRuleSelection) {
break;
}
}
return nameList;
}
///<summary>
/// A rule that describes a name transform.
///</summary>
public class Rule {
private Regex replacePatternRegex;
private Regex globalFilterPatternRegex;
/// <summary>
/// Regular expression pattern for global filtering
/// </summary>
public string GlobalFilterPattern;
/// <summary>
/// Regular expression pattern for replacing text
/// </summary>
public string ReplacePattern;
/// <summary>
/// The list of replacement values
/// </summary>
public IEnumerable<string> ReplacementValues;
/// <summary>
/// Regular expression for global filtering
/// </summary>
public Regex GlobalFilterPatternRegex {
get {
return globalFilterPatternRegex ?? (globalFilterPatternRegex = new Regex(GlobalFilterPattern, options));
}
}
/// <summary>
/// Regular expression for replacing text
/// </summary>
public Regex ReplacePatternRegex {
get {
return replacePatternRegex ?? (replacePatternRegex = new Regex(ReplacePattern, options));
}
}
}
}
}
@@ -0,0 +1,28 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// A result decorator that overrides <see cref="ResultCompletionEventArgs.WasCancelled"/> of the decorated <see cref="IResult"/> instance.
/// </summary>
public class OverrideCancelResultDecorator : ResultDecoratorBase {
static readonly ILog Log = LogManager.GetLog(typeof(OverrideCancelResultDecorator));
/// <summary>
/// Initializes a new instance of the <see cref="OverrideCancelResultDecorator"/> class.
/// </summary>
/// <param name="result">The result to decorate.</param>
public OverrideCancelResultDecorator(IResult result)
: base(result) { }
/// <summary>
/// Called when the execution of the decorated result has completed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="innerResult">The decorated result.</param>
/// <param name="args">The <see cref="ResultCompletionEventArgs" /> instance containing the event data.</param>
protected override void OnInnerResultCompleted(CoroutineExecutionContext context, IResult innerResult, ResultCompletionEventArgs args) {
if (args.WasCancelled)
Log.Info(string.Format("Overriding WasCancelled from {0}.", innerResult.GetType().Name));
OnCompleted(new ResultCompletionEventArgs { Error = args.Error });
}
}
}
@@ -0,0 +1,16 @@
namespace Caliburn.Micro.Core {
/// <summary>
/// Access the current <see cref="IPlatformProvider"/>.
/// </summary>
public static class PlatformProvider {
private static IPlatformProvider current = new DefaultPlatformProvider();
/// <summary>
/// Gets or sets the current <see cref="IPlatformProvider"/>.
/// </summary>
public static IPlatformProvider Current {
get { return current; }
set { current = value; }
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Caliburn.Micro.Core
{
/// <summary>
/// A collection of extension methods to help with differing reflection between the portable library and SL5
/// </summary>
internal static class PortableReflectionExtensions {
public static bool IsAssignableFrom(this Type t, Type c) {
return t.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());
}
public static Type[] GetGenericArguments(this Type t) {
return t.GetTypeInfo().GenericTypeArguments;
}
public static IEnumerable<PropertyInfo> GetProperties(this Type t) {
return t.GetRuntimeProperties();
}
public static IEnumerable<ConstructorInfo> GetConstructors(this Type t) {
return t.GetTypeInfo().DeclaredConstructors;
}
public static IEnumerable<Type> GetInterfaces(this Type t) {
return t.GetTypeInfo().ImplementedInterfaces;
}
public static IEnumerable<Type> GetTypes(this Assembly a) {
return a.DefinedTypes.Select(t => t.AsType());
}
public static bool IsAbstract(this Type t) {
return t.GetTypeInfo().IsAbstract;
}
public static bool IsInterface(this Type t) {
return t.GetTypeInfo().IsInterface;
}
public static bool IsGenericType(this Type t) {
return t.GetTypeInfo().IsGenericType;
}
public static MethodInfo GetMethod(this Type t, string name, Type[] parameters) {
return t.GetRuntimeMethod(name, parameters);
}
}
}
@@ -0,0 +1,90 @@
namespace Caliburn.Micro.Core {
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
/// <summary>
/// A base class that implements the infrastructure for property change notification and automatically performs UI thread marshalling.
/// </summary>
[DataContract]
public class PropertyChangedBase : INotifyPropertyChangedEx {
/// <summary>
/// Creates an instance of <see cref = "PropertyChangedBase" />.
/// </summary>
public PropertyChangedBase() {
IsNotifying = true;
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Enables/Disables property change notification.
/// Virtualized in order to help with document oriented view models.
/// </summary>
public virtual bool IsNotifying { get; set; }
/// <summary>
/// Raises a change notification indicating that all bindings should be refreshed.
/// </summary>
public virtual void Refresh() {
NotifyOfPropertyChange(string.Empty);
}
/// <summary>
/// Notifies subscribers of the property change.
/// </summary>
/// <param name = "propertyName">Name of the property.</param>
#if NET || SILVERLIGHT
public virtual void NotifyOfPropertyChange([CallerMemberName] string propertyName = null) {
#else
public virtual void NotifyOfPropertyChange([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) {
#endif
if (IsNotifying && PropertyChanged != null) {
Execute.OnUIThread(() => OnPropertyChanged(new PropertyChangedEventArgs(propertyName)));
}
}
/// <summary>
/// Notifies subscribers of the property change.
/// </summary>
/// <typeparam name = "TProperty">The type of the property.</typeparam>
/// <param name = "property">The property expression.</param>
public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property) {
NotifyOfPropertyChange(property.GetMemberInfo().Name);
}
/// <summary>
/// Raises the <see cref="PropertyChanged" /> event directly.
/// </summary>
/// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
protected void OnPropertyChanged(PropertyChangedEventArgs e) {
var handler = PropertyChanged;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the property changed event immediately.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
public virtual void RaisePropertyChangedEventImmediately(string propertyName)
{
if (IsNotifying)
RaisePropertyChangedEventCore(propertyName);
}
void RaisePropertyChangedEventCore(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@@ -0,0 +1,65 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Helper class for encoding strings to regular expression patterns
/// </summary>
public static class RegExHelper {
/// <summary>
/// Regular expression pattern for valid name
/// </summary>
public const string NameRegEx = @"[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}_]*";
/// <summary>
/// Regular expression pattern for subnamespace (including dot)
/// </summary>
public const string SubNamespaceRegEx = NameRegEx + @"\.";
/// <summary>
/// Regular expression pattern for namespace or namespace fragment
/// </summary>
public const string NamespaceRegEx = "(" + SubNamespaceRegEx + ")*";
/// <summary>
/// Creates a named capture group with the specified regular expression
/// </summary>
/// <param name="groupName">Name of capture group to create</param>
/// <param name="regEx">Regular expression pattern to capture</param>
/// <returns>Regular expression capture group with the specified group name</returns>
public static string GetCaptureGroup(string groupName, string regEx) {
return String.Concat(@"(?<", groupName, ">", regEx, ")");
}
/// <summary>
/// Converts a namespace (including wildcards) to a regular expression string
/// </summary>
/// <param name="srcNamespace">Source namespace to convert to regular expression</param>
/// <returns>Namespace converted to a regular expression</returns>
public static string NamespaceToRegEx(string srcNamespace) {
//Need to escape the "." as it's a special character in regular expression syntax
var nsencoded = srcNamespace.Replace(".", @"\.");
//Replace "*" wildcard with regular expression syntax
nsencoded = nsencoded.Replace(@"*\.", NamespaceRegEx);
return nsencoded;
}
/// <summary>
/// Creates a capture group for a valid name regular expression pattern
/// </summary>
/// <param name="groupName">Name of capture group to create</param>
/// <returns>Regular expression capture group with the specified group name</returns>
public static string GetNameCaptureGroup(string groupName) {
return GetCaptureGroup(groupName, NameRegEx);
}
/// <summary>
/// Creates a capture group for a namespace regular expression pattern
/// </summary>
/// <param name="groupName">Name of capture group to create</param>
/// <returns>Regular expression capture group with the specified group name</returns>
public static string GetNamespaceCaptureGroup(string groupName) {
return GetCaptureGroup(groupName, NamespaceRegEx);
}
}
}
@@ -0,0 +1,74 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A result decorator which rescues errors from the decorated result by executing a rescue coroutine.
/// </summary>
/// <typeparam name="TException">The type of the exception we want to perform the rescue on</typeparam>
public class RescueResultDecorator<TException> : ResultDecoratorBase where TException : Exception {
static readonly ILog Log = LogManager.GetLog(typeof(RescueResultDecorator<>));
readonly bool cancelResult;
readonly Func<TException, IResult> coroutine;
/// <summary>
/// Initializes a new instance of the <see cref="RescueResultDecorator&lt;TException&gt;"/> class.
/// </summary>
/// <param name="result">The result to decorate.</param>
/// <param name="coroutine">The rescue coroutine.</param>
/// <param name="cancelResult">Set to true to cancel the result after executing rescue.</param>
public RescueResultDecorator(IResult result, Func<TException, IResult> coroutine, bool cancelResult = true) : base(result) {
if (coroutine == null)
throw new ArgumentNullException("coroutine");
this.coroutine = coroutine;
this.cancelResult = cancelResult;
}
/// <summary>
/// Called when the execution of the decorated result has completed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="innerResult">The decorated result.</param>
/// <param name="args">The <see cref="ResultCompletionEventArgs" /> instance containing the event data.</param>
protected override void OnInnerResultCompleted(CoroutineExecutionContext context, IResult innerResult, ResultCompletionEventArgs args) {
var error = args.Error as TException;
if (error == null) {
OnCompleted(args);
}
else {
Log.Error(error);
Log.Info(string.Format("Executing coroutine because {0} threw an exception.", innerResult.GetType().Name));
Rescue(context, error);
}
}
void Rescue(CoroutineExecutionContext context, TException exception) {
IResult rescueResult;
try {
rescueResult = coroutine(exception);
}
catch (Exception ex) {
OnCompleted(new ResultCompletionEventArgs {Error = ex});
return;
}
try {
rescueResult.Completed += RescueCompleted;
IoC.BuildUp(rescueResult);
rescueResult.Execute(context);
}
catch (Exception ex) {
RescueCompleted(rescueResult, new ResultCompletionEventArgs {Error = ex});
}
}
void RescueCompleted(object sender, ResultCompletionEventArgs args) {
((IResult)sender).Completed -= RescueCompleted;
OnCompleted(new ResultCompletionEventArgs
{
Error = args.Error,
WasCancelled = (args.Error == null && (args.WasCancelled || cancelResult))
});
}
}
}
@@ -0,0 +1,20 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// The event args for the Completed event of an <see cref="IResult"/>.
/// </summary>
public class ResultCompletionEventArgs : EventArgs {
/// <summary>
/// Gets or sets the error if one occurred.
/// </summary>
/// <value>The error.</value>
public Exception Error;
/// <summary>
/// Gets or sets a value indicating whether the result was cancelled.
/// </summary>
/// <value><c>true</c> if cancelled; otherwise, <c>false</c>.</value>
public bool WasCancelled;
}
}
@@ -0,0 +1,66 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Base class for all <see cref="IResult"/> decorators.
/// </summary>
public abstract class ResultDecoratorBase : IResult {
readonly IResult innerResult;
CoroutineExecutionContext context;
/// <summary>
/// Initializes a new instance of the <see cref="ResultDecoratorBase"/> class.
/// </summary>
/// <param name="result">The result to decorate.</param>
protected ResultDecoratorBase(IResult result) {
if (result == null)
throw new ArgumentNullException("result");
innerResult = result;
}
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
this.context = context;
try {
innerResult.Completed += InnerResultCompleted;
IoC.BuildUp(innerResult);
innerResult.Execute(this.context);
}
catch (Exception ex) {
InnerResultCompleted(innerResult, new ResultCompletionEventArgs { Error = ex });
}
}
void InnerResultCompleted(object sender, ResultCompletionEventArgs args) {
innerResult.Completed -= InnerResultCompleted;
OnInnerResultCompleted(context, innerResult, args);
context = null;
}
/// <summary>
/// Called when the execution of the decorated result has completed.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="innerResult">The decorated result.</param>
/// <param name="args">The <see cref="ResultCompletionEventArgs"/> instance containing the event data.</param>
protected abstract void OnInnerResultCompleted(CoroutineExecutionContext context, IResult innerResult, ResultCompletionEventArgs args);
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
/// <summary>
/// Raises the <see cref="Completed" /> event.
/// </summary>
/// <param name="args">The <see cref="ResultCompletionEventArgs"/> instance containing the event data.</param>
protected void OnCompleted(ResultCompletionEventArgs args) {
Completed(this, args);
}
}
}
@@ -0,0 +1,53 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Extension methods for <see cref="IResult"/> instances.
/// </summary>
public static class ResultExtensions {
/// <summary>
/// Adds behavior to the result which is executed when the <paramref name ="result"/> was cancelled.
/// </summary>
/// <param name="result">The result to decorate.</param>
/// <param name="coroutine">The coroutine to execute when <paramref name="result"/> was canceled.</param>
/// <returns></returns>
public static IResult WhenCancelled(this IResult result, Func<IResult> coroutine) {
return new ContinueResultDecorator(result, coroutine);
}
/// <summary>
/// Overrides <see cref="ResultCompletionEventArgs.WasCancelled"/> of the decorated <paramref name="result"/> instance.
/// </summary>
/// <param name="result">The result to decorate.</param>
/// <returns></returns>
public static IResult OverrideCancel(this IResult result) {
return new OverrideCancelResultDecorator(result);
}
/// <summary>
/// Rescues <typeparamref name="TException"/> from the decorated <paramref name="result"/> by executing a <paramref name="rescue"/> coroutine.
/// </summary>
/// <typeparam name = "TException">The type of the exception we want to perform the rescue on.</typeparam>
/// <param name="result">The result to decorate.</param>
/// <param name="rescue">The rescue coroutine.</param>
/// <param name="cancelResult">Set to true to cancel the result after executing rescue.</param>
/// <returns></returns>
public static IResult Rescue<TException>(this IResult result, Func<TException, IResult> rescue,
bool cancelResult = true)
where TException : Exception {
return new RescueResultDecorator<TException>(result, rescue, cancelResult);
}
/// <summary>
/// Rescues any exception from the decorated <paramref name="result"/> by executing a <paramref name="rescue"/> coroutine.
/// </summary>
/// <param name="result">The result to decorate.</param>
/// <param name="rescue">The rescue coroutine.</param>
/// <param name="cancelResult">Set to true to cancel the result after executing rescue.</param>
/// <returns></returns>
public static IResult Rescue(this IResult result, Func<Exception, IResult> rescue,
bool cancelResult = true) {
return Rescue<Exception>(result, rescue, cancelResult);
}
}
}
@@ -0,0 +1,170 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A base implementation of <see cref = "IScreen" />.
/// </summary>
public class Screen : ViewAware, IScreen, IChild {
static readonly ILog Log = LogManager.GetLog(typeof (Screen));
bool isActive;
bool isInitialized;
object parent;
string displayName;
/// <summary>
/// Creates an instance of the screen.
/// </summary>
public Screen() {
displayName = GetType().FullName;
}
/// <summary>
/// Gets or Sets the Parent <see cref = "IConductor" />
/// </summary>
public virtual object Parent {
get { return parent; }
set {
parent = value;
NotifyOfPropertyChange("Parent");
}
}
/// <summary>
/// Gets or Sets the Display Name
/// </summary>
public virtual string DisplayName {
get { return displayName; }
set {
displayName = value;
NotifyOfPropertyChange("DisplayName");
}
}
/// <summary>
/// Indicates whether or not this instance is currently active.
/// Virtualized in order to help with document oriented view models.
/// </summary>
public virtual bool IsActive {
get { return isActive; }
private set {
isActive = value;
NotifyOfPropertyChange("IsActive");
}
}
/// <summary>
/// Indicates whether or not this instance is currently initialized.
/// Virtualized in order to help with document oriented view models.
/// </summary>
public virtual bool IsInitialized {
get { return isInitialized; }
private set {
isInitialized = value;
NotifyOfPropertyChange("IsInitialized");
}
}
/// <summary>
/// Raised after activation occurs.
/// </summary>
public virtual event EventHandler<ActivationEventArgs> Activated = delegate { };
/// <summary>
/// Raised before deactivation.
/// </summary>
public virtual event EventHandler<DeactivationEventArgs> AttemptingDeactivation = delegate { };
/// <summary>
/// Raised after deactivation.
/// </summary>
public virtual event EventHandler<DeactivationEventArgs> Deactivated = delegate { };
void IActivate.Activate() {
if (IsActive) {
return;
}
var initialized = false;
if (!IsInitialized) {
IsInitialized = initialized = true;
OnInitialize();
}
IsActive = true;
Log.Info("Activating {0}.", this);
OnActivate();
var handler = Activated;
if (handler != null) {
handler(this, new ActivationEventArgs
{
WasInitialized = initialized
});
}
}
/// <summary>
/// Called when initializing.
/// </summary>
protected virtual void OnInitialize() {}
/// <summary>
/// Called when activating.
/// </summary>
protected virtual void OnActivate() {}
void IDeactivate.Deactivate(bool close) {
if (IsActive || (IsInitialized && close)) {
var attemptingDeactivationHandler = AttemptingDeactivation;
if (attemptingDeactivationHandler != null) {
attemptingDeactivationHandler(this, new DeactivationEventArgs
{
WasClosed = close
});
}
IsActive = false;
Log.Info("Deactivating {0}.", this);
OnDeactivate(close);
var deactivatedHandler = Deactivated;
if (deactivatedHandler != null) {
deactivatedHandler(this, new DeactivationEventArgs
{
WasClosed = close
});
}
if (close) {
Views.Clear();
Log.Info("Closed {0}.", this);
}
}
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name = "close">Inidicates whether this instance will be closed.</param>
protected virtual void OnDeactivate(bool close) {}
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name = "callback">The implementor calls this action with the result of the close check.</param>
public virtual void CanClose(Action<bool> callback) {
callback(true);
}
/// <summary>
/// Tries to close this instance by asking its Parent to initiate shutdown or by asking its corresponding view to close.
/// Also provides an opportunity to pass a dialog result to it's corresponding view.
/// </summary>
/// <param name="dialogResult">The dialog result.</param>
public virtual void TryClose(bool? dialogResult = null) {
PlatformProvider.Current.GetViewCloseAction(this, Views.Values, dialogResult).OnUIThread();
}
}
}
@@ -0,0 +1,96 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// Hosts extension methods for <see cref="IScreen"/> classes.
/// </summary>
public static class ScreenExtensions {
/// <summary>
/// Activates the item if it implements <see cref="IActivate"/>, otherwise does nothing.
/// </summary>
/// <param name="potentialActivatable">The potential activatable.</param>
public static void TryActivate(object potentialActivatable) {
var activator = potentialActivatable as IActivate;
if (activator != null)
activator.Activate();
}
/// <summary>
/// Deactivates the item if it implements <see cref="IDeactivate"/>, otherwise does nothing.
/// </summary>
/// <param name="potentialDeactivatable">The potential deactivatable.</param>
/// <param name="close">Indicates whether or not to close the item after deactivating it.</param>
public static void TryDeactivate(object potentialDeactivatable, bool close) {
var deactivator = potentialDeactivatable as IDeactivate;
if (deactivator != null)
deactivator.Deactivate(close);
}
/// <summary>
/// Closes the specified item.
/// </summary>
/// <param name="conductor">The conductor.</param>
/// <param name="item">The item to close.</param>
public static void CloseItem(this IConductor conductor, object item) {
conductor.DeactivateItem(item, true);
}
/// <summary>
/// Closes the specified item.
/// </summary>
/// <param name="conductor">The conductor.</param>
/// <param name="item">The item to close.</param>
public static void CloseItem<T>(this ConductorBase<T> conductor, T item) where T: class {
conductor.DeactivateItem(item, true);
}
///<summary>
/// Activates a child whenever the specified parent is activated.
///</summary>
///<param name="child">The child to activate.</param>
///<param name="parent">The parent whose activation triggers the child's activation.</param>
public static void ActivateWith(this IActivate child, IActivate parent) {
var childReference = new WeakReference(child);
EventHandler<ActivationEventArgs> handler = null;
handler = (s, e) => {
var activatable = (IActivate) childReference.Target;
if (activatable == null)
((IActivate) s).Activated -= handler;
else
activatable.Activate();
};
parent.Activated += handler;
}
///<summary>
/// Deactivates a child whenever the specified parent is deactivated.
///</summary>
///<param name="child">The child to deactivate.</param>
///<param name="parent">The parent whose deactivation triggers the child's deactivation.</param>
public static void DeactivateWith(this IDeactivate child, IDeactivate parent) {
var childReference = new WeakReference(child);
EventHandler<DeactivationEventArgs> handler = null;
handler = (s, e) => {
var deactivatable = (IDeactivate) childReference.Target;
if (deactivatable == null)
((IDeactivate)s).Deactivated -= handler;
else
deactivatable.Deactivate(e.WasClosed);
};
parent.Deactivated += handler;
}
///<summary>
/// Activates and Deactivates a child whenever the specified parent is Activated or Deactivated.
///</summary>
///<param name="child">The child to activate/deactivate.</param>
///<param name="parent">The parent whose activation/deactivation triggers the child's activation/deactivation.</param>
public static void ConductWith<TChild, TParent>(this TChild child, TParent parent)
where TChild : IActivate, IDeactivate
where TParent : IActivate, IDeactivate
{
child.ActivateWith(parent);
child.DeactivateWith(parent);
}
}
}
@@ -0,0 +1,76 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// An implementation of <see cref = "IResult" /> that enables sequential execution of multiple results.
/// </summary>
public class SequentialResult : IResult {
readonly IEnumerator<IResult> enumerator;
CoroutineExecutionContext context;
/// <summary>
/// Initializes a new instance of the <see cref = "SequentialResult" /> class.
/// </summary>
/// <param name = "enumerator">The enumerator.</param>
public SequentialResult(IEnumerator<IResult> enumerator) {
this.enumerator = enumerator;
}
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name = "context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
this.context = context;
ChildCompleted(null, new ResultCompletionEventArgs());
}
void ChildCompleted(object sender, ResultCompletionEventArgs args) {
var previous = sender as IResult;
if (previous != null) {
previous.Completed -= ChildCompleted;
}
if(args.Error != null || args.WasCancelled) {
OnComplete(args.Error, args.WasCancelled);
return;
}
var moveNextSucceeded = false;
try {
moveNextSucceeded = enumerator.MoveNext();
}
catch(Exception ex) {
OnComplete(ex, false);
return;
}
if(moveNextSucceeded) {
try {
var next = enumerator.Current;
IoC.BuildUp(next);
next.Completed += ChildCompleted;
next.Execute(context);
}
catch(Exception ex) {
OnComplete(ex, false);
return;
}
}
else {
OnComplete(null, false);
}
}
void OnComplete(Exception error, bool wasCancelled) {
enumerator.Dispose();
Completed(this, new ResultCompletionEventArgs { Error = error, WasCancelled = wasCancelled });
}
}
}
@@ -0,0 +1,242 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// A simple IoC container.
/// </summary>
public class SimpleContainer {
static readonly Type delegateType = typeof(Delegate);
static readonly Type enumerableType = typeof(IEnumerable);
readonly List<ContainerEntry> entries;
/// <summary>
/// Initializes a new instance of the <see cref = "SimpleContainer" /> class.
/// </summary>
public SimpleContainer() {
entries = new List<ContainerEntry>();
}
SimpleContainer(IEnumerable<ContainerEntry> entries) {
this.entries = new List<ContainerEntry>(entries);
}
/// <summary>
/// Registers the instance.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
/// <param name = "implementation">The implementation.</param>
public void RegisterInstance(Type service, string key, object implementation) {
RegisterHandler(service, key, container => implementation);
}
/// <summary>
/// Registers the class so that a new instance is created on every request.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
/// <param name = "implementation">The implementation.</param>
public void RegisterPerRequest(Type service, string key, Type implementation) {
RegisterHandler(service, key, container => container.BuildInstance(implementation));
}
/// <summary>
/// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
/// <param name = "implementation">The implementation.</param>
public void RegisterSingleton(Type service, string key, Type implementation) {
object singleton = null;
RegisterHandler(service, key, container => singleton ?? (singleton = container.BuildInstance(implementation)));
}
/// <summary>
/// Registers a custom handler for serving requests from the container.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
/// <param name = "handler">The handler.</param>
public void RegisterHandler(Type service, string key, Func<SimpleContainer, object> handler) {
GetOrCreateEntry(service, key).Add(handler);
}
/// <summary>
/// Unregisters any handlers for the service/key that have previously been registered.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
public void UnregisterHandler(Type service, string key) {
var entry = GetEntry(service, key);
if (entry != null) {
entries.Remove(entry);
}
}
/// <summary>
/// Requests an instance.
/// </summary>
/// <param name = "service">The service.</param>
/// <param name = "key">The key.</param>
/// <returns>The instance, or null if a handler is not found.</returns>
public object GetInstance(Type service, string key) {
var entry = GetEntry(service, key);
if (entry != null) {
return entry.Single()(this);
}
if (service == null) {
return null;
}
if (delegateType.IsAssignableFrom(service)) {
var typeToCreate = service.GetGenericArguments()[0];
var factoryFactoryType = typeof(FactoryFactory<>).MakeGenericType(typeToCreate);
var factoryFactoryHost = Activator.CreateInstance(factoryFactoryType);
var factoryFactoryMethod = factoryFactoryType.GetMethod("Create", new Type[] { typeof(SimpleContainer) });
return factoryFactoryMethod.Invoke(factoryFactoryHost, new object[] { this });
}
if (enumerableType.IsAssignableFrom(service) && service.IsGenericType()) {
var listType = service.GetGenericArguments()[0];
var instances = GetAllInstances(listType).ToList();
var array = Array.CreateInstance(listType, instances.Count);
for (var i = 0; i < array.Length; i++) {
array.SetValue(instances[i], i);
}
return array;
}
return null;
}
/// <summary>
/// Determines if a handler for the service/key has previously been registered.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="key">The key.</param>
/// <returns>True if a handler is registere; false otherwise.</returns>
public bool HasHandler(Type service, string key) {
return GetEntry(service, key) != null;
}
/// <summary>
/// Requests all instances of a given type.
/// </summary>
/// <param name = "service">The service.</param>
/// <returns>All the instances or an empty enumerable if none are found.</returns>
public IEnumerable<object> GetAllInstances(Type service) {
var entry = GetEntry(service, null);
return entry != null ? entry.Select(x => x(this)) : new object[0];
}
/// <summary>
/// Pushes dependencies into an existing instance based on interface properties with setters.
/// </summary>
/// <param name = "instance">The instance.</param>
public void BuildUp(object instance) {
var injectables = from property in instance.GetType().GetProperties()
where property.CanRead && property.CanWrite && property.PropertyType.IsInterface()
select property;
foreach (var propertyInfo in injectables) {
var injection = GetAllInstances(propertyInfo.PropertyType).ToArray();
if (injection.Any()) {
propertyInfo.SetValue(instance, injection.First(), null);
}
}
}
/// <summary>
/// Creates a child container.
/// </summary>
/// <returns>A new container.</returns>
public SimpleContainer CreateChildContainer() {
return new SimpleContainer(entries);
}
ContainerEntry GetOrCreateEntry(Type service, string key) {
var entry = GetEntry(service, key);
if (entry == null) {
entry = new ContainerEntry { Service = service, Key = key };
entries.Add(entry);
}
return entry;
}
ContainerEntry GetEntry(Type service, string key) {
if (service == null) {
return entries.FirstOrDefault(x => x.Key == key);
}
if (key == null) {
return entries.FirstOrDefault(x => x.Service == service && x.Key == null)
?? entries.FirstOrDefault(x => x.Service == service);
}
return entries.FirstOrDefault(x => x.Service == service && x.Key == key);
}
/// <summary>
/// Actually does the work of creating the instance and satisfying it's constructor dependencies.
/// </summary>
/// <param name = "type">The type.</param>
/// <returns></returns>
protected object BuildInstance(Type type) {
var args = DetermineConstructorArgs(type);
return ActivateInstance(type, args);
}
/// <summary>
/// Creates an instance of the type with the specified constructor arguments.
/// </summary>
/// <param name = "type">The type.</param>
/// <param name = "args">The constructor args.</param>
/// <returns>The created instance.</returns>
protected virtual object ActivateInstance(Type type, object[] args) {
var instance = args.Length > 0 ? System.Activator.CreateInstance(type, args) : System.Activator.CreateInstance(type);
Activated(instance);
return instance;
}
/// <summary>
/// Occurs when a new instance is created.
/// </summary>
public event Action<object> Activated = delegate { };
object[] DetermineConstructorArgs(Type implementation) {
var args = new List<object>();
var constructor = SelectEligibleConstructor(implementation);
if (constructor != null)
args.AddRange(constructor.GetParameters().Select(info => GetInstance(info.ParameterType, null)));
return args.ToArray();
}
static ConstructorInfo SelectEligibleConstructor(Type type) {
return (from c in type.GetConstructors().Where(c => c.IsPublic)
orderby c.GetParameters().Length descending
select c).FirstOrDefault();
}
class ContainerEntry : List<Func<SimpleContainer, object>> {
public string Key;
public Type Service;
}
class FactoryFactory<T> {
public Func<T> Create(SimpleContainer container) {
return () => (T)container.GetInstance(typeof(T), null);
}
}
}
}
@@ -0,0 +1,51 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// A simple result.
/// </summary>
public sealed class SimpleResult : IResult {
readonly bool wasCancelled;
readonly Exception error;
private SimpleResult(bool wasCancelled, Exception error) {
this.wasCancelled = wasCancelled;
this.error = error;
}
/// <summary>
/// A result that is always succeeded.
/// </summary>
public static IResult Succeeded() {
return new SimpleResult(false, null);
}
/// <summary>
/// A result that is always canceled.
/// </summary>
/// <returns>The result.</returns>
public static IResult Cancelled() {
return new SimpleResult(true, null);
}
/// <summary>
/// A result that is always failed.
/// </summary>
public static IResult Failed(Exception error) {
return new SimpleResult(false, error);
}
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
Completed(this, new ResultCompletionEventArgs {WasCancelled = wasCancelled, Error = error});
}
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
}
@@ -0,0 +1,141 @@
using System.Collections.Generic;
using System.Text;
namespace Caliburn.Micro.Core {
/// <summary>
/// Helper class when splitting strings
/// </summary>
public static class StringSplitter {
/// <summary>
/// Splits a string with a chosen separator.
/// If a substring is contained in [...] it will not be splitted.
/// </summary>
/// <param name="message">The message to split</param>
/// <param name="separator">The separator to use when splitting</param>
/// <returns></returns>
public static string[] Split(string message, char separator)
{
//Splits a string using the specified separator, if it is found outside of relevant places
//delimited by [ and ]
string str;
var list = new List<string>();
var builder = new StringBuilder();
int squareBrackets = 0;
#if WinRT
foreach (var current in message.ToCharArray())
{
#else
foreach(var current in message) {
#endif
//Square brackets are used as delimiters, so only separators outside them count...
if (current == '[')
{
squareBrackets++;
}
else if (current == ']')
{
squareBrackets--;
}
else if (current == separator)
{
if (squareBrackets == 0)
{
str = builder.ToString();
if (!string.IsNullOrEmpty(str))
list.Add(builder.ToString());
builder.Length = 0;
continue;
}
}
builder.Append(current);
}
str = builder.ToString();
if (!string.IsNullOrEmpty(str))
{
list.Add(builder.ToString());
}
return list.ToArray();
}
/// <summary>
/// Splits a string with , as separator.
/// Does not split within {},[],()
/// </summary>
/// <param name="parameters">The string to split</param>
/// <returns></returns>
public static string[] SplitParameters(string parameters)
{
//Splits parameter string taking into account brackets...
var list = new List<string>();
var builder = new StringBuilder();
bool isInString = false;
int curlyBrackets = 0;
int squareBrackets = 0;
int roundBrackets = 0;
for (int i = 0; i < parameters.Length; i++)
{
var current = parameters[i];
if (current == '"')
{
if (i == 0 || parameters[i - 1] != '\\')
{
isInString = !isInString;
}
}
if (!isInString)
{
switch (current)
{
case '{':
curlyBrackets++;
break;
case '}':
curlyBrackets--;
break;
case '[':
squareBrackets++;
break;
case ']':
squareBrackets--;
break;
case '(':
roundBrackets++;
break;
case ')':
roundBrackets--;
break;
default:
if (current == ',' && roundBrackets == 0 && squareBrackets == 0 && curlyBrackets == 0)
{
//The only commas to be considered as parameter separators are outside:
//- Strings
//- Square brackets (to ignore indexers)
//- Parantheses (to ignore method invocations)
//- Curly brackets (to ignore initializers and Bindings)
list.Add(builder.ToString());
builder.Length = 0;
continue;
}
break;
}
}
builder.Append(current);
}
list.Add(builder.ToString());
return list.ToArray();
}
}
}
@@ -0,0 +1,80 @@
namespace Caliburn.Micro.Core {
using System;
using System.Threading.Tasks;
/// <summary>
/// Extension methods to bring <see cref="System.Threading.Tasks.Task"/> and <see cref="IResult"/> together.
/// </summary>
public static class TaskExtensions {
/// <summary>
/// Executes an <see cref="IResult"/> asynchronous.
/// </summary>
/// <param name="result">The coroutine to execute.</param>
/// <param name="context">The context to execute the coroutine within.</param>
/// <returns>A task that represents the asynchronous coroutine.</returns>
public static Task ExecuteAsync(this IResult result, CoroutineExecutionContext context = null) {
return InternalExecuteAsync<object>(result, context);
}
/// <summary>
/// Executes an <see cref="IResult"/> asynchronous.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="result">The coroutine to execute.</param>
/// <param name="context">The context to execute the coroutine within.</param>
/// <returns>A task that represents the asynchronous coroutine.</returns>
public static Task<TResult> ExecuteAsync<TResult>(this IResult<TResult> result,
CoroutineExecutionContext context = null) {
return InternalExecuteAsync<TResult>(result, context);
}
static Task<TResult> InternalExecuteAsync<TResult>(IResult result, CoroutineExecutionContext context) {
var taskSource = new TaskCompletionSource<TResult>();
EventHandler<ResultCompletionEventArgs> completed = null;
completed = (s, e) => {
result.Completed -= completed;
if (e.Error != null)
taskSource.SetException(e.Error);
else if (e.WasCancelled)
taskSource.SetCanceled();
else {
var rr = result as IResult<TResult>;
taskSource.SetResult(rr != null ? rr.Result : default(TResult));
}
};
try {
IoC.BuildUp(result);
result.Completed += completed;
result.Execute(context ?? new CoroutineExecutionContext());
}
catch (Exception ex) {
result.Completed -= completed;
taskSource.SetException(ex);
}
return taskSource.Task;
}
/// <summary>
/// Encapsulates a task inside a couroutine.
/// </summary>
/// <param name="task">The task.</param>
/// <returns>The coroutine that encapsulates the task.</returns>
public static TaskResult AsResult(this Task task) {
return new TaskResult(task);
}
/// <summary>
/// Encapsulates a task inside a couroutine.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="task">The task.</param>
/// <returns>The coroutine that encapsulates the task.</returns>
public static TaskResult<TResult> AsResult<TResult>(this Task<TResult> task) {
return new TaskResult<TResult>(task);
}
}
}
@@ -0,0 +1,76 @@
namespace Caliburn.Micro.Core {
using System;
using System.Threading.Tasks;
/// <summary>
/// A couroutine that encapsulates an <see cref="System.Threading.Tasks.Task"/>.
/// </summary>
public class TaskResult : IResult {
readonly Task innerTask;
/// <summary>
/// Initializes a new instance of the <see cref="TaskResult"/> class.
/// </summary>
/// <param name="task">The task.</param>
public TaskResult(Task task) {
innerTask = task;
}
/// <summary>
/// Executes the result using the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(CoroutineExecutionContext context) {
if (innerTask.IsCompleted)
OnCompleted(innerTask);
else
innerTask.ContinueWith(OnCompleted,
System.Threading.SynchronizationContext.Current != null
? TaskScheduler.FromCurrentSynchronizationContext()
: TaskScheduler.Current);
}
/// <summary>
/// Called when the asynchronous task has completed.
/// </summary>
/// <param name="task">The completed task.</param>
protected virtual void OnCompleted(Task task) {
Completed(this, new ResultCompletionEventArgs {WasCancelled = task.IsCanceled, Error = task.Exception});
}
/// <summary>
/// Occurs when execution has completed.
/// </summary>
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
/// <summary>
/// A couroutine that encapsulates an <see cref="System.Threading.Tasks.Task&lt;TResult&gt;"/>.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public class TaskResult<TResult> : TaskResult, IResult<TResult> {
/// <summary>
/// Initializes a new instance of the <see cref="TaskResult{TResult}"/> class.
/// </summary>
/// <param name="task">The task.</param>
public TaskResult(Task<TResult> task)
: base(task) {
}
/// <summary>
/// Gets the result of the asynchronous operation.
/// </summary>
public TResult Result { get; private set; }
/// <summary>
/// Called when the asynchronous task has completed.
/// </summary>
/// <param name="task">The completed task.</param>
protected override void OnCompleted(Task task) {
if (!task.IsFaulted && !task.IsCanceled)
Result = ((Task<TResult>) task).Result;
base.OnCompleted(task);
}
}
}
@@ -0,0 +1,44 @@
namespace Caliburn.Micro.Core {
using System.Collections.Generic;
/// <summary>
/// Class to specify settings for configuring type mappings by the ViewLocator or ViewModelLocator
/// </summary>
public class TypeMappingConfiguration {
/// <summary>
/// The default subnamespace for Views. Used for creating default subnamespace mappings. Defaults to "Views".
/// </summary>
public string DefaultSubNamespaceForViews = "Views";
/// <summary>
/// The default subnamespace for ViewModels. Used for creating default subnamespace mappings. Defaults to "ViewModels".
/// </summary>
public string DefaultSubNamespaceForViewModels = "ViewModels";
/// <summary>
/// Flag to indicate whether or not the name of the Type should be transformed when adding a type mapping. Defaults to true.
/// </summary>
public bool UseNameSuffixesInMappings = true;
/// <summary>
/// The format string used to compose the name of a type from base name and name suffix
/// </summary>
public string NameFormat = @"{0}{1}";
/// <summary>
/// Flag to indicate if ViewModel names should include View suffixes (i.e. CustomerPageViewModel vs. CustomerViewModel)
/// </summary>
public bool IncludeViewSuffixInViewModelNames = true;
/// <summary>
/// List of View suffixes for which default type mappings should be created. Applies only when UseNameSuffixesInMappings = true.
/// Default values are "View", "Page"
/// </summary>
public List<string> ViewSuffixList = new List<string>(new[] { "View", "Page" });
/// <summary>
/// The name suffix for ViewModels. Applies only when UseNameSuffixesInMappings = true. The default is "ViewModel".
/// </summary>
public string ViewModelSuffix = "ViewModel";
}
}
@@ -0,0 +1,18 @@
namespace Caliburn.Micro.Core {
using System;
/// <summary>
/// The event args for the <see cref="IViewAware.ViewAttached"/> event.
/// </summary>
public class ViewAttachedEventArgs : EventArgs {
/// <summary>
/// The view.
/// </summary>
public object View;
/// <summary>
/// The context.
/// </summary>
public object Context;
}
}
@@ -0,0 +1,98 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections.Generic;
/// <summary>
/// A base implementation of <see cref = "IViewAware" /> which is capable of caching views by context.
/// </summary>
public class ViewAware : PropertyChangedBase, IViewAware {
readonly IDictionary<object, object> views;
/// <summary>
/// The default view context.
/// </summary>
public static readonly object DefaultContext = new object();
/// <summary>
/// The view chache for this instance.
/// </summary>
protected IDictionary<object, object> Views {
get { return views; }
}
/// <summary>
/// Creates an instance of <see cref="ViewAware"/>.
/// </summary>
public ViewAware() {
views = new WeakValueDictionary<object, object>();
}
/// <summary>
/// Raised when a view is attached.
/// </summary>
public event EventHandler<ViewAttachedEventArgs> ViewAttached = delegate { };
void IViewAware.AttachView(object view, object context) {
Views[context ?? DefaultContext] = view;
var nonGeneratedView = PlatformProvider.Current.GetFirstNonGeneratedView(view);
PlatformProvider.Current.ExecuteOnFirstLoad(nonGeneratedView, OnViewLoaded);
OnViewAttached(nonGeneratedView, context);
ViewAttached(this, new ViewAttachedEventArgs {View = nonGeneratedView, Context = context});
var activatable = this as IActivate;
if (activatable == null || activatable.IsActive) {
PlatformProvider.Current.ExecuteOnLayoutUpdated(nonGeneratedView, OnViewReady);
}
else {
AttachViewReadyOnActivated(activatable, nonGeneratedView);
}
}
static void AttachViewReadyOnActivated(IActivate activatable, object nonGeneratedView) {
var viewReference = new WeakReference(nonGeneratedView);
EventHandler<ActivationEventArgs> handler = null;
handler = (s, e) => {
((IActivate)s).Activated -= handler;
var view = viewReference.Target;
if (view != null) {
PlatformProvider.Current.ExecuteOnLayoutUpdated(view, ((ViewAware)s).OnViewReady);
}
};
activatable.Activated += handler;
}
/// <summary>
/// Called when a view is attached.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="context">The context in which the view appears.</param>
protected virtual void OnViewAttached(object view, object context) {
}
/// <summary>
/// Called when an attached view's Loaded event fires.
/// </summary>
/// <param name = "view"></param>
protected virtual void OnViewLoaded(object view) {
}
/// <summary>
/// Called the first time the page's LayoutUpdated event fires after it is navigated to.
/// </summary>
/// <param name = "view"></param>
protected virtual void OnViewReady(object view) {
}
/// <summary>
/// Gets a view previously attached to this instance.
/// </summary>
/// <param name = "context">The context denoting which view to retrieve.</param>
/// <returns>The view.</returns>
public virtual object GetView(object context = null) {
object view;
Views.TryGetValue(context ?? DefaultContext, out view);
return view;
}
}
}
@@ -0,0 +1,323 @@
namespace Caliburn.Micro.Core {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A dictionary in which the values are weak references.
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values in the dictionary.</typeparam>
internal class WeakValueDictionary<TKey, TValue> : IDictionary<TKey, TValue>
where TValue : class {
private readonly Dictionary<TKey, WeakReference> inner;
private readonly WeakReference gcSentinel = new WeakReference(new object());
#region Cleanup handling
private bool IsCleanupNeeded() {
if (gcSentinel.Target == null) {
gcSentinel.Target = new object();
return true;
}
return false;
}
private void CleanAbandonedItems() {
var keysToRemove = inner.Where(pair => !pair.Value.IsAlive)
.Select(pair => pair.Key)
.ToList();
keysToRemove.Apply(key => inner.Remove(key));
}
private void CleanIfNeeded() {
if (IsCleanupNeeded()) {
CleanAbandonedItems();
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
/// </summary>
public WeakValueDictionary() {
inner = new Dictionary<TKey, WeakReference>();
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that contains elements copied from the specified <see cref="IDictionary&lt;TKey, TValue&gt;"/> and uses the default equality comparer for the key type.
/// </summary>
/// <param name="dictionary">The <see cref="IDictionary&lt;TKey, TValue&gt;"/> whose elements are copied to the new <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.</param>
public WeakValueDictionary(IDictionary<TKey, TValue> dictionary) {
inner = new Dictionary<TKey, WeakReference>();
dictionary.Apply(item => inner.Add(item.Key, new WeakReference(item.Value)));
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that contains elements copied from the specified <see cref="IDictionary&lt;TKey, TValue&gt;"/> and uses the specified <see cref="IEqualityComparer&lt;T&gt;"/>.
/// </summary>
/// <param name="dictionary">The <see cref="IDictionary&lt;TKey, TValue&gt;"/> whose elements are copied to the new <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.</param>
/// <param name="comparer">The <see cref="IEqualityComparer&lt;T&gt;"/> implementation to use when comparing keys, or null to use the default <see cref="EqualityComparer&lt;T&gt;"/> for the type of the key.</param>
public WeakValueDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) {
inner = new Dictionary<TKey, WeakReference>(comparer);
dictionary.Apply(item => inner.Add(item.Key, new WeakReference(item.Value)));
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that is empty, has the default initial capacity, and uses the specified <see cref="IEqualityComparer&lt;T&gt;"/>.
/// </summary>
/// <param name="comparer">The <see cref="IEqualityComparer&lt;T&gt;"/> implementation to use when comparing keys, or null to use the default <see cref="EqualityComparer&lt;T&gt;"/> for the type of the key.</param>
public WeakValueDictionary(IEqualityComparer<TKey> comparer) {
inner = new Dictionary<TKey, WeakReference>(comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.
/// </summary>
/// <param name="capacity">The initial number of elements that the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> can contain.</param>
public WeakValueDictionary(int capacity) {
inner = new Dictionary<TKey, WeakReference>(capacity);
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> class that is empty, has the specified initial capacity, and uses the specified <see cref="IEqualityComparer&lt;T&gt;"/>.
/// </summary>
/// <param name="capacity">The initial number of elements that the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> can contain.</param>
/// <param name="comparer">The <see cref="IEqualityComparer&lt;T&gt;"/> implementation to use when comparing keys, or null to use the default <see cref="EqualityComparer&lt;T&gt;"/> for the type of the key.</param>
public WeakValueDictionary(int capacity, IEqualityComparer<TKey> comparer) {
inner = new Dictionary<TKey, WeakReference>(capacity, comparer);
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
CleanIfNeeded();
var enumerable = inner.Select(pair => new KeyValuePair<TKey, TValue>(pair.Key, (TValue) pair.Value.Target))
.Where(pair => pair.Value != null);
return enumerable.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
Add(item.Key, item.Value);
}
/// <summary>
/// Removes all keys and values from the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
public void Clear() {
inner.Clear();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
TValue value;
if (!TryGetValue(item.Key, out value))
return false;
return value == item.Value;
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
if ((arrayIndex + Count) > array.Length)
throw new ArgumentException(
"The number of elements in the source collection is greater than the available space from arrayIndex to the end of the destination array.");
this.ToArray().CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
TValue value;
if (!TryGetValue(item.Key, out value))
return false;
if (value != item.Value)
return false;
return inner.Remove(item.Key);
}
/// <summary>
/// Gets the number of key/value pairs contained in the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
/// <remarks>
/// Since the items in the dictionary are held by weak reference, the count value
/// cannot be relied upon to guarantee the number of objects that would be discovered via
/// enumeration. Treat the Count as an estimate only.
/// </remarks>
public int Count {
get {
CleanIfNeeded();
return inner.Count;
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get { return false; }
}
/// <summary>
/// Adds the specified key and value to the dictionary.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add. The value can be null for reference types.</param>
public void Add(TKey key, TValue value) {
CleanIfNeeded();
inner.Add(key, new WeakReference(value));
}
/// <summary>
/// Determines whether the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> contains the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.</param>
/// <returns></returns>
public bool ContainsKey(TKey key) {
TValue dummy;
return TryGetValue(key, out dummy);
}
/// <summary>
/// Removes the value with the specified key from the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false. This method returns false if key is not found in the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.</returns>
public bool Remove(TKey key) {
CleanIfNeeded();
return inner.Remove(key);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">
/// When this method returns, contains the value associated with the specified key,
/// if the key is found; otherwise, the default value for the type of the value parameter.
/// This parameter is passed uninitialized.</param>
/// <returns>true if the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/> contains an element with the specified key; otherwise, false.</returns>
public bool TryGetValue(TKey key, out TValue value) {
CleanIfNeeded();
WeakReference wr;
if (!inner.TryGetValue(key, out wr)) {
value = null;
return false;
}
var result = (TValue) wr.Target;
if (result == null) {
inner.Remove(key);
value = null;
return false;
}
value = result;
return true;
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <returns>
/// The value associated with the specified key. If the specified key is not found, a get operation throws a <see cref="KeyNotFoundException"/>,
/// and a set operation creates a new element with the specified key.
/// </returns>
public TValue this[TKey key] {
get {
TValue result;
if (!TryGetValue(key, out result))
throw new KeyNotFoundException();
return result;
}
set {
CleanIfNeeded();
inner[key] = new WeakReference(value);
}
}
/// <summary>
/// Gets a collection containing the keys in the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
public ICollection<TKey> Keys {
get { return inner.Keys; }
}
/// <summary>
/// Gets a collection containing the values in the <see cref="WeakValueDictionary&lt;TKey, TValue&gt;"/>.
/// </summary>
public ICollection<TValue> Values {
get { return new ValueCollection(this); }
}
#region Inner Types
private sealed class ValueCollection : ICollection<TValue> {
private readonly WeakValueDictionary<TKey, TValue> inner;
public ValueCollection(WeakValueDictionary<TKey, TValue> dictionary) {
inner = dictionary;
}
public IEnumerator<TValue> GetEnumerator() {
return inner.Select(pair => pair.Value).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
void ICollection<TValue>.Add(TValue item) {
throw new NotSupportedException();
}
void ICollection<TValue>.Clear() {
throw new NotSupportedException();
}
bool ICollection<TValue>.Contains(TValue item) {
return inner.Any(pair => pair.Value == item);
}
public void CopyTo(TValue[] array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
if ((arrayIndex + Count) > array.Length)
throw new ArgumentException(
"The number of elements in the source collection is greater than the available space from arrayIndex to the end of the destination array.");
this.ToArray().CopyTo(array, arrayIndex);
}
bool ICollection<TValue>.Remove(TValue item) {
throw new NotSupportedException();
}
public int Count {
get { return inner.Count; }
}
bool ICollection<TValue>.IsReadOnly {
get { return true; }
}
}
#endregion
}
}