1
//
2
3
4
using System;
5
using System.Collections.Generic;
6
using System.Diagnostics;
7
using System.Linq;
8
using System.Runtime.Serialization;
9
using System.Threading;
10
using System.Threading.Tasks;
11
12
namespace SharpLib.Ear
13
{
14
[DataContract]
15
[AttributeObject(Id = "Action", Name = "Action Group", Description = "Use it to group other actions together.")]
16
public class Action: Object
17
18
[DataMember]
19
[AttributeObjectProperty
20
(
21
Id = "Action.Iterations",
22
Name = "Iterations",
23
Description = "Specifies the number of time this action should execute.",
24
Minimum = "0",
25
Maximum = "10000",
26
Increment = "1"
27
)
28
]
29
public int Iterations { get; set; } = 1;
30
31
/// <summary>
32
///
33
/// </summary>
34
public bool Enabled
35
36
get { return Iterations > 0; }
37
}
38
39
40
public override bool IsValid()
41
42
// We don't want to override this behaviour for derived classes
43
if (GetType() == typeof(Action))
44
45
// Avoid having empty actions with no name
46
return !string.IsNullOrEmpty(Name);
47
48
49
return base.IsValid();
50
51
52
53
54
/// Basic action just does nothing
55
56
/// <returns></returns>
57
protected virtual async Task DoExecute()
58
59
60
61
62
63
/// Allows testing from generic edit dialog.
64
65
public void Test()
66
67
Trace.WriteLine("Action test");
68
Execute();
69
70
71
72
/// Execute our action N times.
73
74
75
public async Task Execute()
76
77
if (!IsValid())
78
79
Trace.WriteLine("EAR: Action.Execute: WARNING: Action invalid, aborting execution: " + Brief());
80
return;
81
82
83
if (!Enabled)
84
85
Trace.WriteLine("EAR: Action.Execute: Action disabled: " + Brief());
86
87
88
89
for (int i = Iterations; i > 0; i--)
90
91
Trace.WriteLine($"EAR: Action.Execute: [{Iterations - i + 1}/{Iterations}] - {BriefBase()}");
92
//For each iteration
93
//We first execute ourselves
94
await DoExecute();
95
96
//Then our children
97
foreach (Action a in Objects.OfType<Action>())
98
99
await a.Execute();
100
101
102
103
104
105
/// For inherited classes to override.
106
107
108
public virtual string BriefBase()
109
110
return string.IsNullOrEmpty(Name)? AttributeName : Name;
111
112
113
114
/// Dynamic object description.
115
116
117
public sealed override string Brief()
118
119
return Iterations > 1 ? $"{Iterations} x " + BriefBase():BriefBase();
120
121
122
123
124
125
126
127
128
129
130