-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathNodeModelAssemblyLoader.cs
More file actions
305 lines (266 loc) · 11.1 KB
/
NodeModelAssemblyLoader.cs
File metadata and controls
305 lines (266 loc) · 11.1 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Dynamo.Configuration;
using Dynamo.Graph.Nodes;
using Dynamo.Logging;
using Dynamo.Migration;
namespace Dynamo.Models
{
/// <summary>
/// This class is responsible for loading types that derive
/// from NodeModel. For information about package loading see the
/// PackageLoader. For information about loading other libraries,
/// see LibraryServices.
/// </summary>
public class NodeModelAssemblyLoader : LogSourceBase
{
#region Properties/Fields
/// <summary>
/// Used at startup to avoid reloading NodeModels from assemblies that have already been loaded.
/// Is NOT kept in sync with latest loaded assemblies - use LoadedAssemblies Property for that.
/// TODO refactor and use LoadedAssemblies instead
/// </summary>
internal readonly HashSet<string> LoadedAssemblyNames = new HashSet<string>();
private readonly HashSet<Assembly> loadedAssemblies = new HashSet<Assembly>();
/// <summary>
/// All assemblies that have been loaded into Dynamo.
/// </summary>
public IEnumerable<Assembly> LoadedAssemblies
{
get { return loadedAssemblies; }
}
#endregion
#region Events
/// <summary>
/// Delegate used in AssemblyLoaded event.
/// </summary>
/// <param name="args">AssemblyLoadedEventArgs</param>
public delegate void AssemblyLoadedHandler(AssemblyLoadedEventArgs args);
/// <summary>
/// This class holds the reference for the loaded assembly.
/// </summary>
public class AssemblyLoadedEventArgs
{
/// <summary>
/// Loaded assembly.
/// </summary>
public Assembly Assembly { get; private set; }
/// <summary>
/// Creates AssemblyLoadedEventArgs
/// </summary>
/// <param name="assembly">loaded assembly</param>
public AssemblyLoadedEventArgs(Assembly assembly)
{
Assembly = assembly;
}
}
/// <summary>
/// Event fired when a new assembly is loaded.
/// </summary>
public event AssemblyLoadedHandler AssemblyLoaded;
private void OnAssemblyLoaded(Assembly assem)
{
if (AssemblyLoaded != null)
{
AssemblyLoaded(new AssemblyLoadedEventArgs(assem));
}
}
#endregion
#region Methods
/// <summary>
/// Load all types which inherit from NodeModel whose assemblies are located in
/// the bin/nodes directory. Add the types to the searchviewmodel and
/// the controller's dictionaries.
/// </summary>
/// <param name="nodeDirectories">Directories that contain node assemblies.</param>
/// <param name="context"></param>
/// <param name="modelTypes"></param>
/// <param name="migrationTypes"></param>
internal void LoadNodeModelsAndMigrations(IEnumerable<string> nodeDirectories,
string context, out List<TypeLoadData> modelTypes, out List<TypeLoadData> migrationTypes)
{
var loadedAssembliesByPath = new Dictionary<string, Assembly>();
var loadedAssembliesByName = new Dictionary<string, Assembly>();
// cache the loaded assembly information
foreach (
var assembly in
AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.IsDynamic))
{
try
{
loadedAssembliesByPath[assembly.Location] = assembly;
loadedAssembliesByName[assembly.FullName] = assembly;
}
catch { }
}
// find all the dlls registered in all search paths
// and concatenate with all dlls in the current directory
var allDynamoAssemblyPaths = nodeDirectories.SelectMany(
path => Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly));
// add the core assembly to get things like code block nodes and watches.
//allDynamoAssemblyPaths.Add(Path.Combine(DynamoPathManager.Instance.MainExecPath, "DynamoCore.dll"));
ResolveEventHandler resolver =
(sender, args) =>
{
Assembly resolvedAssembly;
loadedAssembliesByName.TryGetValue(args.Name, out resolvedAssembly);
return resolvedAssembly;
};
AppDomain.CurrentDomain.AssemblyResolve += resolver;
var result = new List<TypeLoadData>();
var result2 = new List<TypeLoadData>();
foreach (var assemblyPath in allDynamoAssemblyPaths)
{
var fn = Path.GetFileName(assemblyPath);
if (fn == null)
continue;
// if the assembly has already been loaded, then
// skip it, otherwise cache it.
if (LoadedAssemblyNames.Contains(fn))
continue;
LoadedAssemblyNames.Add(fn);
try
{
Assembly assembly;
if (!loadedAssembliesByPath.TryGetValue(assemblyPath, out assembly))
{
assembly = Dynamo.Utilities.AssemblyHelper.LoadInALCFrom(assemblyPath);
loadedAssembliesByName[assembly.GetName().Name] = assembly;
loadedAssembliesByPath[assemblyPath] = assembly;
}
LoadNodesFromAssembly(assembly, context, result, result2);
}
catch (BadImageFormatException)
{
//swallow these warnings.
}
catch (Exception e)
{
Log(e);
}
}
AppDomain.CurrentDomain.AssemblyResolve -= resolver;
modelTypes = result;
migrationTypes = result2;
}
/// <summary>
/// Determine if a Type is a node. Used by LoadNodesFromAssembly to figure
/// out what nodes to load from other libraries (.dlls).
/// </summary>
/// <parameter>The type</parameter>
/// <returns>True if the type is node.</returns>
internal static bool IsNodeSubType(Type t)
{
return //t.Namespace == "Dynamo.Graph.Nodes" &&
!t.IsAbstract &&
t.IsSubclassOf(typeof(NodeModel))
&& t.GetConstructor(Type.EmptyTypes) != null;
}
internal static bool IsMigration(Type t)
{
return
t.GetMethods(BindingFlags.Public | BindingFlags.Static)
.SelectMany(method => method.GetCustomAttributes<NodeMigrationAttribute>(false))
.Any();
}
internal static bool ContainsNodeModelSubType(Assembly assem)
{
return assem.GetTypes().Any(IsNodeSubType);
}
internal static bool ContainsNodeViewCustomizationType(Assembly assem)
{
return GetCustomizationTypesUsingReflection(assem).Any();
}
internal static IEnumerable<Type> GetCustomizationTypesUsingReflection(Assembly assem)
{
IEnumerable<Type> output = new Type[] { };
//to avoid changing when we load DynamoCoreWpf bail out if it's not yet loaded.
if (AppDomain.CurrentDomain.GetAssemblies().All(x => !x.FullName.StartsWith("DynamoCoreWpf"))){
return output;
}
try
{
// TODO: ALC issue ? DynamoCoreWpf will probably be loaded only once, in a single ALC?
var customizerType = Type.GetType("Dynamo.Wpf.INodeViewCustomization`1,DynamoCoreWpf");
if (customizerType != null)
{
output = assem.GetTypes().Where(t => !t.IsAbstract && Utilities.TypeExtensions.ImplementsGeneric(customizerType, t));
return output;
}
}
catch
{
return output;
}
return output;
}
/// <summary>
/// Enumerate the types in an assembly and add them to DynamoController's
/// dictionaries and the search view model. Internally catches exceptions and sends the error
/// to the console.
/// </summary>
/// <Returns>The list of node types loaded from this assembly</Returns>
internal void LoadNodesFromAssembly(
Assembly assembly, string context, List<TypeLoadData> nodeModels,
List<TypeLoadData> migrationTypes)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
Type[] loadedTypes = null;
try
{
loadedTypes = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
Log(Properties.Resources.CouldNotLoadTypes);
Log(e);
foreach (var ex in e.LoaderExceptions)
{
Log(Properties.Resources.DllLoadException);
Log(ex.ToString());
}
}
catch (Exception e)
{
Log(Properties.Resources.CouldNotLoadTypes);
Log(e);
}
foreach (var t in (loadedTypes ?? Enumerable.Empty<Type>()))
{
try
{
//only load types that are in the right namespace, are not abstract
//and have the elementname attribute
if (IsNodeSubType(t))
{
//if we are running in revit (or any context other than NONE) use the DoNotLoadOnPlatforms attribute,
//if available, to discern whether we should load this type
if (context.Equals(Context.NONE)
|| !t.GetCustomAttributes<DoNotLoadOnPlatformsAttribute>(false)
.SelectMany(attr => attr.Values)
.Any(e => e.Contains(context)))
{
nodeModels.Add(new TypeLoadData(t));
}
}
if (IsMigration(t))
{
migrationTypes.Add(new TypeLoadData(t));
}
}
catch (Exception e)
{
Log(String.Format(Properties.Resources.FailedToLoadType, assembly.FullName, t.FullName));
Log(e);
}
}
loadedAssemblies.Add(assembly);
OnAssemblyLoaded(assembly);
}
#endregion
}
}