Skip to content
This repository was archived by the owner on Dec 3, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions Microsoft.DotNet.Interactive.Rendering.Tests/DictionaryTypes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.DotNet.Interactive.Rendering.Tests
{
/// <summary>
/// Implements <see cref="IDictionary{,}" />, but not <see cref="IDictionary"/>.
/// </summary>
internal class GenericDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> _values = new Dictionary<TKey, TValue>();

public TValue this[TKey key] { get => ((IDictionary<TKey, TValue>)_values)[key]; set => ((IDictionary<TKey, TValue>)_values)[key] = value; }

public ICollection<TKey> Keys => ((IDictionary<TKey, TValue>)_values).Keys;

public ICollection<TValue> Values => ((IDictionary<TKey, TValue>)_values).Values;

public int Count => ((IDictionary<TKey, TValue>)_values).Count;

public bool IsReadOnly => ((IDictionary<TKey, TValue>)_values).IsReadOnly;

public void Add(TKey key, TValue value)
{
((IDictionary<TKey, TValue>)_values).Add(key, value);
}

public void Add(KeyValuePair<TKey, TValue> item)
{
((IDictionary<TKey, TValue>)_values).Add(item);
}

public void Clear()
{
((IDictionary<TKey, TValue>)_values).Clear();
}

public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ((IDictionary<TKey, TValue>)_values).Contains(item);
}

public bool ContainsKey(TKey key)
{
return ((IDictionary<TKey, TValue>)_values).ContainsKey(key);
}

public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((IDictionary<TKey, TValue>)_values).CopyTo(array, arrayIndex);
}

public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return ((IDictionary<TKey, TValue>)_values).GetEnumerator();
}

public bool Remove(TKey key)
{
return ((IDictionary<TKey, TValue>)_values).Remove(key);
}

public bool Remove(KeyValuePair<TKey, TValue> item)
{
return ((IDictionary<TKey, TValue>)_values).Remove(item);
}

public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
return ((IDictionary<TKey, TValue>)_values).TryGetValue(key, out value);
}

IEnumerator IEnumerable.GetEnumerator()
{
return ((IDictionary<TKey, TValue>)_values).GetEnumerator();
}
}

/// <summary>
/// Implements <see cref="IDictionary" />, but not <see cref="IDictionary{,}"/>.
/// </summary>
internal class NonGenericDictionary : IDictionary
{
private Dictionary<object, object> _values = new Dictionary<object, object>();

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();
}
}
}
30 changes: 26 additions & 4 deletions Microsoft.DotNet.Interactive.Rendering.Tests/HtmlFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<string, EntityId> instance = new GenericDictionary<string, EntityId>
{
{ "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(
"<table><thead><tr><th><i>key</i></th><th>TypeName</th><th>Id</th></tr></thead><tbody><tr><td>first</td><td>entity one</td><td>123</td></tr><tr><td>second</td><td>entity two</td><td>456</td></tr></tbody></table>");
}

[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<string, EntityId>
IDictionary instance = new NonGenericDictionary
{
{ "first", new EntityId("entity one", "123") },
{ "second", new EntityId("entity two", "456") }
Expand Down Expand Up @@ -305,4 +327,4 @@ public void ReadOnlyMemory_of_int_is_formatted_like_a_int_array()
}
}
}
}
}
81 changes: 42 additions & 39 deletions Microsoft.DotNet.Interactive.Rendering/HtmlFormatter{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -77,66 +78,68 @@ private static HtmlFormatter<T> CreateForObject(bool includeInternals)

private static HtmlFormatter<T> CreateForSequence(bool includeInternals)
{
IDestructurer destructurer = null;

if (typeof(T).IsConstructedGenericType)
Type valueType = null;
Func<T, IEnumerable> getKeys = null;
Func<T, IEnumerable> 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<T>((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<string> getIndex;

switch (instance)
if (getKeys != null)
{
var keys = new List<string>();
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<IHtmlContent>();
List<IHtmlContent> headers = null;

foreach (var item in sequence)
foreach (var item in getValues(instance))
{
var dictionary = (destructurer ?? Destructurer.Create(item.GetType())).Destructure(item);

Expand Down