forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssemblyUtils.cs
More file actions
249 lines (223 loc) · 7.96 KB
/
AssemblyUtils.cs
File metadata and controls
249 lines (223 loc) · 7.96 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
#if SILVERLIGHT
#endif
using System.Threading;
using ServiceStack.Common.Support;
namespace ServiceStack.Text
{
/// <summary>
/// Utils to load types
/// </summary>
public static class AssemblyUtils
{
private const string FileUri = "file:///";
private const string DllExt = "dll";
private const string ExeExt = "dll";
private const char UriSeperator = '/';
private static Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
#if !XBOX
/// <summary>
/// Find the type from the name supplied
/// </summary>
/// <param name="typeName">[typeName] or [typeName, assemblyName]</param>
/// <returns></returns>
public static Type FindType(string typeName)
{
Type type = null;
if (TypeCache.TryGetValue(typeName, out type)) return type;
#if !SILVERLIGHT
type = Type.GetType(typeName);
#endif
if (type == null)
{
var typeDef = new AssemblyTypeDefinition(typeName);
type = !string.IsNullOrEmpty(typeDef.AssemblyName)
? FindType(typeDef.TypeName, typeDef.AssemblyName)
: FindTypeFromLoadedAssemblies(typeDef.TypeName);
}
Dictionary<string, Type> snapshot, newCache;
do
{
snapshot = TypeCache;
newCache = new Dictionary<string, Type>(TypeCache);
newCache[typeName] = type;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TypeCache, newCache, snapshot), snapshot));
return type;
}
#endif
#if !XBOX
/// <summary>
/// The top-most interface of the given type, if any.
/// </summary>
public static Type MainInterface<T>()
{
var t = typeof(T);
#if NETFX_CORE
if (t.GetTypeInfo().BaseType == typeof(object)) {
// on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order.
var interfaceType = t.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(i => !t.GetTypeInfo().ImplementedInterfaces.Any(i2 => i2.GetTypeInfo().ImplementedInterfaces.Contains(i)));
if (interfaceType != null) return interfaceType;
}
#else
if (t.BaseType == typeof(object)) {
// on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order.
var interfaceType = t.GetInterfaces().FirstOrDefault(i => !t.GetInterfaces().Any(i2 => i2.GetInterfaces().Contains(i)));
if (interfaceType != null) return interfaceType;
}
#endif
return t; // not safe to use interface, as it might be a superclass's one.
}
/// <summary>
/// Find type if it exists
/// </summary>
/// <param name="typeName"></param>
/// <param name="assemblyName"></param>
/// <returns>The type if it exists</returns>
public static Type FindType(string typeName, string assemblyName)
{
var type = FindTypeFromLoadedAssemblies(typeName);
if (type != null)
{
return type;
}
#if !NETFX_CORE
var binPath = GetAssemblyBinPath(Assembly.GetExecutingAssembly());
Assembly assembly = null;
var assemblyDllPath = binPath + String.Format("{0}.{1}", assemblyName, DllExt);
if (File.Exists(assemblyDllPath))
{
assembly = LoadAssembly(assemblyDllPath);
}
var assemblyExePath = binPath + String.Format("{0}.{1}", assemblyName, ExeExt);
if (File.Exists(assemblyExePath))
{
assembly = LoadAssembly(assemblyExePath);
}
return assembly != null ? assembly.GetType(typeName) : null;
#else
return null;
#endif
}
#endif
#if NETFX_CORE
private sealed class AppDomain
{
public static AppDomain CurrentDomain { get; private set; }
public static Assembly[] cacheObj = null;
static AppDomain()
{
CurrentDomain = new AppDomain();
}
public Assembly[] GetAssemblies()
{
return cacheObj ?? GetAssemblyListAsync().Result.ToArray();
}
private async System.Threading.Tasks.Task<IEnumerable<Assembly>> GetAssemblyListAsync()
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
List<Assembly> assemblies = new List<Assembly>();
foreach (Windows.Storage.StorageFile file in await folder.GetFilesAsync())
{
if (file.FileType == ".dll" || file.FileType == ".exe")
{
try
{
var filename = file.Name.Substring(0, file.Name.Length - file.FileType.Length);
AssemblyName name = new AssemblyName() { Name = filename };
Assembly asm = Assembly.Load(name);
assemblies.Add(asm);
}
catch (Exception)
{
// Invalid WinRT assembly!
}
}
}
cacheObj = assemblies.ToArray();
return cacheObj;
}
}
#endif
#if !XBOX
public static Type FindTypeFromLoadedAssemblies(string typeName)
{
#if SILVERLIGHT4
var assemblies = ((dynamic) AppDomain.CurrentDomain).GetAssemblies() as Assembly[];
#else
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
#endif
foreach (var assembly in assemblies)
{
var type = assembly.GetType(typeName);
if (type != null)
{
return type;
}
}
return null;
}
#endif
#if !SILVERLIGHT
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.LoadFrom(assemblyPath);
}
#elif NETFX_CORE
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.Load(new AssemblyName(assemblyPath));
}
#elif WINDOWS_PHONE
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.LoadFrom(assemblyPath);
}
#else
private static Assembly LoadAssembly(string assemblyPath)
{
var sri = System.Windows.Application.GetResourceStream(new Uri(assemblyPath, UriKind.Relative));
var myPart = new System.Windows.AssemblyPart();
var assembly = myPart.Load(sri.Stream);
return assembly;
}
#endif
#if !XBOX
public static string GetAssemblyBinPath(Assembly assembly)
{
#if WINDOWS_PHONE
var codeBase = assembly.GetName().CodeBase;
#elif NETFX_CORE
var codeBase = assembly.GetName().FullName;
#else
var codeBase = assembly.CodeBase;
#endif
var binPathPos = codeBase.LastIndexOf(UriSeperator);
var assemblyPath = codeBase.Substring(0, binPathPos + 1);
if (assemblyPath.StartsWith(FileUri, StringComparison.OrdinalIgnoreCase))
{
assemblyPath = assemblyPath.Remove(0, FileUri.Length);
}
return assemblyPath;
}
#endif
#if !SILVERLIGHT
static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+", RegexOptions.Compiled);
#else
static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+");
#endif
public static string ToTypeString(this Type type)
{
return versionRegEx.Replace(type.AssemblyQualifiedName, "");
}
public static string WriteType(Type type)
{
return type.ToTypeString();
}
}
}