forked from pauldotknopf/JavaScriptViewEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVroomJsEngine.cs
More file actions
99 lines (79 loc) · 2.6 KB
/
VroomJsEngine.cs
File metadata and controls
99 lines (79 loc) · 2.6 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
using System;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using VroomJs;
namespace JavaScriptViewEngine
{
public class VroomJsEngine : IJsEngine
{
private static readonly Lazy<JsEngine> JsEngine = new Lazy<JsEngine>(() => new JsEngine());
private readonly JsContext _context;
private readonly object _lock = new object();
private bool _disposed = false;
public VroomJsEngine()
{
try
{
_context = JsEngine.Value.CreateContext();
}
catch (Exception ex)
{
throw new Exception("V8 engine context couldn't be created.", ex);
}
_context.Execute("");
}
public object CallFunction(string function, params object[] args)
{
VerifyNotDisposed();
var code = $"{function}({string.Join(", ", args.Select(JsonConvert.SerializeObject))})";
return _context.Execute(code);
}
public T CallFunction<T>(string function, params object[] args)
{
VerifyNotDisposed();
return (T)CallFunction(function, args);
}
public void Execute(string code)
{
VerifyNotDisposed();
if (string.IsNullOrEmpty(code))
throw new ArgumentNullException(nameof(code));
_context.Execute(code);
}
public void ExecuteFile(string path, Encoding encoding = null)
{
VerifyNotDisposed();
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
var code = Utils.GetFileTextContent(path, encoding);
Execute(code);
}
public void ExecuteResource(string resourceName, Type type)
{
if (string.IsNullOrWhiteSpace(resourceName))
throw new ArgumentException(nameof(resourceName) + " is empty.");
if (type == null)
throw new ArgumentNullException(nameof(type) + " is null");
var code = Utils.GetResourceAsString(resourceName, type);
Execute(code);
}
protected void VerifyNotDisposed()
{
if (_disposed)
throw new ObjectDisposedException(ToString());
}
public void Dispose()
{
if (!_disposed)
{
lock(_lock)
{
if (_disposed) return;
_disposed = true;
}
_context.Dispose();
}
}
}
}