-
Notifications
You must be signed in to change notification settings - Fork 229
/
ActionInvoker.cs
97 lines (81 loc) · 2.79 KB
/
ActionInvoker.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.VisualStudio.Web.CodeGeneration.Core;
namespace Microsoft.VisualStudio.Web.CodeGeneration
{
public class ActionInvoker
{
public ActionInvoker(ActionDescriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
ActionDescriptor = descriptor;
}
public ActionDescriptor ActionDescriptor
{
get;
private set;
}
public void Execute(string[] args)
{
var app = new CommandLineApplication();
app.Command(ActionDescriptor.Generator.Name, c =>
{
c.HelpOption("--help|-h|-?");
BuildCommandLine(c);
});
app.Execute(args);
}
internal void BuildCommandLine(CommandLineApplication command)
{
foreach (var param in ActionDescriptor.Parameters)
{
param.AddCommandLineParameterTo(command);
}
command.Invoke = () =>
{
object modelInstance;
try
{
modelInstance = Activator.CreateInstance(ActionDescriptor.ActionModel);
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(MessageStrings.ModelCreationFailed, ex.Message));
}
foreach (var param in ActionDescriptor.Parameters)
{
param.Property.SetValue(modelInstance, param.Value);
}
var codeGeneratorInstance = ActionDescriptor.Generator.CodeGeneratorInstance;
try
{
var result = ActionDescriptor.ActionMethod.Invoke(codeGeneratorInstance, new[] { modelInstance });
if (result is Task)
{
((Task)result).Wait();
}
}
catch (Exception ex)
{
while (ex is TargetInvocationException)
{
ex = ex.InnerException;
}
if (ex is AggregateException)
{
ex = ex.GetBaseException();
}
throw new InvalidOperationException(ex.Message);
}
return 0;
};
}
}
}