Core - Add Net Core DevTools

- Add specific Net Core DevTools generated code
- Improve xml doc generation for both Net 4.x and Net Core/Net 5
This commit is contained in:
Alex Maitland
2021-01-06 15:27:51 +10:00
parent 6e881eeafc
commit dcf5b43dc4
10 changed files with 31009 additions and 153 deletions
@@ -0,0 +1,125 @@
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Text.Json;
using CefSharp.DevTools.Audits;
using CefSharp.DevTools.Browser;
using CefSharp.DevTools.CSS;
using CefSharp.Internals.Json;
using Xunit;
namespace CefSharp.Test.DevTools
{
public class JsonEnumConverterFacts
{
[Fact]
public void CanConvertEnumToJsonString()
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
};
options.Converters.Add(new JsonEnumConverterFactory());
var expected = "\"clipboardSanitizedWrite\"";
var actual = JsonSerializer.Serialize(PermissionType.ClipboardSanitizedWrite, options);
Assert.Equal(expected, actual);
}
[Fact]
public void CanConvertEnumArrayToJsonString()
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
};
options.Converters.Add(new JsonEnumConverterFactory());
var expected = "[\"user-agent\",\"regular\"]";
var actual = JsonSerializer.Serialize(new StyleSheetOrigin[] { StyleSheetOrigin.UserAgent, StyleSheetOrigin.Regular }, options);
Assert.Equal(expected, actual);
}
[Fact]
public void CanConvertNullableEnumToJsonStringNull()
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
};
options.Converters.Add(new JsonEnumConverterFactory());
var model = new MixedContentIssueDetails
{
InsecureURL = "Testing",
ResourceType = null
};
var expected = "{\"resolutionStatus\":\"MixedContentBlocked\",\"insecureURL\":\"Testing\"}";
var actual = JsonSerializer.Serialize(model, options);
Assert.Equal(expected, actual);
}
[Fact]
public void CanConvertNullableEnumToJsonStringNotNull()
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
};
options.Converters.Add(new JsonEnumConverterFactory());
var model = new MixedContentIssueDetails
{
InsecureURL = "Testing",
ResourceType = MixedContentResourceType.CSPReport
};
var expected = "{\"resourceType\":\"CSPReport\",\"resolutionStatus\":\"MixedContentBlocked\",\"insecureURL\":\"Testing\"}";
var actual = JsonSerializer.Serialize(model, options);
Assert.Equal(expected, actual);
}
[Fact]
public void CanSerializeDeserializeEnumJson()
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
};
options.Converters.Add(new JsonEnumConverterFactory());
var expected = new MixedContentIssueDetails
{
InsecureURL = "http://testing.domain/index.html",
Frame = new AffectedFrame
{
FrameId = "123"
},
ResourceType = MixedContentResourceType.CSPReport
};
var serialize = JsonSerializer.Serialize(expected, options);
var actual = JsonSerializer.Deserialize<MixedContentIssueDetails>(serialize, options);
Assert.Equal(expected.InsecureURL, actual.InsecureURL);
Assert.Equal(expected.ResourceType, actual.ResourceType);
Assert.Equal(expected.Frame.FrameId, actual.Frame.FrameId);
}
}
}
+5
View File
@@ -26,6 +26,10 @@
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<!-- Don't include items from the "bin" and "obj" folders used by the .NET Framework projects. -->
<EmbeddedResource Remove="Internals\Wcf\**" />
@@ -37,6 +41,7 @@
</ItemGroup>
<ItemGroup>
<Compile Remove="DevTools\DevToolsClient.Generated.cs" />
<Compile Remove="Internals\Partial\ChromiumWebBrowser.Partial.cs" />
</ItemGroup>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+15
View File
@@ -12,6 +12,20 @@ namespace CefSharp.DevTools
{
public abstract class DevToolsDomainBase
{
#if NETCOREAPP
protected string EnumToString(Enum val)
{
return Internals.Json.JsonEnumConverterFactory.ConvertEnumToString(val);
}
protected IEnumerable<string> EnumToString(PermissionType[] values)
{
foreach (var val in values)
{
yield return Internals.Json.JsonEnumConverterFactory.ConvertEnumToString(val);
}
}
#else
protected string EnumToString(Enum val)
{
var memInfo = val.GetType().GetMember(val.ToString());
@@ -30,6 +44,7 @@ namespace CefSharp.DevTools
yield return dataMemberAttribute.Value;
}
}
#endif
protected string ToBase64String(byte[] bytes)
{
+100 -3
View File
@@ -10,10 +10,41 @@ using System.Runtime.Serialization;
namespace CefSharp.DevTools
{
/// <summary>
/// Common Base class for DevTools Domain Model classes
/// </summary>
[DataContract]
public abstract class DevToolsDomainEntityBase
{
public static object StringToEnum(Type enumType, string input)
#if NETCOREAPP
internal static string EnumToString(Enum e)
{
var memberInfo = e.GetType().GetMember(e.ToString()).FirstOrDefault();
var enumMemberAttribute = (System.Text.Json.Serialization.JsonPropertyNameAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(System.Text.Json.Serialization.JsonPropertyNameAttribute), false);
return enumMemberAttribute.Name;
}
internal static string EnumToString(Array enumArray)
{
var returnValue = "[";
foreach (var e in enumArray)
{
var memberInfo = e.GetType().GetMember(e.ToString()).FirstOrDefault();
var enumMemberAttribute = (System.Text.Json.Serialization.JsonPropertyNameAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(System.Text.Json.Serialization.JsonPropertyNameAttribute), false);
returnValue += enumMemberAttribute.Name + ",";
}
returnValue += returnValue.Substring(0, returnValue.Length - 1) + "]";
return returnValue;
}
#else
internal static object StringToEnum(Type enumType, string input)
{
if (enumType.IsArray)
{
@@ -66,7 +97,7 @@ namespace CefSharp.DevTools
return (Enum.GetValues(enumType).GetValue(0));
}
public static string EnumToString(Enum e)
internal static string EnumToString(Enum e)
{
var memberInfo = e.GetType().GetMember(e.ToString()).FirstOrDefault();
@@ -75,7 +106,7 @@ namespace CefSharp.DevTools
return enumMemberAttribute.Value;
}
public static string EnumToString(Array enumArray)
internal static string EnumToString(Array enumArray)
{
var returnValue = "[";
@@ -92,7 +123,72 @@ namespace CefSharp.DevTools
return returnValue;
}
#endif
#if NETCOREAPP
public IDictionary<string, object> ToDictionary()
{
var dict = new Dictionary<string, object>();
var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in properties)
{
var propertyAttribute = (System.Text.Json.Serialization.JsonPropertyNameAttribute)Attribute.GetCustomAttribute(prop, typeof(System.Text.Json.Serialization.JsonPropertyNameAttribute), false);
//Only add members that have JsonPropertyNameAttribute
if (propertyAttribute == null)
{
continue;
}
var propertyName = propertyAttribute.Name;
var propertyRequired = Attribute.IsDefined(prop, typeof(System.Diagnostics.CodeAnalysis.DisallowNullAttribute));
var propertyValue = prop.GetValue(this);
if (propertyRequired && propertyValue == null)
{
throw new DevToolsClientException(prop.Name + " is required");
}
//Not required and value null, don't add to dictionary
if (propertyValue == null)
{
continue;
}
var propertyValueType = propertyValue.GetType();
if (typeof(DevToolsDomainEntityBase).IsAssignableFrom(propertyValueType))
{
propertyValue = ((DevToolsDomainEntityBase)(propertyValue)).ToDictionary();
}
else if (propertyValueType.IsEnum)
{
propertyValue = EnumToString((Enum)propertyValue);
}
else if(propertyValueType.IsGenericType)
{
var nullableType = Nullable.GetUnderlyingType(propertyValueType);
if(nullableType != null && nullableType.IsEnum)
{
propertyValue = EnumToString((Enum)propertyValue);
}
}
else if(propertyValueType.IsArray && propertyValueType.GetElementType().IsEnum)
{
propertyValue = EnumToString((Array)propertyValue);
}
dict.Add(propertyName, propertyValue);
}
return dict;
}
#else
public IDictionary<string, object> ToDictionary()
{
var dict = new Dictionary<string, object>();
@@ -136,5 +232,6 @@ namespace CefSharp.DevTools
return dict;
}
#endif
}
}
@@ -32,12 +32,26 @@ namespace CefSharp.DevTools
{
if (Success)
{
#if NETCOREAPP
var options = new System.Text.Json.JsonSerializerOptions
{
//AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
//PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
};
options.Converters.Add(new Internals.Json.JsonEnumConverterFactory());
return System.Text.Json.JsonSerializer.Deserialize<T>(ResponseAsJsonString, options);
#else
var bytes = Encoding.UTF8.GetBytes(ResponseAsJsonString);
using (var ms = new MemoryStream(bytes))
{
var dcs = new DataContractJsonSerializer(typeof(T));
return (T)dcs.ReadObject(ms);
}
#endif
}
throw new DevToolsClientException(ResponseAsJsonString);
@@ -0,0 +1,52 @@
// Copyright © 2021 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CefSharp.Internals.Json
{
/// <summary>
/// System.Text.Json Enum Converter for the DevToolsClient
/// Only handles enums as strings and converts from .Net naming
/// to the naming convention used by DevTools protocol
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <remarks>
/// There aren't any Type constraints on T currently, we just rely on the
/// <see cref="JsonEnumConverterFactory"/> to only use this for
/// Enum and Nullable Enum
/// </remarks>
public class JsonEnumConverter<T> : JsonConverter<T>
{
/// <inheritdoc/>
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var nullableType = Nullable.GetUnderlyingType(typeToConvert);
var val = reader.GetString();
if (nullableType == null)
{
return (T)JsonEnumConverterFactory.ConvertStringToEnum(val, typeToConvert);
}
if(string.IsNullOrEmpty(val))
{
return default;
}
return (T)JsonEnumConverterFactory.ConvertStringToEnum(val, nullableType);
}
/// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
//Not called when the Nullable enum value is null so we don't need to perform any sort of null checking
var str = JsonEnumConverterFactory.ConvertEnumToString(value);
writer.WriteStringValue(str);
}
}
}
@@ -0,0 +1,74 @@
// Copyright © 2021 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CefSharp.Internals.Json
{
/// <summary>
/// DevTools Json Enum Converter Factory
/// </summary>
public class JsonEnumConverterFactory : JsonConverterFactory
{
/// <inheritdoc/>
public override bool CanConvert(Type typeToConvert)
{
if(typeToConvert.IsEnum)
{
return true;
}
var nullType = Nullable.GetUnderlyingType(typeToConvert);
return nullType?.IsEnum ?? false;
}
/// <inheritdoc/>
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var converter = (JsonConverter)Activator.CreateInstance(
typeof(JsonEnumConverter<>).MakeGenericType(typeToConvert),
BindingFlags.Instance | BindingFlags.Public,
binder: null,
args: null,
culture: null);
return converter;
}
public static object ConvertStringToEnum(string val, Type typeToConvert)
{
foreach (var name in Enum.GetNames(typeToConvert))
{
var attribute = typeToConvert.GetField(name)
.GetCustomAttributes(false)
.OfType<JsonPropertyNameAttribute>()
.Single();
if (attribute.Name == val)
{
return Enum.Parse(typeToConvert, name);
}
}
throw new JsonException("Unable to convert Enum");
}
public static string ConvertEnumToString(object value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
var attribute = type.GetField(name)
.GetCustomAttributes(false)
.OfType<JsonPropertyNameAttribute>()
.Single();
return attribute.Name;
}
}
}
@@ -14,7 +14,11 @@
<dependencies>
<group targetFramework=".NETCoreApp3.1">
<dependency id="chromiumembeddedframework.runtime" version="[$RedistVersion$]" include="Runtime,Native,Build" />
<dependency id="System.Text.Json" version="5.0.0" />
</group>
<group targetFramework=".NETCoreApp5.0">
<dependency id="chromiumembeddedframework.runtime" version="[$RedistVersion$]" include="Runtime,Native,Build" />
</group>
</dependencies>
</metadata>
<files>