-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
InteropComponent.razor
428 lines (373 loc) · 18.5 KB
/
InteropComponent.razor
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
@using Microsoft.JSInterop
@using BasicTestApp.InteropTest
@using System.Runtime.InteropServices
@using System.Text.Json
@using System.IO
@using static BasicTestApp.InteropTest.JSStreamReferenceInterop
@inject IJSRuntime JSRuntime
<button id="btn-interop" @onclick="InvokeInteropAsync">Invoke interop!</button>
<div>
<h1>Invocations</h1>
@foreach (var invocation in Invocations)
{
<h2>@invocation.Key</h2>
<p id="@invocation.Key">@invocation.Value</p>
}
</div>
<div>
<h1>.NET to JS calls: passing .NET object by ref, receiving .NET object by ref</h1>
@foreach (var kvp in ReceiveDotNetObjectByRefResult)
{
<h2>@(kvp.Key)Sync</h2>
<p id="@(kvp.Key)Sync">@kvp.Value</p>
}
@foreach (var kvp in ReceiveDotNetObjectByRefAsyncResult)
{
<h2>@(kvp.Key)Async</h2>
<p id="@(kvp.Key)Async">@kvp.Value</p>
}
</div>
<div>
<h1>Return values and exceptions thrown from .NET</h1>
@foreach (var returnValue in ReturnValues)
{
<h2>@returnValue.Key</h2>
<p id="@returnValue.Key">@returnValue.Value</p>
}
</div>
<div>
<h1>Exceptions thrown from JavaScript</h1>
<h2>@nameof(ExceptionFromSyncMethod)</h2>
<p id="@nameof(ExceptionFromSyncMethod)">@ExceptionFromSyncMethod?.Message</p>
<h2>@nameof(SyncExceptionFromAsyncMethod)</h2>
<p id="@nameof(SyncExceptionFromAsyncMethod)">@SyncExceptionFromAsyncMethod?.Message</p>
<h2>@nameof(AsyncExceptionFromAsyncMethod)</h2>
<p id="@nameof(AsyncExceptionFromAsyncMethod)">@AsyncExceptionFromAsyncMethod?.Message</p>
<h2>@nameof(JSObjectReferenceInvokeNonFunctionException)</h2>
<p id="@nameof(JSObjectReferenceInvokeNonFunctionException)">@JSObjectReferenceInvokeNonFunctionException?.Message</p>
</div>
@if (DoneWithInterop)
{
<p id="done-with-interop">Done with interop.</p>
}
@code {
public IDictionary<string, string> ReturnValues { get; set; } = new Dictionary<string, string>();
public IDictionary<string, string> Invocations { get; set; } = new Dictionary<string, string>();
public JSException ExceptionFromSyncMethod { get; set; }
public JSException SyncExceptionFromAsyncMethod { get; set; }
public JSException AsyncExceptionFromAsyncMethod { get; set; }
public JSException JSObjectReferenceInvokeNonFunctionException { get; set; }
public IDictionary<string, object> ReceiveDotNetObjectByRefResult { get; set; } = new Dictionary<string, object>();
public IDictionary<string, object> ReceiveDotNetObjectByRefAsyncResult { get; set; } = new Dictionary<string, object>();
public bool DoneWithInterop { get; set; }
public async Task InvokeInteropAsync()
{
var shouldSupportSyncInterop = RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"));
var testDTOTOPassByRef = new TestDTO(nonSerializedValue: 123);
var instanceMethodsTarget = new JavaScriptInterop();
var genericType = new JavaScriptInterop.GenericType<string> { Value = "Initial value" };
Console.WriteLine("Starting interop invocations.");
await JSRuntime.InvokeVoidAsync(
"jsInteropTests.invokeDotNetInteropMethodsAsync",
shouldSupportSyncInterop,
DotNetObjectReference.Create(testDTOTOPassByRef),
DotNetObjectReference.Create(instanceMethodsTarget),
DotNetObjectReference.Create(genericType));
if (shouldSupportSyncInterop)
{
InvokeInProcessInterop();
}
Console.WriteLine("Showing interop invocation results.");
var collectResults = await JSRuntime.InvokeAsync<Dictionary<string, string>>("jsInteropTests.collectInteropResults");
ReturnValues = collectResults.ToDictionary(kvp => kvp.Key, kvp => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(kvp.Value)));
var invocations = new Dictionary<string, string>();
foreach (var interopResult in JavaScriptInterop.Invocations)
{
var interopResultValue = JsonSerializer.Serialize(interopResult.Value, TestJsonSerializerOptionsProvider.Options);
invocations[interopResult.Key] = interopResultValue;
}
try
{
await JSRuntime.InvokeAsync<object>("jsInteropTests.asyncFunctionThrowsSyncException");
}
catch (JSException e)
{
SyncExceptionFromAsyncMethod = e;
}
try
{
await JSRuntime.InvokeAsync<object>("jsInteropTests.asyncFunctionThrowsAsyncException");
}
catch (JSException e)
{
AsyncExceptionFromAsyncMethod = e;
}
var passDotNetObjectByRef = new TestDTO(99999);
var passDotNetObjectByRefArg = new PassDotNetObjectByRefArgs
{
StringValue = "My string",
TestDto = DotNetObjectReference.Create(passDotNetObjectByRef),
};
var result = await JSRuntime.InvokeAsync<ReceiveDotNetObjectByRefArgs>("receiveDotNetObjectByRefAsync", passDotNetObjectByRefArg);
ReceiveDotNetObjectByRefAsyncResult["stringValueUpper"] = result.StringValueUpper;
ReceiveDotNetObjectByRefAsyncResult["testDtoNonSerializedValue"] = result.TestDtoNonSerializedValue;
ReceiveDotNetObjectByRefAsyncResult["testDto"] = result.TestDto.Value == passDotNetObjectByRef ? "Same" : "Different";
ReturnValues["returnPrimitiveAsync"] = (await JSRuntime.InvokeAsync<int>("returnPrimitiveAsync")).ToString();
ReturnValues["returnArrayAsync"] = string.Join(",", (await JSRuntime.InvokeAsync<Segment[]>("returnArrayAsync")).Select(x => x.Source).ToArray());
if (shouldSupportSyncInterop)
{
ReturnValues["returnPrimitive"] = ((IJSInProcessRuntime)JSRuntime).Invoke<int>("returnPrimitive").ToString();
ReturnValues["returnArray"] = string.Join(",", ((IJSInProcessRuntime)JSRuntime).Invoke<Segment[]>("returnArray").Select(x => x.Source).ToArray());
}
try
{
// Trigger a non-serializable WindowProxy (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// InvokeVoidAsync shouldn't serialize return values, and thus there shouldn't be any exception thrown.
await JSRuntime.InvokeVoidAsync("eval", "window");
ReturnValues["invokeVoidAsyncReturnsWithoutSerializing"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeVoidAsyncReturnsWithoutSerializing"] = $"Failure: {ex.Message}";
}
try
{
// Trigger a non-serializable WindowProxy (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// InvokeAsync should serialize return values, and thus there should be an exception thrown.
var circularStructure = await JSRuntime.InvokeAsync<object>("eval", "window");
ReturnValues["invokeAsyncThrowsSerializingCircularStructure"] = circularStructure is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeAsyncThrowsSerializingCircularStructure"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncThrowsSerializingCircularStructure"] = $"Failure: {ex.Message}";
}
try
{
var undefinedJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnUndefined");
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}
try
{
var nullJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnNull");
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = nullJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = $"Failure: {ex.Message}";
}
var jsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnJSObjectReference");
ReturnValues["jsObjectReference.identity"] = await jsObjectReference.InvokeAsync<string>("identity", "Invoked from JSObjectReference");
ReturnValues["jsObjectReference.nested.add"] = (await jsObjectReference.InvokeAsync<int>("nested.add", 2, 3)).ToString();
ReturnValues["addViaJSObjectReference"] = (await JSRuntime.InvokeAsync<int>("addViaJSObjectReference", jsObjectReference, 2, 3)).ToString();
try
{
// Fetch a non-serializable Window (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// InvokeVoidAsync shouldn't serialize return values, and thus there shouldn't be any exception thrown.
await jsObjectReference.InvokeVoidAsync("getWindow");
ReturnValues["invokeVoidAsyncReturnsWithoutSerializingInJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeVoidAsyncReturnsWithoutSerializingInJSObjectReference"] = $"Failure: {ex.Message}";
}
try
{
await jsObjectReference.InvokeAsync<object>("nonFunction");
}
catch (JSException e)
{
JSObjectReferenceInvokeNonFunctionException = e;
}
try
{
await jsObjectReference.DisposeAsync();
ReturnValues["disposeJSObjectReferenceAsync"] = "Success";
}
catch (Exception ex)
{
ReturnValues["disposeJSObjectReferenceAsync"] = $"Failure: {ex.Message}";
}
var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/testmodule.js");
ReturnValues["jsObjectReferenceModule"] = await module.InvokeAsync<string>("identity", "Returned from module!");
if (shouldSupportSyncInterop)
{
InvokeInProcessJSInterop();
}
var byteArray = new byte[] { 1, 5, 7, 15, 35, 200 };
var byteArrayWrapperObject = new ByteArrayInterop.ByteArrayWrapper()
{
StrVal = "Some String",
ByteArrayVal = byteArray,
IntVal = 100000
};
ReturnValues["roundTripByteArrayAsyncFromDotNet"] = string.Join(",", (await JSRuntime.InvokeAsync<byte[]>("roundTripByteArrayAsync", byteArray)).ToArray());
ReturnValues["roundTripByteArrayWrapperObjectAsyncFromDotNet"] = (await JSRuntime.InvokeAsync<ByteArrayInterop.ByteArrayWrapper>("roundTripByteArrayWrapperObjectAsync", byteArrayWrapperObject)).ToString();
if (shouldSupportSyncInterop)
{
ReturnValues["roundTripByteArrayFromDotNet"] = string.Join(",", ((IJSInProcessRuntime)JSRuntime).Invoke<byte[]>("roundTripByteArray", byteArray).ToArray());
ReturnValues["roundTripByteArrayWrapperObjectFromDotNet"] = ((IJSInProcessRuntime)JSRuntime).Invoke<ByteArrayInterop.ByteArrayWrapper>("roundTripByteArrayWrapperObject", byteArrayWrapperObject).ToString();
}
var dataReference = await JSRuntime.InvokeAsync<IJSStreamReference>("jsToDotNetStreamReturnValueAsync");
using var dataReferenceStream = await dataReference.OpenReadStreamAsync();
await ValidateStreamValuesAsync("jsToDotNetStreamReturnValueAsync", dataReferenceStream);
var dataWrapperReference = await JSRuntime.InvokeAsync<JSStreamReferenceWrapper>("jsToDotNetStreamWrapperObjectReturnValueAsync");
if (dataWrapperReference.StrVal != "SomeStr")
{
ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = $"StrVal did not match expected 'SomeStr', received {dataWrapperReference.StrVal}.";
}
else if (dataWrapperReference.IntVal != 5)
{
ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = $"IntVal did not match expected '5', received {dataWrapperReference.IntVal}.";
}
else
{
using var dataWrapperReferenceStream = await dataWrapperReference.JSStreamReferenceVal.OpenReadStreamAsync();
await ValidateStreamValuesAsync("jsToDotNetStreamWrapperObjectReturnValueAsync", dataWrapperReferenceStream);
}
var dotNetStreamReference = DotNetStreamReferenceInterop.GetDotNetStreamReference();
ReturnValues["dotNetToJSReceiveDotNetStreamReferenceAsync"] = await JSRuntime.InvokeAsync<string>("jsInteropTests.receiveDotNetStreamReference", dotNetStreamReference);
var dotNetStreamReferenceWrapper = DotNetStreamReferenceInterop.GetDotNetStreamWrapperReference();
ReturnValues["dotNetToJSReceiveDotNetStreamWrapperReferenceAsync"] = await JSRuntime.InvokeAsync<string>("jsInteropTests.receiveDotNetStreamWrapperReference", dotNetStreamReferenceWrapper);
Invocations = invocations;
DoneWithInterop = true;
}
private async Task ValidateStreamValuesAsync(string testName, Stream stream)
{
using var memoryStream = new System.IO.MemoryStream();
await stream.CopyToAsync(memoryStream);
var buffer = memoryStream.ToArray();
for (var i = 0; i < buffer.Length; i++)
{
var expectedValue = i % 256;
if (buffer[i] != expectedValue)
{
ReturnValues[testName] = $"Failure at index {i}.";
break;
}
}
if (buffer.Length != 100_000)
{
ReturnValues[testName] = $"Failure, got a stream of length {buffer.Length}, expected a length of 100,000.";
}
// Mark the test as successful if we haven't already set a failure above
ReturnValues.TryAdd(testName, "Success");
}
public void InvokeInProcessInterop()
{
var inProcRuntime = ((IJSInProcessRuntime)JSRuntime);
try
{
inProcRuntime.Invoke<object>("jsInteropTests.functionThrowsException");
}
catch (JSException e)
{
ExceptionFromSyncMethod = e;
}
var passDotNetObjectByRef = new TestDTO(99999);
var passDotNetObjectByRefArg = new PassDotNetObjectByRefArgs
{
StringValue = "My string",
TestDto = DotNetObjectReference.Create(passDotNetObjectByRef),
};
var result = inProcRuntime.Invoke<ReceiveDotNetObjectByRefArgs>("receiveDotNetObjectByRef", passDotNetObjectByRefArg);
ReceiveDotNetObjectByRefResult["stringValueUpper"] = result.StringValueUpper;
ReceiveDotNetObjectByRefResult["testDtoNonSerializedValue"] = result.TestDtoNonSerializedValue;
ReceiveDotNetObjectByRefResult["testDto"] = result.TestDto.Value == passDotNetObjectByRef ? "Same" : "Different";
}
public void InvokeInProcessJSInterop()
{
var inProcRuntime = ((IJSInProcessRuntime)JSRuntime);
try
{
// Fetch a non-serializable Window (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// InvokeVoid shouldn't serialize return values, and thus there shouldn't be any exception thrown.
inProcRuntime.InvokeVoid("eval", "window");
ReturnValues["invokeVoidReturnsWithoutSerializingIJSInProcessRuntime"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeVoidReturnsWithoutSerializingIJSInProcessRuntime"] = $"Failure: {ex.Message}";
}
try
{
// Trigger a non-serializable WindowProxy (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// Invoke should serialize return values, and thus there should be an exception thrown.
var circularStructure = inProcRuntime.Invoke<object>("eval", "window");
ReturnValues["invokeThrowsSerializingCircularStructure"] = circularStructure is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeThrowsSerializingCircularStructure"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeThrowsSerializingCircularStructure"] = $"Failure: {ex.Message}";
}
try
{
var undefinedJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnUndefined");
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}
try
{
var nullJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnNull");
ReturnValues["invokeThrowsNullJSObjectReference"] = nullJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeThrowsNullJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeThrowsNullJSObjectReference"] = $"Failure: {ex.Message}";
}
var jsInProcObjectReference = inProcRuntime.Invoke<IJSInProcessObjectReference>("returnJSObjectReference");
ReturnValues["jsInProcessObjectReference.identity"] = jsInProcObjectReference.Invoke<string>("identity", "Invoked from JSInProcessObjectReference");
try
{
// Fetch a non-serializable Window (https://developer.mozilla.org/en-US/docs/Web/API/Window)
// InvokeVoid shouldn't serialize return values, and thus there shouldn't be any exception thrown.
jsInProcObjectReference.InvokeVoid("getWindow");
ReturnValues["invokeVoidReturnsWithoutSerializingInIJSInProcessObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeVoidReturnsWithoutSerializingInIJSInProcessObjectReference"] = $"Failure: {ex.Message}";
}
}
public class PassDotNetObjectByRefArgs
{
public string StringValue { get; set; }
public DotNetObjectReference<TestDTO> TestDto { get; set; }
}
public class ReceiveDotNetObjectByRefArgs
{
public string StringValueUpper { get; set; }
public int TestDtoNonSerializedValue { get; set; }
public DotNetObjectReference<TestDTO> TestDto { get; set; }
}
}