From 006ecf0d9c6a8fd57cf8c649c0362ebf4baec63b Mon Sep 17 00:00:00 2001 From: Jan-Willem Spuij Date: Mon, 6 Apr 2020 22:17:08 +0200 Subject: [PATCH] Fix for #97. --- src/WebWindow.Blazor/DesktopJSRuntime.cs | 4 +- .../ElementReferenceJsonConverter.cs | 52 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/WebWindow.Blazor/SharedSource/ElementReferenceJsonConverter.cs diff --git a/src/WebWindow.Blazor/DesktopJSRuntime.cs b/src/WebWindow.Blazor/DesktopJSRuntime.cs index b2dc81e..b642f0d 100644 --- a/src/WebWindow.Blazor/DesktopJSRuntime.cs +++ b/src/WebWindow.Blazor/DesktopJSRuntime.cs @@ -1,4 +1,5 @@ -using Microsoft.JSInterop; +using Microsoft.AspNetCore.Components; +using Microsoft.JSInterop; using Microsoft.JSInterop.Infrastructure; using System; using System.Collections.Generic; @@ -16,6 +17,7 @@ internal class DesktopJSRuntime : JSRuntime public DesktopJSRuntime(IPC ipc) { _ipc = ipc ?? throw new ArgumentNullException(nameof(ipc)); + JsonSerializerOptions.Converters.Add(new ElementReferenceJsonConverter()); } protected override void BeginInvokeJS(long asyncHandle, string identifier, string argsJson) diff --git a/src/WebWindow.Blazor/SharedSource/ElementReferenceJsonConverter.cs b/src/WebWindow.Blazor/SharedSource/ElementReferenceJsonConverter.cs new file mode 100644 index 0000000..7daa517 --- /dev/null +++ b/src/WebWindow.Blazor/SharedSource/ElementReferenceJsonConverter.cs @@ -0,0 +1,52 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components +{ + internal sealed class ElementReferenceJsonConverter : JsonConverter + { + private static readonly JsonEncodedText IdProperty = JsonEncodedText.Encode("__internalId"); + + public override ElementReference Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string id = null; + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType == JsonTokenType.PropertyName) + { + if (reader.ValueTextEquals(IdProperty.EncodedUtf8Bytes)) + { + reader.Read(); + id = reader.GetString(); + } + else + { + throw new JsonException($"Unexpected JSON property '{reader.GetString()}'."); + } + } + else + { + throw new JsonException($"Unexpected JSON Token {reader.TokenType}."); + } + } + + if (id is null) + { + throw new JsonException("__internalId is required."); + } + + return new ElementReference(id); + } + + public override void Write(Utf8JsonWriter writer, ElementReference value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString(IdProperty, value.Id); + writer.WriteEndObject(); + } + } +} \ No newline at end of file