From 0046da889eefe9fe4a0b1bcb7dd51b3d9ab807d0 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Mon, 28 Oct 2019 16:05:37 -0700 Subject: [PATCH] properly format non-generic `IDictionary` --- .../DictionaryTypes.cs | 139 ++++++++++++++++++ .../HtmlFormatterTests.cs | 30 +++- .../HtmlFormatter{T}.cs | 81 +++++----- 3 files changed, 207 insertions(+), 43 deletions(-) create mode 100644 Microsoft.DotNet.Interactive.Rendering.Tests/DictionaryTypes.cs diff --git a/Microsoft.DotNet.Interactive.Rendering.Tests/DictionaryTypes.cs b/Microsoft.DotNet.Interactive.Rendering.Tests/DictionaryTypes.cs new file mode 100644 index 000000000..1614affa8 --- /dev/null +++ b/Microsoft.DotNet.Interactive.Rendering.Tests/DictionaryTypes.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.DotNet.Interactive.Rendering.Tests +{ + /// + /// Implements , but not . + /// + internal class GenericDictionary : IDictionary + { + private Dictionary _values = new Dictionary(); + + public TValue this[TKey key] { get => ((IDictionary)_values)[key]; set => ((IDictionary)_values)[key] = value; } + + public ICollection Keys => ((IDictionary)_values).Keys; + + public ICollection Values => ((IDictionary)_values).Values; + + public int Count => ((IDictionary)_values).Count; + + public bool IsReadOnly => ((IDictionary)_values).IsReadOnly; + + public void Add(TKey key, TValue value) + { + ((IDictionary)_values).Add(key, value); + } + + public void Add(KeyValuePair item) + { + ((IDictionary)_values).Add(item); + } + + public void Clear() + { + ((IDictionary)_values).Clear(); + } + + public bool Contains(KeyValuePair item) + { + return ((IDictionary)_values).Contains(item); + } + + public bool ContainsKey(TKey key) + { + return ((IDictionary)_values).ContainsKey(key); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + ((IDictionary)_values).CopyTo(array, arrayIndex); + } + + public IEnumerator> GetEnumerator() + { + return ((IDictionary)_values).GetEnumerator(); + } + + public bool Remove(TKey key) + { + return ((IDictionary)_values).Remove(key); + } + + public bool Remove(KeyValuePair item) + { + return ((IDictionary)_values).Remove(item); + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + return ((IDictionary)_values).TryGetValue(key, out value); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IDictionary)_values).GetEnumerator(); + } + } + + /// + /// Implements , but not . + /// + internal class NonGenericDictionary : IDictionary + { + private Dictionary _values = new Dictionary(); + + public object this[object key] { get => ((IDictionary)_values)[key]; set => ((IDictionary)_values)[key] = value; } + + public bool IsFixedSize => ((IDictionary)_values).IsFixedSize; + + public bool IsReadOnly => ((IDictionary)_values).IsReadOnly; + + public ICollection Keys => ((IDictionary)_values).Keys; + + public ICollection Values => ((IDictionary)_values).Values; + + public int Count => ((IDictionary)_values).Count; + + public bool IsSynchronized => ((IDictionary)_values).IsSynchronized; + + public object SyncRoot => ((IDictionary)_values).SyncRoot; + + public void Add(object key, object value) + { + ((IDictionary)_values).Add(key, value); + } + + public void Clear() + { + ((IDictionary)_values).Clear(); + } + + public bool Contains(object key) + { + return ((IDictionary)_values).Contains(key); + } + + public void CopyTo(Array array, int index) + { + ((IDictionary)_values).CopyTo(array, index); + } + + public IDictionaryEnumerator GetEnumerator() + { + return ((IDictionary)_values).GetEnumerator(); + } + + public void Remove(object key) + { + ((IDictionary)_values).Remove(key); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IDictionary)_values).GetEnumerator(); + } + } +} diff --git a/Microsoft.DotNet.Interactive.Rendering.Tests/HtmlFormatterTests.cs b/Microsoft.DotNet.Interactive.Rendering.Tests/HtmlFormatterTests.cs index fe48e6ea0..1a8086b65 100644 --- a/Microsoft.DotNet.Interactive.Rendering.Tests/HtmlFormatterTests.cs +++ b/Microsoft.DotNet.Interactive.Rendering.Tests/HtmlFormatterTests.cs @@ -2,11 +2,12 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.IO; -using FluentAssertions; using System.Linq; +using FluentAssertions; using Xunit; namespace Microsoft.DotNet.Interactive.Rendering.Tests @@ -226,11 +227,32 @@ public void It_formats_sequences_as_tables_with_an_index_on_the_y_axis() } [Fact] - public void It_formats_dictionaries_as_tables_with_the_key_on_the_y_axis() + public void It_formats_generic_dictionaries_that_arent_non_generic_as_tables_with_the_key_on_the_y_axis() + { + var writer = new StringWriter(); + + IDictionary instance = new GenericDictionary + { + { "first", new EntityId("entity one", "123") }, + { "second", new EntityId("entity two", "456") } + }; + + var formatter = HtmlFormatter.Create(instance.GetType()); + + formatter.Format(instance, writer); + + writer.ToString() + .Should() + .Be( + "
keyTypeNameId
firstentity one123
secondentity two456
"); + } + + [Fact] + public void It_formats_non_generic_dictionaries_that_arent_generic_as_tables_with_the_key_on_the_y_axis() { var writer = new StringWriter(); - var instance = new Dictionary + IDictionary instance = new NonGenericDictionary { { "first", new EntityId("entity one", "123") }, { "second", new EntityId("entity two", "456") } @@ -305,4 +327,4 @@ public void ReadOnlyMemory_of_int_is_formatted_like_a_int_array() } } } -} \ No newline at end of file +} diff --git a/Microsoft.DotNet.Interactive.Rendering/HtmlFormatter{T}.cs b/Microsoft.DotNet.Interactive.Rendering/HtmlFormatter{T}.cs index eeb1bcb21..82203ffcf 100644 --- a/Microsoft.DotNet.Interactive.Rendering/HtmlFormatter{T}.cs +++ b/Microsoft.DotNet.Interactive.Rendering/HtmlFormatter{T}.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.ComponentModel; using System.IO; using System.Linq; using System.Text.Encodings.Web; @@ -77,66 +78,68 @@ private static HtmlFormatter CreateForObject(bool includeInternals) private static HtmlFormatter CreateForSequence(bool includeInternals) { - IDestructurer destructurer = null; - - if (typeof(T).IsConstructedGenericType) + Type valueType = null; + Func getKeys = null; + Func getValues = instance => (IEnumerable)instance; + + var dictionaryGenericType = typeof(T).GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); + var dictionaryObjectType = typeof(T).GetInterfaces() + .FirstOrDefault(i => i == typeof(IDictionary)); + var enumerableGenericType = typeof(T).GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); + + if (dictionaryGenericType != null || dictionaryObjectType != null) { - var dictionaryType = typeof(T).GetInterfaces() - .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); + var keysProperty = typeof(T).GetProperty("Keys"); + getKeys = instance => (IEnumerable)keysProperty.GetValue(instance, null); - if (dictionaryType != null) - { - var itemType = dictionaryType.GenericTypeArguments.ElementAt(1); - destructurer = Destructurer.Create(itemType); - } + var valuesProperty = typeof(T).GetProperty("Values"); + getValues = instance => (IEnumerable)valuesProperty.GetValue(instance, null); - if (destructurer == null) + if (dictionaryGenericType != null) { - var ienumerableType = typeof(T).GetInterfaces() - .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); - - if (ienumerableType != null) - { - var itemType = ienumerableType.GenericTypeArguments.Single(); - - destructurer = Destructurer.Create(itemType); - } + valueType = typeof(T).GenericTypeArguments[1]; } } + else if (enumerableGenericType != null) + { + valueType = typeof(T).GenericTypeArguments.Single(); + } + + var destructurer = valueType != null + ? Destructurer.Create(valueType) + : null; return new HtmlFormatter((instance, writer) => { var index = 0; - IEnumerable sequence = instance switch { - IDictionary d => d.Values, - IEnumerable s => s, - _ => throw new ArgumentException($"{instance.GetType()} is not IEnumerable") - }; - IHtmlContent indexHeader = null; Func getIndex; - switch (instance) + if (getKeys != null) + { + var keys = new List(); + foreach (var key in getKeys(instance)) + { + keys.Add(key.ToString()); + } + + getIndex = () => keys[index]; + indexHeader = th(i("key")); + } + else { - case IDictionary dict: - var keys = new string[dict.Keys.Count]; - dict.Keys.CopyTo(keys, 0); - getIndex = () => keys[index]; - indexHeader = th(i("key")); - break; - - default: - getIndex = () => index.ToString(); - indexHeader = th(i("index")); - break; + getIndex = () => index.ToString(); + indexHeader = th(i("index")); } var rows = new List(); List headers = null; - foreach (var item in sequence) + foreach (var item in getValues(instance)) { var dictionary = (destructurer ?? Destructurer.Create(item.GetType())).Destructure(item);