-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericPlatform.cs
More file actions
77 lines (65 loc) · 2.89 KB
/
GenericPlatform.cs
File metadata and controls
77 lines (65 loc) · 2.89 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
using JetBrains.Annotations;
using PostSharp.Patterns.Model;
using PostSharp.Patterns.Threading;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Automation
{
[Freezable]
public class GenericPlatform
{
[Reference] public GenericHost Host = new GenericHost();
[Pure]
private Assembly _caller() => Assembly.GetCallingAssembly();
[Pure]
private bool InvalidNamespace([Required] Assembly assembly, [Required] string @namespace) =>
assembly.GetTypes().All(type => type.Namespace != @namespace);
[Pure]
public INativeClass GetNativeClass([Required] string @namespace, [Required] string className) =>
this.Create(_caller(), @namespace, className);
[Pure]
private INativeClass Create([Required] Assembly assembly, [Required] string @namespace, [Required] string className)
{
if (this.InvalidNamespace(assembly, @namespace))
this.Crash($"[Generic Platform]: Namespace not be located: {@namespace} in assembly: {assembly.FullName}");
// Platform looks like Win32NT for Windows.
string platformNamespace = $"{@namespace}.{Environment.OSVersion.Platform.ToString()}";
// Check for any implementations of this platform.
if (this.InvalidNamespace(assembly, platformNamespace))
this.Crash($"[Generic Platform]: {Environment.OSVersion.Platform.ToString()} was not found at {@namespace} in assembly: {assembly.FullName}");
// Native implementations currently require usage of the same class name but can exist under multiple platform namespaces.
try
{
var native = assembly.GetType($"{platformNamespace}.{className}");
var instance = (INativeClass)Activator.CreateInstance(native);
return instance;
}
catch (Exception ex)
{
this.Crash($"Could not create an instance of a native platform class called {className} --- {ex.Message}");
return null;
}
}
[Pure, ContractAnnotation("=> halt")]
public void Crash(string reason = "Unexpected behavior.")
{
Log.Fatal(reason);
this.DebugHook();
// ReSharper disable once InconsistentNaming - 128 (0x80) indicates no need to wait for child processes
const int ERROR_WAIT_NO_CHILDREN = 128;
Environment.Exit(ERROR_WAIT_NO_CHILDREN);
}
[Pure, Conditional("DEBUG")]
private void DebugHook()
{
if (Debugger.IsAttached) Debugger.Break();
}
}
}