-
Notifications
You must be signed in to change notification settings - Fork 177
/
FormBuilder.cs
521 lines (480 loc) · 20.1 KB
/
FormBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Bot.Builder.Community.Dialogs.FormFlow.Advanced;
using Bot.Builder.Community.Dialogs.FormFlow.Resource;
namespace Bot.Builder.Community.Dialogs.FormFlow
{
#region Documentation
/// <summary>Abstract base class for Form Builders.</summary>
/// <typeparam name="T">Form state class. </typeparam>
#endregion
public abstract class FormBuilderBase<T> : IFormBuilder<T>
where T : class
{
public virtual IForm<T> Build(Assembly resourceAssembly = null, string resourceName = null)
{
if (resourceAssembly == null)
{
resourceAssembly = typeof(T).Assembly;
}
if (resourceName == null)
{
resourceName = typeof(T).FullName;
}
if (this._form._prompter == null)
{
this._form._prompter = async (context, prompt, state, field) =>
{
var preamble = context.MakeMessage();
var promptMessage = context.MakeMessage();
if (prompt.GenerateMessages(preamble, promptMessage))
{
await context.PostAsync(preamble);
}
await context.PostAsync(promptMessage);
return prompt;
};
}
var lang = resourceAssembly.GetCustomAttribute<NeutralResourcesLanguageAttribute>();
if (lang != null && !string.IsNullOrWhiteSpace(lang.CultureName))
{
IEnumerable<string> missing, extra;
string name = null;
foreach (var resource in resourceAssembly.GetManifestResourceNames())
{
if (resource.Contains(resourceName))
{
var pieces = resource.Split('.');
name = string.Join(".", pieces.Take(pieces.Count() - 1));
break;
}
}
if (name != null)
{
var rm = new ResourceManager(name, resourceAssembly);
var rs = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true);
_form.Localize(rs.GetEnumerator(), out missing, out extra);
if (missing.Any())
{
throw new MissingManifestResourceException($"Missing {missing.Count()} resources {string.Join(", ", missing)}");
}
}
}
Validate();
return this._form;
}
public FormConfiguration Configuration { get { return _form.Configuration; } }
public bool HasField(string name)
{
return _form.Fields.Field(name) != null;
}
public virtual IFormBuilder<T> Message(string message, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
_form._steps.Add(new MessageStep<T>(new PromptAttribute(message), condition, dependencies, _form));
return this;
}
public virtual IFormBuilder<T> Message(PromptAttribute prompt, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
_form._steps.Add(new MessageStep<T>(prompt, condition, dependencies, _form));
return this;
}
public virtual IFormBuilder<T> Message(MessageDelegate<T> generateMessage, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
_form._steps.Add(new MessageStep<T>(generateMessage, condition, dependencies, _form));
return this;
}
public virtual IFormBuilder<T> Field(IField<T> field)
{
return AddField(field);
}
public virtual IFormBuilder<T> Confirm(string prompt, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
return Confirm(new PromptAttribute(prompt) { ChoiceFormat = Resources.ConfirmChoiceFormat, AllowDefault = BoolDefault.False }, condition, dependencies);
}
public virtual IFormBuilder<T> Confirm(PromptAttribute prompt, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
if (condition == null) condition = state => true;
dependencies = dependencies ?? _form.Dependencies(_form.Steps.Count());
var confirmation = new Confirmation<T>(prompt, condition, dependencies, _form);
confirmation.Form = _form;
_form._fields.Add(confirmation);
_form._steps.Add(new ConfirmStep<T>(confirmation));
return this;
}
public virtual IFormBuilder<T> Confirm(MessageDelegate<T> generateMessage, ActiveDelegate<T> condition = null, IEnumerable<string> dependencies = null)
{
if (condition == null) condition = state => true;
dependencies = dependencies ?? _form.Dependencies(_form.Steps.Count());
var confirmation = new Confirmation<T>(generateMessage, condition, dependencies, _form);
confirmation.Form = _form;
_form._fields.Add(confirmation);
_form._steps.Add(new ConfirmStep<T>(confirmation));
return this;
}
public virtual IFormBuilder<T> OnCompletion(OnCompletionAsyncDelegate<T> callback)
{
_form._completion = callback;
return this;
}
public virtual IFormBuilder<T> Prompter(PromptAsyncDelegate<T> prompter)
{
_form._prompter = prompter;
return this;
}
public abstract IFormBuilder<T> Field(string name, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null);
public abstract IFormBuilder<T> Field(string name, string prompt, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null);
public abstract IFormBuilder<T> Field(string name, PromptAttribute prompt, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null);
public abstract IFormBuilder<T> AddRemainingFields(IEnumerable<string> exclude = null);
private Dictionary<TemplateUsage, int> _templateArgs = new Dictionary<TemplateUsage, int>
{
{ TemplateUsage.AttachmentCollection, 0 },
{ TemplateUsage.AttachmentCollectionDescription, 1 },
{ TemplateUsage.AttachmentCollectionHelp, 1 },
{ TemplateUsage.AttachmentContentTypeValidatorError, 2 },
{ TemplateUsage.AttachmentContentTypeValidatorHelp, 1 },
{ TemplateUsage.AttachmentField, 0 },
{ TemplateUsage.AttachmentFieldDescription, 2 },
{ TemplateUsage.AttachmentFieldHelp, 1 },
{ TemplateUsage.Bool, 0 },
{ TemplateUsage.BoolHelp, 1},
{ TemplateUsage.Clarify, 1},
{ TemplateUsage.Confirmation, 0 },
{ TemplateUsage.CurrentChoice, 0},
{ TemplateUsage.DateTime, 0},
{ TemplateUsage.DateTimeHelp, 2},
{ TemplateUsage.Double, 2},
{ TemplateUsage.DoubleHelp, 4},
{ TemplateUsage.EnumManyNumberHelp, 3},
{ TemplateUsage.EnumOneNumberHelp, 3},
{ TemplateUsage.EnumManyWordHelp, 3},
{ TemplateUsage.EnumOneWordHelp, 3},
{ TemplateUsage.EnumSelectOne, 0},
{ TemplateUsage.EnumSelectMany, 0},
{ TemplateUsage.Feedback, 1},
{ TemplateUsage.Help, 2},
{ TemplateUsage.HelpClarify, 2},
{ TemplateUsage.HelpConfirm, 2},
{ TemplateUsage.HelpNavigation, 2},
{ TemplateUsage.Integer, 2},
{ TemplateUsage.IntegerHelp, 4},
{ TemplateUsage.Navigation, 0},
{ TemplateUsage.NavigationCommandHelp, 1},
{ TemplateUsage.NavigationFormat, 0},
{ TemplateUsage.NavigationHelp, 2},
{ TemplateUsage.NoPreference, 0},
{ TemplateUsage.NotUnderstood, 1},
{ TemplateUsage.StatusFormat, 0},
{ TemplateUsage.String, 0},
{ TemplateUsage.StringHelp, 2},
{ TemplateUsage.Unspecified, 0},
};
private int TemplateArgs(TemplateUsage usage)
{
int args;
if (!_templateArgs.TryGetValue(usage, out args))
{
throw new ArgumentException("Missing template usage for validation");
}
return args;
}
private void Validate()
{
foreach (var step in _form._steps)
{
// Validate prompt
var annotation = step.Annotation;
if (annotation != null)
{
var name = step.Type == StepType.Field ? step.Name : "";
foreach (var pattern in annotation.Patterns)
{
ValidatePattern(pattern, _form.Fields.Field(name), 5);
}
if (step.Type != StepType.Message)
{
foreach (TemplateUsage usage in Enum.GetValues(typeof(TemplateUsage)))
{
if (usage != TemplateUsage.None)
{
foreach (var pattern in step.Field.Template(usage).Patterns)
{
ValidatePattern(pattern, _form.Fields.Field(name), TemplateArgs(usage));
}
}
}
}
}
}
ValidatePattern(_form.Configuration.DefaultPrompt.ChoiceFormat, null, 2);
}
private void ValidatePattern(string pattern, IField<T> field, int maxArgs)
{
if (!Prompter<T>.ValidatePattern(_form, pattern, field, maxArgs))
{
throw new ArgumentException(string.Format("Illegal pattern: \"{0}\"", pattern));
}
}
private IFormBuilder<T> AddField(IField<T> field)
{
field.Form = _form;
_form._fields.Add(field);
var step = new FieldStep<T>(field.Name, _form);
var stepIndex = this._form._steps.FindIndex(s => s.Name == field.Name);
if (stepIndex >= 0)
{
_form._steps[stepIndex] = step;
}
else
{
_form._steps.Add(step);
}
return this;
}
protected internal sealed class Form : IForm<T>
{
internal readonly FormConfiguration _configuration = new FormConfiguration();
internal readonly Fields<T> _fields = new Fields<T>();
internal readonly List<IStep<T>> _steps = new List<IStep<T>>();
internal OnCompletionAsyncDelegate<T> _completion = null;
internal PromptAsyncDelegate<T> _prompter = null;
internal ILocalizer _resources = new Localizer() { Culture = CultureInfo.CurrentUICulture };
public Form()
{
}
internal override ILocalizer Resources
{
get
{
return _resources;
}
}
public override void SaveResources(IResourceWriter writer)
{
_resources = new Localizer() { Culture = CultureInfo.CurrentUICulture };
foreach (var step in _steps)
{
step.SaveResources();
}
_resources.Save(writer);
}
public override void Localize(IDictionaryEnumerator reader, out IEnumerable<string> missing, out IEnumerable<string> extra)
{
foreach (var step in _steps)
{
step.SaveResources();
}
_resources = _resources.Load(reader, out missing, out extra);
foreach (var step in _steps)
{
step.Localize();
}
}
internal override FormConfiguration Configuration
{
get
{
return _configuration;
}
}
internal override IReadOnlyList<IStep<T>> Steps
{
get
{
return _steps;
}
}
internal override async Task<FormPrompt> Prompt(DialogContext context, FormPrompt prompt, T state, IField<T> field)
{
return prompt == null ? prompt : await _prompter(context, prompt, state, field);
}
internal override OnCompletionAsyncDelegate<T> Completion
{
get
{
return _completion;
}
}
public override IFields<T> Fields
{
get
{
return _fields;
}
}
}
protected internal Form _form = new Form();
}
#region Documentation
/// <summary> Build a form by specifying messages, fields and confirmations via reflection or programatically.</summary>
/// <typeparam name="T">Form state class. </typeparam>
/// <remarks>
/// Fields will be defined through reflection over the type <typeparamref name="T"/> and attributes like
/// <see cref="DescribeAttribute"/>,
/// <see cref="NumericAttribute"/>,
/// <see cref="OptionalAttribute"/>
/// <see cref="PatternAttribute"/>,
/// <see cref="PromptAttribute"/>,
/// <see cref="TermsAttribute"/> and
/// <see cref="TemplateAttribute"/>.
/// For all of the attributes, reasonable defaults will be generated.
/// </remarks>
#endregion
public sealed class FormBuilder<T> : FormBuilderBase<T>
where T : class
{
private readonly bool _ignoreAnnotations;
/// <summary>
/// Create a new form builder for building a form using reflection.
/// </summary>
/// <param name="ignoreAnnotations">True to ignore any attributes on the form class.</param>
public FormBuilder(bool ignoreAnnotations = false)
: base()
{
_ignoreAnnotations = ignoreAnnotations;
}
public override IForm<T> Build(Assembly resourceAssembly = null, string resourceName = null)
{
if (!_form._steps.Any((step) => step.Type == StepType.Field))
{
var paths = new List<string>();
FieldPaths(typeof(T), "", paths);
foreach (var path in paths)
{
Field(new FieldReflector<T>(path, _ignoreAnnotations));
}
Confirm(new PromptAttribute(_form.Configuration.Template(TemplateUsage.Confirmation)));
}
return base.Build(resourceAssembly, resourceName);
}
public override IFormBuilder<T> Field(string name, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null)
{
var field = new FieldReflector<T>(name, _ignoreAnnotations);
field.SetActive(active);
field.SetValidate(validate);
return Field(field);
}
public override IFormBuilder<T> Field(string name, string prompt, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null)
{
return Field(name, new PromptAttribute(prompt), active, validate);
}
public override IFormBuilder<T> Field(string name, PromptAttribute prompt, ActiveDelegate<T> active = null, ValidateAsyncDelegate<T> validate = null)
{
var field = new FieldReflector<T>(name, _ignoreAnnotations);
field.SetActive(active);
field.SetValidate(validate);
field.SetPrompt(prompt);
return Field(field);
}
public override IFormBuilder<T> AddRemainingFields(IEnumerable<string> exclude = null)
{
var exclusions = (exclude == null ? Array.Empty<string>() : exclude.ToArray());
var paths = new List<string>();
FieldPaths(typeof(T), "", paths);
foreach (var path in paths)
{
if (!exclusions.Contains(path) && !HasField(path))
{
Field(new FieldReflector<T>(path, _ignoreAnnotations));
}
}
return this;
}
private void FieldPaths(Type type, string path, List<string> paths)
{
var newPath = (path == "" ? path : path + ".");
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(f => !f.IsDefined(typeof(IgnoreFieldAttribute))).OrderBy(f => f.GetCustomAttributes(typeof(OrderAttribute), true).Cast<OrderAttribute>().Select(a => a.Order).FirstOrDefault()))
{
TypePaths(field.FieldType, newPath + field.Name, paths);
}
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.CanRead && property.CanWrite)
{
TypePaths(property.PropertyType, newPath + property.Name, paths);
}
}
}
private void TypePaths(Type type, string path, List<string> paths)
{
if (type.IsClass)
{
if (type == typeof(string) || type.IsAttachmentType())
{
paths.Add(path);
}
else if (type.IsIEnumerable())
{
var elt = type.GetGenericElementType();
if (elt.IsEnum)
{
paths.Add(path);
}
else
{
// TODO: What to do about enumerations of things other than enums?
}
}
else
{
FieldPaths(type, path, paths);
}
}
else if (type.IsAttachmentCollection())
{
paths.Add(path);
}
else if (type.IsEnum)
{
paths.Add(path);
}
else if (type == typeof(bool))
{
paths.Add(path);
}
else if (type.IsIntegral())
{
paths.Add(path);
}
else if (type.IsDouble())
{
paths.Add(path);
}
else if (type.IsNullable() && type.IsValueType)
{
paths.Add(path);
}
else if (type == typeof(DateTime))
{
paths.Add(path);
}
}
}
}