├── README.md
├── Source
├── Common
│ ├── Services
│ │ ├── IService1.cs
│ │ ├── IService2.cs
│ │ ├── IService3.cs
│ │ ├── Service1.cs
│ │ ├── Service2.cs
│ │ └── Service3.cs
│ ├── Common.csproj
│ ├── ICloneableT.cs
│ ├── IEventAggregator.cs
│ ├── EventAggregator.cs
│ ├── DelegateRule.cs
│ ├── Commands
│ │ ├── Command.cs
│ │ ├── AsyncCommand.cs
│ │ ├── CommandT.cs
│ │ ├── AsyncCommandT.cs
│ │ ├── CommandBase.cs
│ │ ├── DelegateCommand.cs
│ │ ├── AsyncDelegateCommand.cs
│ │ ├── DelegateCommandT.cs
│ │ └── AsyncDelegateCommandT.cs
│ ├── Rule.cs
│ ├── RuleCollection.cs
│ ├── Disposable.cs
│ ├── RevertibleChangeTracking.cs
│ ├── EditableObject.cs
│ ├── NotifyDataErrorInfo.cs
│ └── NotifyPropertyChanges.cs
├── Rx
│ ├── Rx.csproj
│ └── Program.cs
├── CommandPattern
│ ├── CommandPattern.csproj
│ └── Program.cs
├── EventAggregatorPattern
│ ├── EventAggregatorPattern.csproj
│ └── Program.cs
└── ViewModelComposition
│ ├── ViewModelComposition.csproj
│ └── Program.cs
├── LICENSE
├── .gitattributes
├── MVVM-Design-Patterns.sln
├── .gitignore
└── .editorconfig
/README.md:
--------------------------------------------------------------------------------
1 | # MVVM-Design-Patterns
2 | Showcasing the design patterns you can use alongside Model-View-ViewModel (MVVM)
3 |
--------------------------------------------------------------------------------
/Source/Common/Services/IService1.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public interface IService1
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Services/IService2.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public interface IService2
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Services/IService3.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public interface IService3
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Services/Service1.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public class Service1 : IService1
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Services/Service2.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public class Service2 : IService2
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Services/Service3.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Services
2 | {
3 | public class Service3 : IService3
4 | {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Source/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Source/Rx/Rx.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Source/CommandPattern/CommandPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Source/EventAggregatorPattern/EventAggregatorPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Source/ViewModelComposition/ViewModelComposition.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Source/Common/ICloneableT.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 |
5 | ///
6 | /// Produces deep clones of objects.
7 | ///
8 | /// The type of the object to clone.
9 | public interface ICloneable : ICloneable
10 | {
11 | ///
12 | /// Clones the clone-able object of type .
13 | ///
14 | ///
15 | /// The cloned object of type .
16 | ///
17 | new T Clone();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Source/Common/IEventAggregator.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 |
5 | ///
6 | /// Channels events from multiple objects into a single object to simplify registration for clients.
7 | ///
8 | /// See https://www.martinfowler.com/eaaDev/EventAggregator.html.
9 | public interface IEventAggregator
10 | {
11 | ///
12 | /// Gets the event with the specified type.
13 | ///
14 | /// The type of the event.
15 | /// An .
16 | IObservable GetEvent();
17 |
18 | ///
19 | /// Publishes the specified event.
20 | ///
21 | /// The type of the event.
22 | /// The event to publish.
23 | void Publish(TEvent eventValue);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Muhammad Rehan Saeed
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Source/Common/EventAggregator.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.Collections.Concurrent;
5 | using System.Reactive.Subjects;
6 |
7 | ///
8 | public class EventAggregator : Disposable, IEventAggregator
9 | {
10 | private readonly ConcurrentDictionary subjects = new ConcurrentDictionary();
11 |
12 | ///
13 | public IObservable GetEvent() =>
14 | (ISubject)this.subjects.GetOrAdd(typeof(TEvent), x => new Subject());
15 |
16 | ///
17 | public void Publish(TEvent eventValue)
18 | {
19 | if (this.subjects.TryGetValue(typeof(TEvent), out var subject))
20 | {
21 | ((ISubject)subject).OnNext(eventValue);
22 | }
23 | }
24 |
25 | ///
26 | protected override void DisposeManaged()
27 | {
28 | foreach (var item in this.subjects)
29 | {
30 | if (item.Value is IDisposable disposable)
31 | {
32 | disposable.Dispose();
33 | }
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################
2 | # Git Line Endings #
3 | ###############################
4 |
5 | # Set default behavior to automatically normalize line endings.
6 | * text=auto
7 |
8 | # Force batch scripts to always use CRLF line endings so that if a repo is accessed
9 | # in Windows via a file share from Linux, the scripts will work.
10 | *.{cmd,[cC][mM][dD]} text eol=crlf
11 | *.{bat,[bB][aA][tT]} text eol=crlf
12 |
13 | # Force bash scripts to always use LF line endings so that if a repo is accessed
14 | # in Unix via a file share from Windows, the scripts will work.
15 | *.sh text eol=lf
16 |
17 | ###############################
18 | # Git Large File System (LFS) #
19 | ###############################
20 |
21 | # Archives
22 | *.7z filter=lfs diff=lfs merge=lfs -text
23 | *.br filter=lfs diff=lfs merge=lfs -text
24 | *.gz filter=lfs diff=lfs merge=lfs -text
25 | *.tar filter=lfs diff=lfs merge=lfs -text
26 | *.zip filter=lfs diff=lfs merge=lfs -text
27 |
28 | # Documents
29 | *.pdf filter=lfs diff=lfs merge=lfs -text
30 |
31 | # Images
32 | *.gif filter=lfs diff=lfs merge=lfs -text
33 | *.ico filter=lfs diff=lfs merge=lfs -text
34 | *.jpg filter=lfs diff=lfs merge=lfs -text
35 | *.png filter=lfs diff=lfs merge=lfs -text
36 | *.psd filter=lfs diff=lfs merge=lfs -text
37 | *.webp filter=lfs diff=lfs merge=lfs -text
38 |
39 | # Fonts
40 | *.woff2 filter=lfs diff=lfs merge=lfs -text
41 |
42 | # Other
43 | *.exe filter=lfs diff=lfs merge=lfs -text
44 |
--------------------------------------------------------------------------------
/Source/Common/DelegateRule.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 |
5 | ///
6 | /// Determines whether or not an object of type satisfies a rule and
7 | /// provides an error if it does not.
8 | ///
9 | /// The type of the object the rule can be applied to.
10 | public sealed class DelegateRule : Rule
11 | {
12 | private readonly Func rule;
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// >The name of the property the rules applies to.
18 | /// The error if the rules fails.
19 | /// The rule to execute.
20 | public DelegateRule(string propertyName, object error, Func rule)
21 | : base(propertyName, error) =>
22 | this.rule = rule ?? throw new ArgumentNullException(nameof(rule));
23 |
24 | ///
25 | /// Applies the rule to the specified object.
26 | ///
27 | /// The object to apply the rule to.
28 | ///
29 | /// true if the object satisfies the rule, otherwise false .
30 | ///
31 | public override bool Apply(T obj) => this.rule(obj);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Source/Common/Commands/Command.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System.Windows.Input;
4 |
5 | ///
6 | /// base class.
7 | ///
8 | public abstract class Command : CommandBase
9 | {
10 | ///
11 | /// Defines the method that determines whether the command can execute in its current state.
12 | ///
13 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
14 | ///
15 | /// true if this command can be executed; otherwise, false.
16 | ///
17 | public override bool CanExecute(object parameter) => this.CanExecute();
18 |
19 | ///
20 | /// Defines the method to be called when the command is invoked.
21 | ///
22 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
23 | public override void Execute(object parameter) => this.Execute();
24 |
25 | ///
26 | /// Determines whether this instance can execute.
27 | ///
28 | ///
29 | /// true if this instance can execute; otherwise, false .
30 | ///
31 | public virtual bool CanExecute() => true;
32 |
33 | ///
34 | /// Executes this instance.
35 | ///
36 | public abstract void Execute();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Source/Common/Commands/AsyncCommand.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System.Threading.Tasks;
4 | using System.Windows.Input;
5 |
6 | ///
7 | /// base class.
8 | ///
9 | public abstract class AsyncCommand : CommandBase
10 | {
11 | ///
12 | /// Defines the method that determines whether the command can execute in its current state.
13 | ///
14 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
15 | ///
16 | /// true if this command can be executed; otherwise, false.
17 | ///
18 | public override bool CanExecute(object parameter) => this.CanExecute();
19 |
20 | ///
21 | /// Defines the method to be called when the command is invoked.
22 | ///
23 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
24 | public override void Execute(object parameter) => this.Execute();
25 |
26 | ///
27 | /// Determines whether this instance can execute.
28 | ///
29 | ///
30 | /// true if this instance can execute; otherwise, false .
31 | ///
32 | public virtual bool CanExecute() => true;
33 |
34 | ///
35 | /// Executes this instance.
36 | ///
37 | public abstract Task Execute();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Source/Common/Rule.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 |
5 | ///
6 | /// A named rule containing an error to be used if the rule fails.
7 | ///
8 | /// The type of the object the rule applies to.
9 | public abstract class Rule
10 | {
11 | ///
12 | /// Initializes a new instance of the class.
13 | ///
14 | /// The name of the property this instance applies to.
15 | /// The error message if the rules fails.
16 | protected Rule(string propertyName, object error)
17 | {
18 | this.PropertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName));
19 | this.Error = error ?? throw new ArgumentNullException(nameof(error));
20 | }
21 |
22 | ///
23 | /// Gets the name of the property this instance applies to.
24 | ///
25 | /// The name of the property this instance applies to.
26 | public string PropertyName { get; }
27 |
28 | ///
29 | /// Gets the error message if the rules fails.
30 | ///
31 | /// The error message if the rules fails.
32 | public object Error { get; }
33 |
34 | ///
35 | /// Applies the rule to the specified object.
36 | ///
37 | /// The object to apply the rule to.
38 | ///
39 | /// true if the object satisfies the rule, otherwise false .
40 | ///
41 | public abstract bool Apply(T obj);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Source/Common/Commands/CommandT.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System.Windows.Input;
4 |
5 | ///
6 | /// base class.
7 | ///
8 | /// The type of the command parameter.
9 | public abstract class Command : CommandBase
10 | {
11 | ///
12 | /// Defines the method that determines whether the command can execute in its current state.
13 | ///
14 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
15 | ///
16 | /// true if this command can be executed; otherwise, false.
17 | ///
18 | public override bool CanExecute(object parameter) => this.CanExecute((T)parameter);
19 |
20 | ///
21 | /// Defines the method to be called when the command is invoked.
22 | ///
23 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
24 | public override void Execute(object parameter) => this.Execute((T)parameter);
25 |
26 | ///
27 | /// Determines whether this instance can execute.
28 | ///
29 | /// The command parameter.
30 | ///
31 | /// true if this instance can execute; otherwise, false .
32 | ///
33 | public virtual bool CanExecute(T parameter) => true;
34 |
35 | ///
36 | /// Executes this instance.
37 | ///
38 | /// The command parameter.
39 | public abstract void Execute(T parameter);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Source/Common/Commands/AsyncCommandT.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System.Threading.Tasks;
4 | using System.Windows.Input;
5 |
6 | ///
7 | /// base class.
8 | ///
9 | /// The type of the command parameter.
10 | public abstract class AsyncCommand : CommandBase
11 | {
12 | ///
13 | /// Defines the method that determines whether the command can execute in its current state.
14 | ///
15 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
16 | ///
17 | /// true if this command can be executed; otherwise, false.
18 | ///
19 | public override bool CanExecute(object parameter) => this.CanExecute((T)parameter);
20 |
21 | ///
22 | /// Defines the method to be called when the command is invoked.
23 | ///
24 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
25 | public override void Execute(object parameter) => this.Execute((T)parameter);
26 |
27 | ///
28 | /// Determines whether this instance can execute.
29 | ///
30 | /// The command parameter.
31 | ///
32 | /// true if this instance can execute; otherwise, false .
33 | ///
34 | public virtual bool CanExecute(T parameter) => true;
35 |
36 | ///
37 | /// Executes this instance.
38 | ///
39 | /// The command parameter.
40 | public abstract Task Execute(T parameter);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Source/Common/RuleCollection.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Collections.ObjectModel;
6 |
7 | ///
8 | /// A collection of rules.
9 | ///
10 | /// The type of the object the rules can be applied to.
11 | public sealed class RuleCollection : Collection>
12 | {
13 | ///
14 | /// Adds a new to this instance.
15 | ///
16 | /// The name of the property the rules applies to.
17 | /// The error if the object does not satisfy the rule.
18 | /// The rule to execute.
19 | public void Add(string propertyName, object error, Func rule) =>
20 | this.Add(new DelegateRule(propertyName, error, rule));
21 |
22 | ///
23 | /// Applies the 's contained in this instance to .
24 | ///
25 | /// The object to apply the rules to.
26 | /// Name of the property we want to apply rules for. null
27 | /// to apply all rules.
28 | /// A collection of errors.
29 | public IEnumerable Apply(T obj, string propertyName)
30 | {
31 | var errors = new List();
32 |
33 | foreach (var rule in this)
34 | {
35 | if (string.IsNullOrEmpty(propertyName) || rule.PropertyName.Equals(propertyName))
36 | {
37 | if (!rule.Apply(obj))
38 | {
39 | errors.Add(rule.Error);
40 | }
41 | }
42 | }
43 |
44 | return errors;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Source/Common/Commands/CommandBase.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System;
4 | using System.Windows.Input;
5 |
6 | ///
7 | /// base class.
8 | ///
9 | public abstract class CommandBase : ICommand
10 | {
11 | ///
12 | /// Initializes a new instance of the class.
13 | ///
14 | protected CommandBase()
15 | {
16 | }
17 |
18 | ///
19 | /// Occurs when changes occur that affect whether or not the command should execute.
20 | ///
21 | public event EventHandler CanExecuteChanged;
22 |
23 | ///
24 | /// Defines the method that determines whether the command can execute in its current state.
25 | ///
26 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
27 | ///
28 | /// true if this command can be executed; otherwise, false.
29 | ///
30 | public abstract bool CanExecute(object parameter);
31 |
32 | ///
33 | /// Defines the method to be called when the command is invoked.
34 | ///
35 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
36 | public abstract void Execute(object parameter);
37 |
38 | ///
39 | /// Raises the can execute changed event.
40 | ///
41 | public void RaiseCanExecuteChanged() => this.OnCanExecuteChanged();
42 |
43 | ///
44 | /// Called when can execute is changed.
45 | ///
46 | protected virtual void OnCanExecuteChanged() => this.CanExecuteChanged?.Invoke(this, EventArgs.Empty);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Source/Common/Commands/DelegateCommand.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System;
4 |
5 | ///
6 | /// This class allows delegating the commanding logic to methods passed as parameters,
7 | /// and enables a View to bind commands to objects that are not part of the element tree.
8 | ///
9 | public sealed class DelegateCommand : Command
10 | {
11 | private readonly Action execute;
12 | private readonly Func canExecute;
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// The execute.
18 | public DelegateCommand(Action execute)
19 | : this(execute, null)
20 | {
21 | }
22 |
23 | ///
24 | /// Initializes a new instance of the class.
25 | ///
26 | /// The execute.
27 | /// The can execute.
28 | public DelegateCommand(Action execute, Func canExecute)
29 | {
30 | this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
31 | this.canExecute = canExecute;
32 | }
33 |
34 | ///
35 | /// Determines whether this instance can execute.
36 | ///
37 | ///
38 | /// true if this instance can execute; otherwise, false .
39 | ///
40 | public override bool CanExecute()
41 | {
42 | if (this.canExecute != null)
43 | {
44 | return this.canExecute();
45 | }
46 |
47 | return true;
48 | }
49 |
50 | ///
51 | /// Executes this instance.
52 | ///
53 | public override void Execute() => this.execute.Invoke();
54 | }
55 | }
--------------------------------------------------------------------------------
/Source/Common/Commands/AsyncDelegateCommand.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System;
4 | using System.Threading.Tasks;
5 |
6 | ///
7 | /// This class allows delegating the commanding logic to methods passed as parameters,
8 | /// and enables a View to bind commands to objects that are not part of the element tree.
9 | ///
10 | public sealed class AsyncDelegateCommand : AsyncCommand
11 | {
12 | private readonly Func execute;
13 | private readonly Func canExecute;
14 |
15 | ///
16 | /// Initializes a new instance of the class.
17 | ///
18 | /// The execute.
19 | public AsyncDelegateCommand(Func execute)
20 | : this(execute, null)
21 | {
22 | }
23 |
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// The execute.
28 | /// The can execute.
29 | public AsyncDelegateCommand(Func execute, Func canExecute)
30 | {
31 | this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
32 | this.canExecute = canExecute;
33 | }
34 |
35 | ///
36 | /// Determines whether this instance can execute.
37 | ///
38 | ///
39 | /// true if this instance can execute; otherwise, false .
40 | ///
41 | public override bool CanExecute()
42 | {
43 | if (this.canExecute != null)
44 | {
45 | return this.canExecute();
46 | }
47 |
48 | return true;
49 | }
50 |
51 | ///
52 | /// Executes this instance.
53 | ///
54 | public override Task Execute() => this.execute();
55 | }
56 | }
--------------------------------------------------------------------------------
/Source/Common/Commands/DelegateCommandT.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System;
4 |
5 | ///
6 | /// This class allows delegating the commanding logic to methods passed as parameters,
7 | /// and enables a View to bind commands to objects that are not part of the element tree.
8 | ///
9 | /// The type of the command parameter.
10 | public sealed class DelegateCommand : Command
11 | {
12 | private readonly Action execute;
13 | private readonly Func canExecute;
14 |
15 | ///
16 | /// Initializes a new instance of the class.
17 | ///
18 | /// The execute.
19 | public DelegateCommand(Action execute)
20 | : this(execute, null)
21 | {
22 | }
23 |
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// The execute.
28 | /// The can execute.
29 | public DelegateCommand(Action execute, Func canExecute)
30 | {
31 | this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
32 | this.canExecute = canExecute;
33 | }
34 |
35 | ///
36 | /// Determines whether this instance can execute.
37 | ///
38 | /// The command parameter.
39 | ///
40 | /// true if this instance can execute; otherwise, false .
41 | ///
42 | public override bool CanExecute(T parameter)
43 | {
44 | if (this.canExecute != null)
45 | {
46 | return this.canExecute(parameter);
47 | }
48 |
49 | return true;
50 | }
51 |
52 | ///
53 | /// Executes this instance.
54 | ///
55 | /// The command parameter.
56 | public override void Execute(T parameter) => this.execute.Invoke(parameter);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Source/EventAggregatorPattern/Program.cs:
--------------------------------------------------------------------------------
1 | namespace EventAggregatorPattern
2 | {
3 | using System;
4 | using Common;
5 | using DryIoc;
6 |
7 | public class Program
8 | {
9 | public static void Main()
10 | {
11 | var container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
12 | container.Register(Reuse.Singleton);
13 | container.Register();
14 | container.Register();
15 |
16 | var subscriberViewModel = container.Resolve();
17 | var publisherViewModel = container.Resolve();
18 | publisherViewModel.NewMessage("Hello");
19 |
20 | Console.Read();
21 | }
22 | }
23 |
24 | public class NewMessageEvent
25 | {
26 | public NewMessageEvent(string text) => this.Text = text;
27 |
28 | public string Text { get; }
29 | }
30 |
31 | public class PublisherViewModel
32 | {
33 | private readonly IEventAggregator eventAggregator;
34 |
35 | public PublisherViewModel(IEventAggregator eventAggregator) => this.eventAggregator = eventAggregator;
36 |
37 | public void NewMessage(string text) => this.eventAggregator.Publish(new NewMessageEvent(text));
38 | }
39 |
40 | public class SubscriberViewModel : Disposable
41 | {
42 | private readonly IDisposable newMessageSubscription;
43 |
44 | public SubscriberViewModel(IEventAggregator eventAggregator) =>
45 | this.newMessageSubscription = eventAggregator
46 | .GetEvent()
47 | // .ObserveOnDispatcher()
48 | .Subscribe(this.OnNewMessage);
49 |
50 | protected override void DisposeManaged() => this.newMessageSubscription.Dispose();
51 |
52 | private void OnNewMessage(NewMessageEvent newMessageEvent) => Console.WriteLine(newMessageEvent.Text);
53 | }
54 |
55 | // Publisher and subscriber are completely decoupled.
56 | // There can be multiple publishers e.g. Clear conversation history from two totally different parts of the app.
57 | // There can be multiple subscribers e.g. New user message event kicks off multiple view models.
58 | }
59 |
--------------------------------------------------------------------------------
/Source/Common/Commands/AsyncDelegateCommandT.cs:
--------------------------------------------------------------------------------
1 | namespace Common.Commands
2 | {
3 | using System;
4 | using System.Threading.Tasks;
5 |
6 | ///
7 | /// This class allows delegating the commanding logic to methods passed as parameters,
8 | /// and enables a View to bind commands to objects that are not part of the element tree.
9 | ///
10 | /// The type of the command parameter.
11 | public sealed class AsyncDelegateCommand : AsyncCommand
12 | {
13 | private readonly Func execute;
14 | private readonly Func canExecute;
15 |
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | /// The execute.
20 | public AsyncDelegateCommand(Func execute)
21 | : this(execute, null)
22 | {
23 | }
24 |
25 | ///
26 | /// Initializes a new instance of the class.
27 | ///
28 | /// The execute.
29 | /// The can execute.
30 | public AsyncDelegateCommand(Func execute, Func canExecute)
31 | {
32 | this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
33 | this.canExecute = canExecute;
34 | }
35 |
36 | ///
37 | /// Determines whether this instance can execute.
38 | ///
39 | /// The command parameter.
40 | ///
41 | /// true if this instance can execute; otherwise, false .
42 | ///
43 | public override bool CanExecute(T parameter)
44 | {
45 | if (this.canExecute != null)
46 | {
47 | return this.canExecute(parameter);
48 | }
49 |
50 | return true;
51 | }
52 |
53 | ///
54 | /// Executes this instance.
55 | ///
56 | /// The command parameter.
57 | public override Task Execute(T parameter) => this.execute(parameter);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Source/ViewModelComposition/Program.cs:
--------------------------------------------------------------------------------
1 | namespace ViewModelComposition
2 | {
3 | using System;
4 | using System.Collections.ObjectModel;
5 | using Common;
6 | using Common.Services;
7 | using DryIoc;
8 |
9 | public class Program
10 | {
11 | public static void Main()
12 | {
13 | var container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
14 | container.Register();
15 | container.Register();
16 | container.Register();
17 | container.Register();
18 | container.Register();
19 | container.Register();
20 |
21 | var conversationViewModel = container.Resolve();
22 | conversationViewModel.AddMessage("Hello World");
23 |
24 | Console.Read();
25 | }
26 | }
27 |
28 | public class ConversationViewModel : NotifyPropertyChanges
29 | {
30 | private readonly Func messageViewModelFactory;
31 | private readonly IService1 service1;
32 |
33 | public ConversationViewModel(
34 | InputViewModel inputViewModel,
35 | Func messageViewModelFactory,
36 | IService1 service1)
37 | {
38 | this.Input = inputViewModel;
39 | this.messageViewModelFactory = messageViewModelFactory;
40 | this.service1 = service1;
41 |
42 | this.Messages = new ObservableCollection();
43 | }
44 |
45 | public InputViewModel Input { get; }
46 |
47 | public ObservableCollection Messages { get; }
48 |
49 | public void AddMessage(string text)
50 | {
51 | var messageViewModel = this.messageViewModelFactory();
52 | messageViewModel.Text = text;
53 | this.Messages.Add(messageViewModel);
54 | }
55 | }
56 |
57 | public class InputViewModel : NotifyPropertyChanges
58 | {
59 | private readonly IService2 service2;
60 |
61 | private string text;
62 |
63 | public InputViewModel(IService2 service2) => this.service2 = service2;
64 |
65 | public string Text
66 | {
67 | get => this.text;
68 | set => this.SetProperty(ref this.text, value);
69 | }
70 | }
71 |
72 | public class MessageViewModel : NotifyPropertyChanges
73 | {
74 | private readonly IService3 service3;
75 |
76 | private string text;
77 |
78 | public MessageViewModel(IService3 service3) => this.service3 = service3;
79 |
80 | public string Text
81 | {
82 | get => this.text;
83 | set => this.SetProperty(ref this.text, value);
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/Source/Common/Disposable.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 |
5 | ///
6 | /// Base class for members implementing .
7 | ///
8 | public abstract class Disposable : IDisposable
9 | {
10 | ///
11 | /// Finalizes an instance of the class. Releases unmanaged
12 | /// resources and performs other clean-up operations before the
13 | /// is reclaimed by garbage collection. Will run only if the
14 | /// Dispose method does not get called.
15 | ///
16 | ~Disposable()
17 | {
18 | this.Dispose(false);
19 | }
20 |
21 | ///
22 | /// Gets a value indicating whether this is disposed.
23 | ///
24 | /// true if disposed; otherwise, false .
25 | public bool IsDisposed { get; private set; }
26 |
27 | ///
28 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
29 | ///
30 | public void Dispose()
31 | {
32 | // Dispose all managed and unmanaged resources.
33 | this.Dispose(true);
34 |
35 | // Take this object off the finalization queue and prevent finalization code for this
36 | // object from executing a second time.
37 | GC.SuppressFinalize(this);
38 | }
39 |
40 | ///
41 | /// Disposes the managed resources implementing .
42 | ///
43 | protected virtual void DisposeManaged()
44 | {
45 | }
46 |
47 | ///
48 | /// Disposes the unmanaged resources implementing .
49 | ///
50 | protected virtual void DisposeUnmanaged()
51 | {
52 | }
53 |
54 | ///
55 | /// Throws a if this instance is disposed.
56 | ///
57 | protected void ThrowIfDisposed()
58 | {
59 | if (this.IsDisposed)
60 | {
61 | throw new ObjectDisposedException(this.GetType().Name);
62 | }
63 | }
64 |
65 | ///
66 | /// Releases unmanaged and - optionally - managed resources.
67 | ///
68 | /// true to release both managed and unmanaged resources;
69 | /// false to release only unmanaged resources, called from the finalizer only.
70 | /// We suppress CA1063 which requires that this method be protected virtual because we want to hide
71 | /// the internal implementation.
72 | #pragma warning disable CA1063 // Implement IDisposable Correctly
73 | private void Dispose(bool disposing)
74 | #pragma warning restore CA1063 // Implement IDisposable Correctly
75 | {
76 | // Check to see if Dispose has already been called.
77 | if (!this.IsDisposed)
78 | {
79 | // If disposing managed and unmanaged resources.
80 | if (disposing)
81 | {
82 | this.DisposeManaged();
83 | }
84 |
85 | this.DisposeUnmanaged();
86 |
87 | this.IsDisposed = true;
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/MVVM-Design-Patterns.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29209.62
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "Source\Common\Common.csproj", "{55613994-149C-4D48-A06E-069EEB0935D0}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViewModelComposition", "Source\ViewModelComposition\ViewModelComposition.csproj", "{7AA1C956-8486-4C9C-8226-4716D7E8212D}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandPattern", "Source\CommandPattern\CommandPattern.csproj", "{F7EAF027-33A4-4FB5-803E-40AEE57F309D}"
13 | EndProject
14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4318BA69-FFF2-4DBD-AD08-01D5AD4E6E39}"
15 | ProjectSection(SolutionItems) = preProject
16 | .editorconfig = .editorconfig
17 | .gitattributes = .gitattributes
18 | .gitignore = .gitignore
19 | EndProjectSection
20 | EndProject
21 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Documentation", "Documentation", "{68AB6848-44A9-4AAD-A415-13F223BC85AA}"
22 | ProjectSection(SolutionItems) = preProject
23 | LICENSE = LICENSE
24 | README.md = README.md
25 | EndProjectSection
26 | EndProject
27 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventAggregatorPattern", "Source\EventAggregatorPattern\EventAggregatorPattern.csproj", "{3D183B21-0297-45EC-B6D7-DB4909064DA9}"
28 | EndProject
29 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rx", "Source\Rx\Rx.csproj", "{9FEEEE62-758D-430D-9F49-CF947BB33FEE}"
30 | EndProject
31 | Global
32 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
33 | Debug|Any CPU = Debug|Any CPU
34 | Release|Any CPU = Release|Any CPU
35 | EndGlobalSection
36 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
37 | {55613994-149C-4D48-A06E-069EEB0935D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {55613994-149C-4D48-A06E-069EEB0935D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {55613994-149C-4D48-A06E-069EEB0935D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
40 | {55613994-149C-4D48-A06E-069EEB0935D0}.Release|Any CPU.Build.0 = Release|Any CPU
41 | {7AA1C956-8486-4C9C-8226-4716D7E8212D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {7AA1C956-8486-4C9C-8226-4716D7E8212D}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {7AA1C956-8486-4C9C-8226-4716D7E8212D}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {7AA1C956-8486-4C9C-8226-4716D7E8212D}.Release|Any CPU.Build.0 = Release|Any CPU
45 | {F7EAF027-33A4-4FB5-803E-40AEE57F309D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
46 | {F7EAF027-33A4-4FB5-803E-40AEE57F309D}.Debug|Any CPU.Build.0 = Debug|Any CPU
47 | {F7EAF027-33A4-4FB5-803E-40AEE57F309D}.Release|Any CPU.ActiveCfg = Release|Any CPU
48 | {F7EAF027-33A4-4FB5-803E-40AEE57F309D}.Release|Any CPU.Build.0 = Release|Any CPU
49 | {3D183B21-0297-45EC-B6D7-DB4909064DA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
50 | {3D183B21-0297-45EC-B6D7-DB4909064DA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
51 | {3D183B21-0297-45EC-B6D7-DB4909064DA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
52 | {3D183B21-0297-45EC-B6D7-DB4909064DA9}.Release|Any CPU.Build.0 = Release|Any CPU
53 | {9FEEEE62-758D-430D-9F49-CF947BB33FEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
54 | {9FEEEE62-758D-430D-9F49-CF947BB33FEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
55 | {9FEEEE62-758D-430D-9F49-CF947BB33FEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
56 | {9FEEEE62-758D-430D-9F49-CF947BB33FEE}.Release|Any CPU.Build.0 = Release|Any CPU
57 | EndGlobalSection
58 | GlobalSection(SolutionProperties) = preSolution
59 | HideSolutionNode = FALSE
60 | EndGlobalSection
61 | GlobalSection(NestedProjects) = preSolution
62 | {55613994-149C-4D48-A06E-069EEB0935D0} = {E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}
63 | {7AA1C956-8486-4C9C-8226-4716D7E8212D} = {E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}
64 | {F7EAF027-33A4-4FB5-803E-40AEE57F309D} = {E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}
65 | {3D183B21-0297-45EC-B6D7-DB4909064DA9} = {E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}
66 | {9FEEEE62-758D-430D-9F49-CF947BB33FEE} = {E33EDBE9-3502-465B-A4CB-C3D4D471FCE2}
67 | EndGlobalSection
68 | GlobalSection(ExtensibilityGlobals) = postSolution
69 | SolutionGuid = {381734F3-5429-4DF7-BCB8-8F68E6E7D5FC}
70 | EndGlobalSection
71 | EndGlobal
72 |
--------------------------------------------------------------------------------
/Source/Rx/Program.cs:
--------------------------------------------------------------------------------
1 | namespace Rx
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Reactive.Linq;
6 | using System.Reactive.Subjects;
7 | using Common;
8 | using DryIoc;
9 |
10 | public class Program
11 | {
12 | public static void Main()
13 | {
14 | var container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
15 | container.Register(Reuse.Singleton);
16 | container.Register(Reuse.Singleton);
17 | container.Register(Reuse.Singleton);
18 | container.Register(Reuse.Singleton);
19 |
20 | CSharpEventUsage.Execute(container);
21 | ReactiveExtensionsUsage.Execute(container);
22 |
23 | Console.Read();
24 | }
25 | }
26 |
27 | #region C# Events
28 |
29 | public static class CSharpEventUsage
30 | {
31 | public static void Execute(Container container)
32 | {
33 | var subscriberViewModel = container.Resolve();
34 | var publisherViewModel = container.Resolve();
35 | publisherViewModel.RaiseNewMessage("Hello");
36 | }
37 | }
38 |
39 | public class NewMessageEventArgs : EventArgs
40 | {
41 | public NewMessageEventArgs(string text) => this.Text = text;
42 |
43 | public string Text { get; }
44 | }
45 |
46 | public class CSharpEventPublisherViewModel
47 | {
48 | public event EventHandler NewMessage;
49 |
50 | public void RaiseNewMessage(string text) => this.NewMessage?.Invoke(this, new NewMessageEventArgs(text));
51 | }
52 |
53 | public class CSharpEventSubscriberViewModel : Disposable
54 | {
55 | private readonly CSharpEventPublisherViewModel publisherViewModel;
56 |
57 | public CSharpEventSubscriberViewModel(CSharpEventPublisherViewModel publisherViewModel)
58 | {
59 | this.publisherViewModel = publisherViewModel;
60 | publisherViewModel.NewMessage += this.OnNewMessage;
61 | }
62 |
63 | protected override void DisposeManaged() => this.publisherViewModel.NewMessage -= this.OnNewMessage;
64 |
65 | private void OnNewMessage(object sender, NewMessageEventArgs e) => Console.WriteLine(e.Text);
66 | }
67 |
68 | #endregion
69 |
70 | #region IEnumerator is Dual of IObserver
71 |
72 | public class Dual
73 | {
74 | public Dual()
75 | {
76 | #pragma warning disable CS0219 // Shhh...sleep C# compiler
77 | IEnumerable enumerable = null;
78 | IEnumerator enumerator = null;
79 |
80 | IObservable observable = null;
81 | IObserver observer = null;
82 | #pragma warning restore CS0219
83 | }
84 | }
85 |
86 | #endregion
87 |
88 | #region Reactive Extensions
89 |
90 | public static class ReactiveExtensionsUsage
91 | {
92 | public static void Execute(Container container)
93 | {
94 | var subscriberViewModel = container.Resolve();
95 | var publisherViewModel = container.Resolve();
96 |
97 | publisherViewModel.NewMessage("Hi");
98 | publisherViewModel.NewMessage("Hello");
99 | }
100 | }
101 |
102 | public class RxPublisherViewModel
103 | {
104 | private readonly Subject newMessageSubject = new Subject();
105 |
106 | public IObservable WhenNewMessage => this.newMessageSubject.AsObservable();
107 |
108 | public void NewMessage(string text) => this.newMessageSubject.OnNext(text);
109 | }
110 |
111 | public class RxSubscriberViewModel : Disposable
112 | {
113 | private readonly IDisposable newMessageSubscription;
114 |
115 | public RxSubscriberViewModel(RxPublisherViewModel publisherViewModel) =>
116 | this.newMessageSubscription = publisherViewModel.WhenNewMessage
117 | .Where(x => x.Contains("Hello"))
118 | .Select(x => $"{x} ({x.Length})")
119 | .Throttle(TimeSpan.FromSeconds(1))
120 | // .ObserveOnDispatcher();
121 | .Subscribe(this.OnNewMessage);
122 |
123 | protected override void DisposeManaged() => this.newMessageSubscription.Dispose();
124 |
125 | private void OnNewMessage(string text) => Console.WriteLine(text);
126 | }
127 |
128 | #endregion
129 |
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/Source/Common/RevertibleChangeTracking.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.ComponentModel;
5 | using System.Runtime.CompilerServices;
6 |
7 | ///
8 | /// Provides support for rolling back changes made to this objects properties. This object
9 | /// automatically saves its state before it is changed. Also provides errors for the object if
10 | /// it is in an invalid state.
11 | ///
12 | /// The type of this instance.
13 | public abstract class RevertibleChangeTracking : EditableObject, IRevertibleChangeTracking, IEquatable
14 | where T : RevertibleChangeTracking, new()
15 | {
16 | private bool isChanged;
17 | private bool isChangeTrackingEnabled;
18 | private bool isNew = true;
19 |
20 | ///
21 | /// Gets or sets a value indicating whether the change tracking of the object's status is enabled.
22 | ///
23 | ///
24 | /// true if change tracking ir enabled; otherwise, false .
25 | ///
26 | public bool IsChangeTrackingEnabled
27 | {
28 | get => this.isChangeTrackingEnabled;
29 | set
30 | {
31 | base.OnPropertyChanging("IsChangeTrackingEnabled");
32 | this.isChangeTrackingEnabled = value;
33 | base.OnPropertyChanged("IsChangeTrackingEnabled");
34 | }
35 | }
36 |
37 | ///
38 | /// Gets a value indicating whether the object's status changed.
39 | ///
40 | ///
41 | /// true if the object’s content has changed since the last call to ; otherwise, false .
42 | ///
43 | public bool IsChanged
44 | {
45 | get => this.isChanged;
46 |
47 | private set
48 | {
49 | base.OnPropertyChanging("IsChanged");
50 | this.isChanged = value;
51 | base.OnPropertyChanged("IsChanged");
52 | }
53 | }
54 |
55 | ///
56 | /// Gets a value indicating whether this instance is new.
57 | ///
58 | /// true if this instance is new; otherwise, false .
59 | public bool IsNew
60 | {
61 | get => this.isNew;
62 | private set => this.SetProperty(ref this.isNew, value);
63 | }
64 |
65 | ///
66 | /// Resets the object’s state to unchanged by accepting the modifications.
67 | ///
68 | public virtual void AcceptChanges()
69 | {
70 | if (this.IsNew)
71 | {
72 | this.IsNew = false;
73 | this.IsChangeTrackingEnabled = true;
74 | }
75 | else if (this.IsChanged)
76 | {
77 | this.EndEdit();
78 |
79 | this.IsChanged = false;
80 | }
81 | }
82 |
83 | ///
84 | /// Discards changes since the last call.
85 | ///
86 | public override void CancelEdit()
87 | {
88 | base.CancelEdit();
89 |
90 | this.IsChanged = false;
91 | }
92 |
93 | ///
94 | /// Indicates whether the current object is equal to another object of the same type.
95 | ///
96 | /// An object to compare with this object.
97 | ///
98 | /// true if the current object is equal to the parameter; otherwise, false.
99 | ///
100 | public virtual bool Equals(T other) => object.Equals(this, other);
101 |
102 | ///
103 | /// Resets the object’s state to unchanged by rejecting the modifications.
104 | ///
105 | public virtual void RejectChanges() => this.CancelEdit();
106 |
107 | ///
108 | /// Raises the PropertyChanged event.
109 | ///
110 | /// Name of the property.
111 | protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
112 | {
113 | base.OnPropertyChanged(propertyName);
114 |
115 | if (this.IsChangeTrackingEnabled)
116 | {
117 | if (this.Equals(this.Original))
118 | {
119 | this.IsChanged = false;
120 | }
121 | else
122 | {
123 | this.IsChanged = true;
124 | }
125 | }
126 | }
127 |
128 | ///
129 | /// Raises the PropertyChanging event.
130 | ///
131 | /// Name of the property.
132 | protected override void OnPropertyChanging([CallerMemberName] string propertyName = null)
133 | {
134 | if (this.IsChangeTrackingEnabled)
135 | {
136 | this.BeginEdit();
137 | }
138 |
139 | base.OnPropertyChanging(propertyName);
140 | }
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/Source/Common/EditableObject.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.ComponentModel;
5 | using System.Reactive;
6 | using System.Reactive.Linq;
7 | using System.Reactive.Subjects;
8 |
9 | ///
10 | /// Provides functionality to commit or rollback changes to an object that is used as a data
11 | /// source and provide errors for the object if it is in an invalid state.
12 | ///
13 | /// The type of this instance.
14 | public abstract class EditableObject : NotifyDataErrorInfo, ICloneable, IEditableObject
15 | where T : EditableObject, new()
16 | {
17 | private readonly Subject beginEditingSubject = new Subject();
18 | private readonly Subject cancelEditingSubject = new Subject();
19 | private readonly Subject endEditingSubject = new Subject();
20 |
21 | ///
22 | /// Gets the when begin editing observable event. Occurs when beginning editing.
23 | ///
24 | ///
25 | /// The when begin editing observable event.
26 | ///
27 | public IObservable WhenBeginEditing => this.beginEditingSubject.AsObservable();
28 |
29 | ///
30 | /// Gets the when cancel editing observable event. Occurs when cancelling editing.
31 | ///
32 | ///
33 | /// The when begin cancel observable event.
34 | ///
35 | public IObservable WhenCancelEditing => this.cancelEditingSubject.AsObservable();
36 |
37 | ///
38 | /// Gets the when end editing observable event. Occurs when ending editing.
39 | ///
40 | ///
41 | /// The when begin end observable event.
42 | ///
43 | public IObservable WhenEndEditing => this.endEditingSubject.AsObservable();
44 |
45 | ///
46 | /// Gets the original version of this object before was called.
47 | ///
48 | /// The original version of this object before was called.
49 | public T Original { get; private set; }
50 |
51 | ///
52 | /// Clones the clonable object of type .
53 | ///
54 | ///
55 | /// The cloned object of type .
56 | ///
57 | public T Clone()
58 | {
59 | var clone = new T();
60 | clone.Load((T)this);
61 | return clone;
62 | }
63 |
64 | ///
65 | /// Creates a new object that is a copy of the current instance.
66 | ///
67 | ///
68 | /// A new object that is a copy of this instance.
69 | ///
70 | object ICloneable.Clone() => this.Clone();
71 |
72 | ///
73 | /// Begins an edit on an object.
74 | ///
75 | public virtual void BeginEdit()
76 | {
77 | if (this.Original == null)
78 | {
79 | this.Original = this.Clone();
80 |
81 | this.OnBeginEditing();
82 | }
83 | }
84 |
85 | ///
86 | /// Discards changes since the last call.
87 | ///
88 | public virtual void CancelEdit()
89 | {
90 | if (this.Original != null)
91 | {
92 | this.Load(this.Original);
93 |
94 | this.Original = null;
95 |
96 | this.OnCancelEditing();
97 | }
98 | }
99 |
100 | ///
101 | /// Pushes changes since the last or call into the underlying object.
102 | ///
103 | public virtual void EndEdit()
104 | {
105 | this.Original = null;
106 |
107 | this.OnEndEditing();
108 | }
109 |
110 | ///
111 | /// Loads the specified item.
112 | ///
113 | /// The item to load this instance from.
114 | public abstract void Load(T item);
115 |
116 | ///
117 | /// Disposes the managed resources implementing .
118 | ///
119 | protected override void DisposeManaged()
120 | {
121 | this.beginEditingSubject.Dispose();
122 | this.cancelEditingSubject.Dispose();
123 | this.endEditingSubject.Dispose();
124 | }
125 |
126 | ///
127 | /// Called when editing has began.
128 | ///
129 | protected virtual void OnBeginEditing() => this.beginEditingSubject.OnNext(Unit.Default);
130 |
131 | ///
132 | /// Called when editing is cancelled.
133 | ///
134 | protected virtual void OnCancelEditing() => this.cancelEditingSubject.OnNext(Unit.Default);
135 |
136 | ///
137 | /// Called when editing has ended.
138 | ///
139 | protected virtual void OnEndEditing() => this.endEditingSubject.OnNext(Unit.Default);
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/Source/CommandPattern/Program.cs:
--------------------------------------------------------------------------------
1 | namespace CommandPattern
2 | {
3 | using System;
4 | using System.Threading.Tasks;
5 | using System.Windows.Input;
6 | using Common;
7 | using Common.Commands;
8 | using Common.Services;
9 | using DryIoc;
10 |
11 | ///
12 | /// See .
13 | ///
14 | ///
15 | /// Command="{Binding Foo}"
16 | /// CommandParameter="{Binding Bar}"
17 | ///
18 | public class Program
19 | {
20 | public static async Task Main()
21 | {
22 | var container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
23 | container.Register();
24 | container.Register();
25 | container.Register();
26 |
27 | container.Register();
28 | await FirstUsage.Execute(container);
29 |
30 | container.Register();
31 | container.Register();
32 | SecondUsage.Execute(container);
33 |
34 | container.Register();
35 | container.Register();
36 | ThirdUsage.Execute(container);
37 |
38 | Console.Read();
39 | }
40 | }
41 |
42 | #region First
43 |
44 | public static class FirstUsage
45 | {
46 | public static async Task Execute(Container container)
47 | {
48 | var firstViewModel = container.Resolve();
49 |
50 | if (firstViewModel.NoParameterCommand.CanExecute())
51 | {
52 | firstViewModel.NoParameterCommand.Execute();
53 | }
54 |
55 | if (firstViewModel.HasParameterCommand.CanExecute("Hi"))
56 | {
57 | firstViewModel.HasParameterCommand.Execute("Hi");
58 | }
59 |
60 | if (firstViewModel.NoParameterAsyncCommand.CanExecute())
61 | {
62 | await firstViewModel.NoParameterAsyncCommand.Execute();
63 | }
64 |
65 | if (firstViewModel.HasParameterAsyncCommand.CanExecute("Hi"))
66 | {
67 | await firstViewModel.HasParameterAsyncCommand.Execute("Hi");
68 | }
69 | }
70 | }
71 |
72 | public class FirstViewModel : NotifyPropertyChanges
73 | {
74 | public FirstViewModel()
75 | {
76 | this.NoParameterCommand = new DelegateCommand(this.NoParameter);
77 | this.HasParameterCommand = new DelegateCommand(this.HasParameter);
78 | this.NoParameterAsyncCommand = new AsyncDelegateCommand(this.NoParameterAsync);
79 | this.HasParameterAsyncCommand = new AsyncDelegateCommand(this.HasParameterAsync);
80 | }
81 |
82 | public DelegateCommand NoParameterCommand { get; }
83 |
84 | public DelegateCommand HasParameterCommand { get; }
85 |
86 | public AsyncDelegateCommand NoParameterAsyncCommand { get; }
87 |
88 | public AsyncDelegateCommand HasParameterAsyncCommand { get; }
89 |
90 | private void NoParameter() => Console.WriteLine("Hello World");
91 |
92 | private void HasParameter(string greeting) => Console.WriteLine($"{greeting}");
93 |
94 | private Task NoParameterAsync()
95 | {
96 | Console.WriteLine("Async Hello World");
97 | return Task.CompletedTask;
98 | }
99 |
100 | private Task HasParameterAsync(string greeting)
101 | {
102 | Console.WriteLine($"Async {greeting}");
103 | return Task.CompletedTask;
104 | }
105 | }
106 |
107 | #endregion
108 |
109 | #region Second
110 |
111 | public static class SecondUsage
112 | {
113 | public static void Execute(Container container)
114 | {
115 | var secondViewModel = container.Resolve();
116 | if (secondViewModel.GreetingCommand.CanExecute("Foo"))
117 | {
118 | // This should never execute
119 | }
120 |
121 | if (secondViewModel.GreetingCommand.CanExecute("Hello"))
122 | {
123 | secondViewModel.GreetingCommand.Execute("Hello");
124 | }
125 | }
126 | }
127 |
128 | public class SecondViewModel : NotifyPropertyChanges
129 | {
130 | private readonly IService2 service2;
131 |
132 | public SecondViewModel(
133 | GreetingCommand greetingCommand,
134 | IService2 service2)
135 | {
136 | this.GreetingCommand = greetingCommand;
137 | this.service2 = service2;
138 | }
139 |
140 | // returning false from CanExecute can cause a control's IsEnabled property to be set to false.
141 | // You can use this behaviour to do other things like hide the control:
142 | //
143 | //
144 | //
151 | //
152 | //
153 | public GreetingCommand GreetingCommand { get; }
154 | }
155 |
156 | public class GreetingCommand : Command
157 | {
158 | private readonly IService1 service1;
159 |
160 | public GreetingCommand(IService1 service1) => this.service1 = service1;
161 |
162 | public override bool CanExecute(string parameter) => parameter.Contains("H");
163 |
164 | public override void Execute(string greeting) => Console.WriteLine(greeting);
165 | }
166 |
167 | #endregion
168 |
169 | #region Third
170 |
171 | public static class ThirdUsage
172 | {
173 | public static void Execute(Container container)
174 | {
175 | var thirdViewModel = container.Resolve();
176 | if (thirdViewModel.DoStuffOnTheViewModelCommand.CanExecute(thirdViewModel))
177 | {
178 | thirdViewModel.DoStuffOnTheViewModelCommand.Execute(thirdViewModel);
179 | }
180 | }
181 | }
182 |
183 | public class ThirdViewModel : NotifyPropertyChanges
184 | {
185 | private readonly IService3 service3;
186 | private string text;
187 |
188 | public ThirdViewModel(
189 | DoStuffOnTheViewModelCommand doStuffOnTheViewModelCommand,
190 | IService3 service3)
191 | {
192 | this.DoStuffOnTheViewModelCommand = doStuffOnTheViewModelCommand;
193 | this.service3 = service3;
194 | }
195 |
196 | //
198 | public DoStuffOnTheViewModelCommand DoStuffOnTheViewModelCommand { get; }
199 |
200 | public string Text
201 | {
202 | get => this.text;
203 | set => this.SetProperty(ref this.text, value);
204 | }
205 | }
206 |
207 | public class DoStuffOnTheViewModelCommand : Command
208 | {
209 | private readonly IService1 service1;
210 |
211 | public DoStuffOnTheViewModelCommand(IService1 service1) => this.service1 = service1;
212 |
213 | public override void Execute(ThirdViewModel otherViewModel) => otherViewModel.Text = "Hello World";
214 | }
215 |
216 | #endregion
217 | }
218 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 |
33 | # Visual Studio 2015/2017 cache/options directory
34 | .vs/
35 | # Uncomment if you have tasks that create the project's static files in wwwroot
36 | #wwwroot/
37 |
38 | # Visual Studio 2017 auto generated files
39 | Generated\ Files/
40 |
41 | # MSTest test Results
42 | [Tt]est[Rr]esult*/
43 | [Bb]uild[Ll]og.*
44 |
45 | # NUnit
46 | *.VisualState.xml
47 | TestResult.xml
48 | nunit-*.xml
49 |
50 | # Build Results of an ATL Project
51 | [Dd]ebugPS/
52 | [Rr]eleasePS/
53 | dlldata.c
54 |
55 | # Benchmark Results
56 | BenchmarkDotNet.Artifacts/
57 |
58 | # .NET Core
59 | project.lock.json
60 | project.fragment.lock.json
61 | artifacts/
62 |
63 | # StyleCop
64 | StyleCopReport.xml
65 |
66 | # Files built by Visual Studio
67 | *_i.c
68 | *_p.c
69 | *_h.h
70 | *.ilk
71 | *.meta
72 | *.obj
73 | *.iobj
74 | *.pch
75 | *.pdb
76 | *.ipdb
77 | *.pgc
78 | *.pgd
79 | *.rsp
80 | *.sbr
81 | *.tlb
82 | *.tli
83 | *.tlh
84 | *.tmp
85 | *.tmp_proj
86 | *_wpftmp.csproj
87 | *.log
88 | *.vspscc
89 | *.vssscc
90 | .builds
91 | *.pidb
92 | *.svclog
93 | *.scc
94 |
95 | # Chutzpah Test files
96 | _Chutzpah*
97 |
98 | # Visual C++ cache files
99 | ipch/
100 | *.aps
101 | *.ncb
102 | *.opendb
103 | *.opensdf
104 | *.sdf
105 | *.cachefile
106 | *.VC.db
107 | *.VC.VC.opendb
108 |
109 | # Visual Studio profiler
110 | *.psess
111 | *.vsp
112 | *.vspx
113 | *.sap
114 |
115 | # Visual Studio Trace Files
116 | *.e2e
117 |
118 | # TFS 2012 Local Workspace
119 | $tf/
120 |
121 | # Guidance Automation Toolkit
122 | *.gpState
123 |
124 | # ReSharper is a .NET coding add-in
125 | _ReSharper*/
126 | *.[Rr]e[Ss]harper
127 | *.DotSettings.user
128 |
129 | # JustCode is a .NET coding add-in
130 | .JustCode
131 |
132 | # TeamCity is a build add-in
133 | _TeamCity*
134 |
135 | # DotCover is a Code Coverage Tool
136 | *.dotCover
137 |
138 | # AxoCover is a Code Coverage Tool
139 | .axoCover/*
140 | !.axoCover/settings.json
141 |
142 | # Visual Studio code coverage results
143 | *.coverage
144 | *.coveragexml
145 |
146 | # NCrunch
147 | _NCrunch_*
148 | .*crunch*.local.xml
149 | nCrunchTemp_*
150 |
151 | # MightyMoose
152 | *.mm.*
153 | AutoTest.Net/
154 |
155 | # Web workbench (sass)
156 | .sass-cache/
157 |
158 | # Installshield output folder
159 | [Ee]xpress/
160 |
161 | # DocProject is a documentation generator add-in
162 | DocProject/buildhelp/
163 | DocProject/Help/*.HxT
164 | DocProject/Help/*.HxC
165 | DocProject/Help/*.hhc
166 | DocProject/Help/*.hhk
167 | DocProject/Help/*.hhp
168 | DocProject/Help/Html2
169 | DocProject/Help/html
170 |
171 | # Click-Once directory
172 | publish/
173 |
174 | # Publish Web Output
175 | *.[Pp]ublish.xml
176 | *.azurePubxml
177 | # Note: Comment the next line if you want to checkin your web deploy settings,
178 | # but database connection strings (with potential passwords) will be unencrypted
179 | *.pubxml
180 | *.publishproj
181 |
182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
183 | # checkin your Azure Web App publish settings, but sensitive information contained
184 | # in these scripts will be unencrypted
185 | PublishScripts/
186 |
187 | # NuGet Packages
188 | *.nupkg
189 | # NuGet Symbol Packages
190 | *.snupkg
191 | # The packages folder can be ignored because of Package Restore
192 | **/[Pp]ackages/*
193 | # except build/, which is used as an MSBuild target.
194 | !**/[Pp]ackages/build/
195 | # Uncomment if necessary however generally it will be regenerated when needed
196 | #!**/[Pp]ackages/repositories.config
197 | # NuGet v3's project.json files produces more ignorable files
198 | *.nuget.props
199 | *.nuget.targets
200 |
201 | # Microsoft Azure Build Output
202 | csx/
203 | *.build.csdef
204 |
205 | # Microsoft Azure Emulator
206 | ecf/
207 | rcf/
208 |
209 | # Windows Store app package directories and files
210 | AppPackages/
211 | BundleArtifacts/
212 | Package.StoreAssociation.xml
213 | _pkginfo.txt
214 | *.appx
215 | *.appxbundle
216 | *.appxupload
217 |
218 | # Visual Studio cache files
219 | # files ending in .cache can be ignored
220 | *.[Cc]ache
221 | # but keep track of directories ending in .cache
222 | !?*.[Cc]ache/
223 |
224 | # Others
225 | ClientBin/
226 | ~$*
227 | *~
228 | *.dbmdl
229 | *.dbproj.schemaview
230 | *.jfm
231 | *.pfx
232 | *.publishsettings
233 | orleans.codegen.cs
234 |
235 | # Including strong name files can present a security risk
236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
237 | #*.snk
238 |
239 | # Since there are multiple workflows, uncomment next line to ignore bower_components
240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
241 | #bower_components/
242 |
243 | # RIA/Silverlight projects
244 | Generated_Code/
245 |
246 | # Backup & report files from converting an old project file
247 | # to a newer Visual Studio version. Backup files are not needed,
248 | # because we have git ;-)
249 | _UpgradeReport_Files/
250 | Backup*/
251 | UpgradeLog*.XML
252 | UpgradeLog*.htm
253 | ServiceFabricBackup/
254 | *.rptproj.bak
255 |
256 | # SQL Server files
257 | *.mdf
258 | *.ldf
259 | *.ndf
260 |
261 | # Business Intelligence projects
262 | *.rdl.data
263 | *.bim.layout
264 | *.bim_*.settings
265 | *.rptproj.rsuser
266 | *- [Bb]ackup.rdl
267 | *- [Bb]ackup ([0-9]).rdl
268 | *- [Bb]ackup ([0-9][0-9]).rdl
269 |
270 | # Microsoft Fakes
271 | FakesAssemblies/
272 |
273 | # GhostDoc plugin setting file
274 | *.GhostDoc.xml
275 |
276 | # Node.js Tools for Visual Studio
277 | .ntvs_analysis.dat
278 | node_modules/
279 |
280 | # Visual Studio 6 build log
281 | *.plg
282 |
283 | # Visual Studio 6 workspace options file
284 | *.opt
285 |
286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
287 | *.vbw
288 |
289 | # Visual Studio LightSwitch build output
290 | **/*.HTMLClient/GeneratedArtifacts
291 | **/*.DesktopClient/GeneratedArtifacts
292 | **/*.DesktopClient/ModelManifest.xml
293 | **/*.Server/GeneratedArtifacts
294 | **/*.Server/ModelManifest.xml
295 | _Pvt_Extensions
296 |
297 | # Paket dependency manager
298 | .paket/paket.exe
299 | paket-files/
300 |
301 | # FAKE - F# Make
302 | .fake/
303 |
304 | # CodeRush personal settings
305 | .cr/personal
306 |
307 | # Python Tools for Visual Studio (PTVS)
308 | __pycache__/
309 | *.pyc
310 |
311 | # Cake - Uncomment if you are using it
312 | # tools/**
313 | # !tools/packages.config
314 |
315 | # Tabs Studio
316 | *.tss
317 |
318 | # Telerik's JustMock configuration file
319 | *.jmconfig
320 |
321 | # BizTalk build output
322 | *.btp.cs
323 | *.btm.cs
324 | *.odx.cs
325 | *.xsd.cs
326 |
327 | # OpenCover UI analysis results
328 | OpenCover/
329 |
330 | # Azure Stream Analytics local run output
331 | ASALocalRun/
332 |
333 | # MSBuild Binary and Structured Log
334 | *.binlog
335 |
336 | # NVidia Nsight GPU debugger configuration file
337 | *.nvuser
338 |
339 | # MFractors (Xamarin productivity tool) working folder
340 | .mfractor/
341 |
342 | # Local History for Visual Studio
343 | .localhistory/
344 |
345 | # BeatPulse healthcheck temp database
346 | healthchecksdb
347 |
348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
349 | MigrationBackup/
350 |
351 | # Ionide (cross platform F# VS Code tools) working folder
352 | .ionide/
353 |
--------------------------------------------------------------------------------
/Source/Common/NotifyDataErrorInfo.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.Collections;
5 | using System.Collections.Generic;
6 | using System.ComponentModel;
7 | using System.Diagnostics;
8 | using System.Linq;
9 | using System.Reactive.Linq;
10 | using System.Runtime.CompilerServices;
11 |
12 | ///
13 | /// Provides functionality to provide errors for the object if it is in an invalid state.
14 | ///
15 | /// The type of this instance.
16 | public abstract class NotifyDataErrorInfo : NotifyPropertyChanges, INotifyDataErrorInfo, IDataErrorInfo
17 | where T : NotifyDataErrorInfo
18 | {
19 | private const string HasErrorsPropertyName = "HasErrors";
20 | private Dictionary> errors;
21 |
22 | ///
23 | /// Occurs when the validation errors have changed for a property or for the entire object.
24 | ///
25 | event EventHandler INotifyDataErrorInfo.ErrorsChanged
26 | {
27 | add { this.errorsChanged += value; }
28 | remove { this.errorsChanged -= value; }
29 | }
30 |
31 | #pragma warning disable IDE1006 // Naming Styles
32 | private event EventHandler errorsChanged;
33 | #pragma warning restore IDE1006 // Naming Styles
34 |
35 | ///
36 | /// Gets the when errors changed observable event. Occurs when the validation errors have changed for a property or for the entire object.
37 | ///
38 | ///
39 | /// The when errors changed observable event.
40 | ///
41 | public IObservable WhenErrorsChanged
42 | {
43 | get
44 | {
45 | this.ThrowIfDisposed();
46 |
47 | return Observable
48 | .FromEventPattern(
49 | h => this.errorsChanged += h,
50 | h => this.errorsChanged -= h)
51 | .Select(x => x.EventArgs.PropertyName);
52 | }
53 | }
54 |
55 | ///
56 | /// Gets the errors for the property with the specified name.
57 | ///
58 | /// The name of the property to get errors for.
59 | /// A collection of all errors from the . null
60 | /// if there are no errors.
61 | string IDataErrorInfo.this[string columnName] => string.Join(". ", this.GetErrors(columnName));
62 |
63 | ///
64 | /// Gets a value indicating whether the object has validation errors.
65 | ///
66 | /// true if this instance has errors, otherwise false .
67 | public virtual bool HasErrors
68 | {
69 | get
70 | {
71 | this.InitializeErrors();
72 | return this.errors.Count > 0;
73 | }
74 | }
75 |
76 | ///
77 | /// Gets an error message indicating what is wrong with this object.
78 | ///
79 | ///
80 | ///
81 | /// An error message indicating what is wrong with this object. The default is an empty string ("").
82 | ///
83 | string IDataErrorInfo.Error => ((IDataErrorInfo)this)[null];
84 |
85 | ///
86 | /// Gets the rules which provide the errors.
87 | ///
88 | /// The rules this instance must satisfy.
89 | protected static RuleCollection Rules { get; } = new RuleCollection();
90 |
91 | ///
92 | /// Gets the validation errors for the entire object.
93 | ///
94 | /// A collection of errors.
95 | public IEnumerable GetErrors() => this.GetErrors(null);
96 |
97 | ///
98 | /// Gets the validation errors for a specified property or for the entire object.
99 | ///
100 | /// Name of the property to retrieve errors for. null to
101 | /// retrieve all errors for this instance.
102 | /// A collection of errors.
103 | public IEnumerable GetErrors(string propertyName)
104 | {
105 | Debug.Assert(
106 | string.IsNullOrEmpty(propertyName) ||
107 | (this.GetType().GetProperty(propertyName) != null),
108 | "Check that the property name exists for this instance.");
109 |
110 | this.InitializeErrors();
111 |
112 | IEnumerable result;
113 | if (string.IsNullOrEmpty(propertyName))
114 | {
115 | var allErrors = new List();
116 | foreach (var keyValuePair in this.errors)
117 | {
118 | allErrors.AddRange(keyValuePair.Value);
119 | }
120 |
121 | result = allErrors;
122 | }
123 | else
124 | {
125 | if (this.errors.ContainsKey(propertyName))
126 | {
127 | result = this.errors[propertyName];
128 | }
129 | else
130 | {
131 | result = Enumerable.Empty();
132 | }
133 | }
134 |
135 | return result;
136 | }
137 |
138 | ///
139 | /// Raises the PropertyChanged event.
140 | ///
141 | /// Name of the property.
142 | protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
143 | {
144 | base.OnPropertyChanged(propertyName);
145 |
146 | if (string.IsNullOrEmpty(propertyName))
147 | {
148 | this.ApplyRules();
149 | }
150 | else
151 | {
152 | this.ApplyRules(propertyName);
153 | }
154 |
155 | base.OnPropertyChanged(HasErrorsPropertyName);
156 | }
157 |
158 | ///
159 | /// Called when the errors have changed.
160 | ///
161 | /// Name of the property.
162 | protected virtual void OnErrorsChanged([CallerMemberName] string propertyName = null)
163 | {
164 | Debug.Assert(
165 | string.IsNullOrEmpty(propertyName) ||
166 | (this.GetType().GetProperty(propertyName) != null),
167 | "Check that the property name exists for this instance.");
168 |
169 | this.errorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
170 | }
171 |
172 | ///
173 | /// Applies all rules to this instance.
174 | ///
175 | private void ApplyRules()
176 | {
177 | this.InitializeErrors();
178 |
179 | foreach (var propertyName in Rules.Select(x => x.PropertyName))
180 | {
181 | this.ApplyRules(propertyName);
182 | }
183 | }
184 |
185 | ///
186 | /// Applies the rules to this instance for the specified property.
187 | ///
188 | /// Name of the property.
189 | private void ApplyRules(string propertyName)
190 | {
191 | this.InitializeErrors();
192 |
193 | var propertyErrors = Rules.Apply((T)this, propertyName).ToList();
194 | if (propertyErrors.Count > 0)
195 | {
196 | if (this.errors.ContainsKey(propertyName))
197 | {
198 | this.errors[propertyName].Clear();
199 | }
200 | else
201 | {
202 | this.errors[propertyName] = new List();
203 | }
204 |
205 | this.errors[propertyName].AddRange(propertyErrors);
206 | this.OnErrorsChanged(propertyName);
207 | }
208 | else if (this.errors.ContainsKey(propertyName))
209 | {
210 | this.errors.Remove(propertyName);
211 | this.OnErrorsChanged(propertyName);
212 | }
213 | }
214 |
215 | ///
216 | /// Initializes the errors and applies the rules if not initialized.
217 | ///
218 | private void InitializeErrors()
219 | {
220 | if (this.errors == null)
221 | {
222 | this.errors = new Dictionary>();
223 |
224 | this.ApplyRules();
225 | }
226 | }
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/Source/Common/NotifyPropertyChanges.cs:
--------------------------------------------------------------------------------
1 | namespace Common
2 | {
3 | using System;
4 | using System.ComponentModel;
5 | using System.Diagnostics;
6 | using System.Reactive.Linq;
7 | using System.Reflection;
8 | using System.Runtime.CompilerServices;
9 |
10 | ///
11 | /// Notifies subscribers that a property in this instance is changing or has changed.
12 | ///
13 | public abstract class NotifyPropertyChanges : Disposable, INotifyPropertyChanged, INotifyPropertyChanging
14 | {
15 | ///
16 | /// Occurs after a property value changes.
17 | ///
18 | event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
19 | {
20 | add { this.propertyChanged += value; }
21 | remove { this.propertyChanged -= value; }
22 | }
23 |
24 | ///
25 | /// Occurs before a property value is changed.
26 | ///
27 | event PropertyChangingEventHandler INotifyPropertyChanging.PropertyChanging
28 | {
29 | add { this.propertyChanging += value; }
30 | remove { this.propertyChanging -= value; }
31 | }
32 |
33 | #pragma warning disable IDE1006 // Naming Styles
34 | private event PropertyChangedEventHandler propertyChanged;
35 | private event PropertyChangingEventHandler propertyChanging;
36 | #pragma warning restore IDE1006 // Naming Styles
37 |
38 | ///
39 | /// Gets the when property changed observable event. Occurs when a property value changes.
40 | ///
41 | ///
42 | /// The when property changed observable event.
43 | ///
44 | public IObservable WhenPropertyChanged
45 | {
46 | get
47 | {
48 | this.ThrowIfDisposed();
49 |
50 | return Observable
51 | .FromEventPattern(
52 | h => this.propertyChanged += h,
53 | h => this.propertyChanged -= h)
54 | .Select(x => x.EventArgs.PropertyName);
55 | }
56 | }
57 |
58 | ///
59 | /// Gets the when property changing observable event. Occurs when a property value is changing.
60 | ///
61 | ///
62 | /// The when property changing observable event.
63 | ///
64 | public IObservable WhenPropertyChanging
65 | {
66 | get
67 | {
68 | this.ThrowIfDisposed();
69 |
70 | return Observable
71 | .FromEventPattern(
72 | h => this.propertyChanging += h,
73 | h => this.propertyChanging -= h)
74 | .Select(x => x.EventArgs.PropertyName);
75 | }
76 | }
77 |
78 | ///
79 | /// Raises the PropertyChanged event.
80 | ///
81 | /// Name of the property.
82 | protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
83 | {
84 | Debug.Assert(
85 | string.IsNullOrEmpty(propertyName) ||
86 | (this.GetType().GetRuntimeProperty(propertyName) != null),
87 | "Check that the property name exists for this instance.");
88 | this.propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
89 | }
90 |
91 | ///
92 | /// Raises the PropertyChanged event.
93 | ///
94 | /// The property names.
95 | protected void OnPropertyChanged(params string[] propertyNames)
96 | {
97 | if (propertyNames == null)
98 | {
99 | throw new ArgumentNullException(nameof(propertyNames));
100 | }
101 |
102 | foreach (var propertyName in propertyNames)
103 | {
104 | this.OnPropertyChanged(propertyName);
105 | }
106 | }
107 |
108 | ///
109 | /// Raises the PropertyChanging event.
110 | ///
111 | /// Name of the property.
112 | protected virtual void OnPropertyChanging([CallerMemberName] string propertyName = null)
113 | {
114 | Debug.Assert(
115 | string.IsNullOrEmpty(propertyName) ||
116 | (this.GetType().GetRuntimeProperty(propertyName) != null),
117 | "Check that the property name exists for this instance.");
118 | this.propertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
119 | }
120 |
121 | ///
122 | /// Raises the PropertyChanging event.
123 | ///
124 | /// The property names.
125 | protected void OnPropertyChanging(params string[] propertyNames)
126 | {
127 | if (propertyNames == null)
128 | {
129 | throw new ArgumentNullException(nameof(propertyNames));
130 | }
131 |
132 | foreach (var propertyName in propertyNames)
133 | {
134 | this.OnPropertyChanging(propertyName);
135 | }
136 | }
137 |
138 | ///
139 | /// Sets the value of the property to the specified value if it has changed.
140 | ///
141 | /// The type of the property.
142 | /// The current value of the property.
143 | /// The new value of the property.
144 | /// Name of the property.
145 | /// true if the property was changed, otherwise false .
146 | protected bool SetProperty(
147 | ref TProp currentValue,
148 | TProp newValue,
149 | [CallerMemberName] string propertyName = null)
150 | {
151 | this.ThrowIfDisposed();
152 |
153 | if (!object.Equals(currentValue, newValue))
154 | {
155 | this.OnPropertyChanging(propertyName);
156 | currentValue = newValue;
157 | this.OnPropertyChanged(propertyName);
158 |
159 | return true;
160 | }
161 |
162 | return false;
163 | }
164 |
165 | ///
166 | /// Sets the value of the property to the specified value if it has changed.
167 | ///
168 | /// The type of the property.
169 | /// The current value of the property.
170 | /// The new value of the property.
171 | /// The names of all properties changed.
172 | /// true if the property was changed, otherwise false .
173 | protected bool SetProperty(
174 | ref TProp currentValue,
175 | TProp newValue,
176 | params string[] propertyNames)
177 | {
178 | this.ThrowIfDisposed();
179 |
180 | if (!object.Equals(currentValue, newValue))
181 | {
182 | this.OnPropertyChanging(propertyNames);
183 | currentValue = newValue;
184 | this.OnPropertyChanged(propertyNames);
185 |
186 | return true;
187 | }
188 |
189 | return false;
190 | }
191 |
192 | ///
193 | /// Sets the value of the property to the specified value if it has changed.
194 | ///
195 | /// A function which returns true if the property value has changed, otherwise false .
196 | /// The action where the property is set.
197 | /// Name of the property.
198 | /// true if the property was changed, otherwise false .
199 | protected bool SetProperty(
200 | Func equal,
201 | Action action,
202 | [CallerMemberName] string propertyName = null)
203 | {
204 | this.ThrowIfDisposed();
205 |
206 | if (equal())
207 | {
208 | return false;
209 | }
210 |
211 | this.OnPropertyChanging(propertyName);
212 | action();
213 | this.OnPropertyChanged(propertyName);
214 |
215 | return true;
216 | }
217 |
218 | ///
219 | /// Sets the value of the property to the specified value if it has changed.
220 | ///
221 | /// A function which returns true if the property value has changed, otherwise false .
222 | /// The action where the property is set.
223 | /// The property names.
224 | /// true if the property was changed, otherwise false .
225 | protected bool SetProperty(
226 | Func equal,
227 | Action action,
228 | params string[] propertyNames)
229 | {
230 | this.ThrowIfDisposed();
231 |
232 | if (equal())
233 | {
234 | return false;
235 | }
236 |
237 | this.OnPropertyChanging(propertyNames);
238 | action();
239 | this.OnPropertyChanged(propertyNames);
240 |
241 | return true;
242 | }
243 | }
244 | }
245 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Version: 1.3.2 (Using https://semver.org/)
2 | # Updated: 2019-08-04
3 | # See https://github.com/RehanSaeed/EditorConfig/releases for release notes.
4 | # See https://github.com/RehanSaeed/EditorConfig for updates to this file.
5 | # See http://EditorConfig.org for more information about .editorconfig files.
6 |
7 | ##########################################
8 | # Common Settings
9 | ##########################################
10 |
11 | # This file is the top-most EditorConfig file
12 | root = true
13 |
14 | # All Files
15 | [*]
16 | charset = utf-8
17 | indent_style = space
18 | indent_size = 4
19 | insert_final_newline = true
20 | trim_trailing_whitespace = true
21 |
22 | ##########################################
23 | # File Extension Settings
24 | ##########################################
25 |
26 | # Visual Studio Solution Files
27 | [*.sln]
28 | indent_style = tab
29 |
30 | # Visual Studio XML Project Files
31 | [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
32 | indent_size = 2
33 |
34 | # Various XML Configuration Files
35 | [*.{xml,config,props,targets,nuspec,resx,ruleset,vsixmanifest,vsct}]
36 | indent_size = 2
37 |
38 | # JSON Files
39 | [*.{json,json5}]
40 | indent_size = 2
41 |
42 | # YAML Files
43 | [*.{yml,yaml}]
44 | indent_size = 2
45 |
46 | # Markdown Files
47 | [*.md]
48 | trim_trailing_whitespace = false
49 |
50 | # Web Files
51 | [*.{htm,html,js,ts,tsx,css,sass,scss,less,svg,vue}]
52 | indent_size = 2
53 |
54 | # Batch Files
55 | [*.{cmd,bat}]
56 | end_of_line = crlf
57 |
58 | # Bash Files
59 | [*.sh]
60 | end_of_line = lf
61 |
62 | ##########################################
63 | # .NET Language Conventions
64 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions
65 | ##########################################
66 |
67 | # .NET Code Style Settings
68 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#net-code-style-settings
69 | [*.{cs,csx,cake,vb}]
70 | # "this." and "Me." qualifiers
71 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#this-and-me
72 | dotnet_style_qualification_for_field = true:warning
73 | dotnet_style_qualification_for_property = true:warning
74 | dotnet_style_qualification_for_method = true:warning
75 | dotnet_style_qualification_for_event = true:warning
76 | # Language keywords instead of framework type names for type references
77 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#language-keywords
78 | dotnet_style_predefined_type_for_locals_parameters_members = true:warning
79 | dotnet_style_predefined_type_for_member_access = true:warning
80 | # Modifier preferences
81 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#normalize-modifiers
82 | dotnet_style_require_accessibility_modifiers = always:warning
83 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async
84 | visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async
85 | dotnet_style_readonly_field = true:warning
86 | # Parentheses preferences
87 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#parentheses-preferences
88 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning
89 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning
90 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning
91 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion
92 | # Expression-level preferences
93 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-level-preferences
94 | dotnet_style_object_initializer = true:warning
95 | dotnet_style_collection_initializer = true:warning
96 | dotnet_style_explicit_tuple_names = true:warning
97 | dotnet_style_prefer_inferred_tuple_names = true:warning
98 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
99 | dotnet_style_prefer_auto_properties = true:warning
100 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
101 | dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
102 | dotnet_style_prefer_conditional_expression_over_return = false:suggestion
103 | dotnet_style_prefer_compound_assignment = true:warning
104 | # Null-checking preferences
105 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#null-checking-preferences
106 | dotnet_style_coalesce_expression = true:warning
107 | dotnet_style_null_propagation = true:warning
108 | # Parameter preferences
109 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#parameter-preferences
110 | dotnet_code_quality_unused_parameters = all:warning
111 | # More style options (Undocumented)
112 | # https://github.com/MicrosoftDocs/visualstudio-docs/issues/3641
113 | dotnet_style_operator_placement_when_wrapping = end_of_line
114 |
115 | # C# Code Style Settings
116 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#c-code-style-settings
117 | [*.{cs,csx,cake}]
118 | # Implicit and explicit types
119 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#implicit-and-explicit-types
120 | csharp_style_var_for_built_in_types = true:warning
121 | csharp_style_var_when_type_is_apparent = true:warning
122 | csharp_style_var_elsewhere = true:warning
123 | # Expression-bodied members
124 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-bodied-members
125 | csharp_style_expression_bodied_methods = true:warning
126 | csharp_style_expression_bodied_constructors = true:warning
127 | csharp_style_expression_bodied_operators = true:warning
128 | csharp_style_expression_bodied_properties = true:warning
129 | csharp_style_expression_bodied_indexers = true:warning
130 | csharp_style_expression_bodied_accessors = true:warning
131 | csharp_style_expression_bodied_lambdas = true:warning
132 | csharp_style_expression_bodied_local_functions = true:warning
133 | # Pattern matching
134 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#pattern-matching
135 | csharp_style_pattern_matching_over_is_with_cast_check = true:warning
136 | csharp_style_pattern_matching_over_as_with_null_check = true:warning
137 | # Inlined variable declarations
138 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#inlined-variable-declarations
139 | csharp_style_inlined_variable_declaration = true:warning
140 | # Expression-level preferences
141 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-level-preferences
142 | csharp_prefer_simple_default_expression = true:warning
143 | # "Null" checking preferences
144 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#c-null-checking-preferences
145 | csharp_style_throw_expression = true:warning
146 | csharp_style_conditional_delegate_call = true:warning
147 | # Code block preferences
148 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#code-block-preferences
149 | csharp_prefer_braces = true:warning
150 | # Unused value preferences
151 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#unused-value-preferences
152 | csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
153 | csharp_style_unused_value_assignment_preference = discard_variable:suggestion
154 | # Index and range preferences
155 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#index-and-range-preferences
156 | csharp_style_prefer_index_operator = true:warning
157 | csharp_style_prefer_range_operator = true:warning
158 | # Miscellaneous preferences
159 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#miscellaneous-preferences
160 | csharp_style_deconstructed_variable_declaration = true:warning
161 | csharp_style_pattern_local_over_anonymous_function = true:warning
162 | csharp_using_directive_placement = inside_namespace:warning
163 | csharp_prefer_static_local_function = true:warning
164 | csharp_prefer_simple_using_statement = false:warning
165 |
166 | ##########################################
167 | # .NET Formatting Conventions
168 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-code-style-settings-reference#formatting-conventions
169 | ##########################################
170 |
171 | # Organize usings
172 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#organize-using-directives
173 | dotnet_sort_system_directives_first = true
174 | # Newline options
175 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#new-line-options
176 | csharp_new_line_before_open_brace = all
177 | csharp_new_line_before_else = true
178 | csharp_new_line_before_catch = true
179 | csharp_new_line_before_finally = true
180 | csharp_new_line_before_members_in_object_initializers = true
181 | csharp_new_line_before_members_in_anonymous_types = true
182 | csharp_new_line_between_query_expression_clauses = true
183 | # Indentation options
184 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#indentation-options
185 | csharp_indent_case_contents = true
186 | csharp_indent_switch_labels = true
187 | csharp_indent_labels = no_change
188 | csharp_indent_block_contents = true
189 | csharp_indent_braces = false
190 | csharp_indent_case_contents_when_block = false
191 | # Spacing options
192 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#spacing-options
193 | csharp_space_after_cast = false
194 | csharp_space_after_keywords_in_control_flow_statements = true
195 | csharp_space_between_parentheses = false
196 | csharp_space_before_colon_in_inheritance_clause = true
197 | csharp_space_after_colon_in_inheritance_clause = true
198 | csharp_space_around_binary_operators = before_and_after
199 | csharp_space_between_method_declaration_parameter_list_parentheses = false
200 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
201 | csharp_space_between_method_declaration_name_and_open_parenthesis = false
202 | csharp_space_between_method_call_parameter_list_parentheses = false
203 | csharp_space_between_method_call_empty_parameter_list_parentheses = false
204 | csharp_space_between_method_call_name_and_opening_parenthesis = false
205 | csharp_space_after_comma = true
206 | csharp_space_before_comma = false
207 | csharp_space_after_dot = false
208 | csharp_space_before_dot = false
209 | csharp_space_after_semicolon_in_for_statement = true
210 | csharp_space_before_semicolon_in_for_statement = false
211 | csharp_space_around_declaration_statements = false
212 | csharp_space_before_open_square_brackets = false
213 | csharp_space_between_empty_square_brackets = false
214 | csharp_space_between_square_brackets = false
215 | # Wrapping options
216 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#wrap-options
217 | csharp_preserve_single_line_statements = false
218 | csharp_preserve_single_line_blocks = true
219 |
220 | ##########################################
221 | # .NET Naming Conventions
222 | # https://docs.microsoft.com/visualstudio/ide/editorconfig-naming-conventions
223 | ##########################################
224 |
225 | [*.{cs,csx,cake,vb}]
226 |
227 | ##########################################
228 | # Styles
229 | ##########################################
230 |
231 | # camel_case_style - Define the camelCase style
232 | dotnet_naming_style.camel_case_style.capitalization = camel_case
233 | # pascal_case_style - Define the PascalCase style
234 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case
235 | # first_upper_style - The first character must start with an upper-case character
236 | dotnet_naming_style.first_upper_style.capitalization = first_word_upper
237 | # prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I'
238 | dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case
239 | dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I
240 | # prefix_type_parameters_with_t_style - Generic Type Parameters must be PascalCase and the first character must be a 'T'
241 | dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case
242 | dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T
243 | # disallowed_style - Anything that has this style applied is marked as disallowed
244 | dotnet_naming_style.disallowed_style.capitalization = pascal_case
245 | dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____
246 | dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____
247 | # internal_error_style - This style should never occur... if it does, it's indicates a bug in file or in the parser using the file
248 | dotnet_naming_style.internal_error_style.capitalization = pascal_case
249 | dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____
250 | dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____
251 |
252 | ##########################################
253 | # .NET Design Guideline Field Naming Rules
254 | # Naming rules for fields follow the .NET Framework design guidelines
255 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/index
256 | ##########################################
257 |
258 | # All public/protected/protected_internal constant fields must be PascalCase
259 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/field
260 | dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal
261 | dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const
262 | dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field
263 | dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group
264 | dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
265 | dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning
266 |
267 | # All public/protected/protected_internal static readonly fields must be PascalCase
268 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/field
269 | dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal
270 | dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly
271 | dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field
272 | dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group
273 | dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
274 | dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning
275 |
276 | # No other public/protected/protected_internal fields are allowed
277 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/field
278 | dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal
279 | dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field
280 | dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group
281 | dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style
282 | dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error
283 |
284 | ##########################################
285 | # StyleCop Field Naming Rules
286 | # Naming rules for fields follow the StyleCop analyzers
287 | # This does not override any rules using disallowed_style above
288 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers
289 | ##########################################
290 |
291 | # All constant fields must be PascalCase
292 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1303.md
293 | dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
294 | dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const
295 | dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field
296 | dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group
297 | dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
298 | dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning
299 |
300 | # All static readonly fields must be PascalCase
301 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1311.md
302 | dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
303 | dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly
304 | dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field
305 | dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group
306 | dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
307 | dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning
308 |
309 | # No non-private instance fields are allowed
310 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
311 | dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected
312 | dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field
313 | dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group
314 | dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style
315 | dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error
316 |
317 | # Private fields must be camelCase
318 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1306.md
319 | dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private
320 | dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field
321 | dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group
322 | dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = camel_case_style
323 | dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning
324 |
325 | # Local variables must be camelCase
326 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md
327 | dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local
328 | dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local
329 | dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group
330 | dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style
331 | dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = silent
332 |
333 | # This rule should never fire. However, it's included for at least two purposes:
334 | # First, it helps to understand, reason about, and root-case certain types of issues, such as bugs in .editorconfig parsers.
335 | # Second, it helps to raise immediate awareness if a new field type is added (as occurred recently in C#).
336 | dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = *
337 | dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field
338 | dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group
339 | dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style
340 | dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error
341 |
342 |
343 | ##########################################
344 | # Other Naming Rules
345 | ##########################################
346 |
347 | # All of the following must be PascalCase:
348 | # - Namespaces
349 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-namespaces
350 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md
351 | # - Classes and Enumerations
352 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
353 | # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md
354 | # - Delegates
355 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-common-types
356 | # - Constructors, Properties, Events, Methods
357 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-type-members
358 | dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property
359 | dotnet_naming_rule.element_rule.symbols = element_group
360 | dotnet_naming_rule.element_rule.style = pascal_case_style
361 | dotnet_naming_rule.element_rule.severity = warning
362 |
363 | # Interfaces use PascalCase and are prefixed with uppercase 'I'
364 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
365 | dotnet_naming_symbols.interface_group.applicable_kinds = interface
366 | dotnet_naming_rule.interface_rule.symbols = interface_group
367 | dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style
368 | dotnet_naming_rule.interface_rule.severity = warning
369 |
370 | # Generics Type Parameters use PascalCase and are prefixed with uppercase 'T'
371 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
372 | dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter
373 | dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group
374 | dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style
375 | dotnet_naming_rule.type_parameter_rule.severity = warning
376 |
377 | # Function parameters use camelCase
378 | # https://docs.microsoft.com/dotnet/standard/design-guidelines/naming-parameters
379 | dotnet_naming_symbols.parameters_group.applicable_kinds = parameter
380 | dotnet_naming_rule.parameters_rule.symbols = parameters_group
381 | dotnet_naming_rule.parameters_rule.style = camel_case_style
382 | dotnet_naming_rule.parameters_rule.severity = warning
383 |
384 | ##########################################
385 | # License
386 | ##########################################
387 | # The following applies as to the .editorconfig file ONLY, and is
388 | # included below for reference, per the requirements of the license
389 | # corresponding to this .editorconfig file.
390 | # See: https://github.com/RehanSaeed/EditorConfig
391 | #
392 | # MIT License
393 | #
394 | # Copyright (c) 2017-2019 Muhammad Rehan Saeed
395 | # Copyright (c) 2019 Henry Gabryjelski
396 | #
397 | # Permission is hereby granted, free of charge, to any
398 | # person obtaining a copy of this software and associated
399 | # documentation files (the "Software"), to deal in the
400 | # Software without restriction, including without limitation
401 | # the rights to use, copy, modify, merge, publish, distribute,
402 | # sublicense, and/or sell copies of the Software, and to permit
403 | # persons to whom the Software is furnished to do so, subject
404 | # to the following conditions:
405 | #
406 | # The above copyright notice and this permission notice shall be
407 | # included in all copies or substantial portions of the Software.
408 | #
409 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
410 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
411 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
412 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
413 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
414 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
415 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
416 | # OTHER DEALINGS IN THE SOFTWARE.
417 | ##########################################
418 |
--------------------------------------------------------------------------------