Skip to content

Commit

Permalink
Consolidate formatting for http request and response types.
Browse files Browse the repository at this point in the history
Also switch to attribute-based formatter registration.
  • Loading branch information
shyamnamboodiripad committed Jun 16, 2023
1 parent 41eda18 commit 9a7dd19
Show file tree
Hide file tree
Showing 17 changed files with 183 additions and 208 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ Microsoft.DotNet.Interactive.HttpRequest
public HttpRequest Request { get;}
public System.Int32 StatusCode { get;}
public System.String Version { get;}
public static class HttpResponseMessageFormattingExtensions
public static System.Void RegisterFormatters()
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.CSharp;
using Microsoft.DotNet.Interactive.Events;
using Microsoft.DotNet.Interactive.HttpRequest;
using Microsoft.DotNet.Interactive.Tests.Utility;
using Xunit;

Expand All @@ -25,6 +26,8 @@ public AspNetCoreTests()

var loadTask = new AspNetCoreKernelExtension().OnLoadAsync(_kernel);
Assert.Same(Task.CompletedTask, loadTask);

HttpResponseMessageFormattingExtensions.RegisterFormatters();
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<ProjectReference Include="..\dotnet-interactive\dotnet-interactive.csproj" />
<ProjectReference Include="..\interface-generator\interface-generator.csproj" />
<ProjectReference Include="..\Microsoft.DotNet.Interactive.AspNetCore\Microsoft.DotNet.Interactive.AspNetCore.csproj" />
<ProjectReference Include="..\Microsoft.DotNet.Interactive.HttpRequest\Microsoft.DotNet.Interactive.HttpRequest.csproj" />
<ProjectReference Include="..\Microsoft.DotNet.Interactive.Tests\Microsoft.DotNet.Interactive.Tests.csproj" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Microsoft.DotNet.Interactive.AspNetCore;

public static class AspNetCoreCSharpKernelExtensions
{
private static readonly Assembly[] _references =
private static readonly Assembly[] _references =
{
typeof(Host).Assembly, // Microsoft.Extensions.Hosting
typeof(WebHost).Assembly, // Microsoft.AspNetCore
Expand All @@ -37,7 +37,7 @@ public static class AspNetCoreCSharpKernelExtensions
typeof(IEndpointRouteBuilder).Namespace, // Microsoft.AspNetCore.Routing
typeof(EndpointRouteBuilderExtensions).Namespace, // Microsoft.AspNetCore.Builder
typeof(InteractiveEndpointRouteBuilderExtensions).Namespace, // Microsoft.DotNet.Interactive.AspNetCore
typeof(HttpClient).Namespace, // System.Net.Htttp
typeof(HttpClient).Namespace, // System.Net.Http
};

public static CSharpKernel UseAspNetCore(this CSharpKernel kernel)
Expand All @@ -48,7 +48,7 @@ public static CSharpKernel UseAspNetCore(this CSharpKernel kernel)
{
Handler = CommandHandler.Create(async () =>
{
if (interactiveHost is {})
if (interactiveHost is { })
{
return;
}
Expand Down
22 changes: 2 additions & 20 deletions src/Microsoft.DotNet.Interactive.Formatting/HtmlFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Numerics;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using Microsoft.AspNetCore.Html;
using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags;

Expand Down Expand Up @@ -44,7 +42,7 @@ internal static ITypeFormatter GetDefaultFormatterForAnyEnumerable(Type type) =>
FormattersForAnyEnumerable.GetOrCreateFormatterForType(type);

internal static void FormatAndStyleAsPlainText(
object value,
object value,
FormatContext context)
{
context.RequireDefaultStyles();
Expand Down Expand Up @@ -160,7 +158,7 @@ type.Namespace is not null &&
var typeLookupName =
genericTypeDefinition.FullName.ToLower().Replace("+",".").Replace("`","-");
PocketView view =
PocketView view =
span(a[href: $"https://docs.microsoft.com/dotnet/api/{typeLookupName}?view=net-7.0"](
text));
view.WriteTo(context);
Expand Down Expand Up @@ -314,22 +312,6 @@ type.Namespace is not null &&
view.WriteTo(context);
return true;
}),

new HtmlFormatter<HttpResponseMessage>((value, context) =>
{
// Prevent SynchronizationContext-induced deadlocks given the following sync-over-async code.
ExecutionContext.SuppressFlow();
try
{
value.FormatAsHtml(context).Wait();
}
finally
{
ExecutionContext.RestoreFlow();
}
return true;
})
};
Expand Down

This file was deleted.

29 changes: 5 additions & 24 deletions src/Microsoft.DotNet.Interactive.Formatting/PlainTextFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Numerics;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;

using Microsoft.AspNetCore.Html;
using Microsoft.DotNet.Interactive.CSharp;
Expand All @@ -38,7 +36,7 @@ internal static FormatDelegate<T> CreateFormatDelegate<T>(MemberInfo[] forMember
{
var accessors = forMembers.GetMemberAccessors<T>().ToArray();

if (Formatter<T>.TypeIsValueTuple ||
if (Formatter<T>.TypeIsValueTuple ||
Formatter<T>.TypeIsTuple)
{
return FormatTuple;
Expand Down Expand Up @@ -195,9 +193,9 @@ bool FormatTuple(T target, FormatContext context)
return true;
}),

new PlainTextFormatter<ReadOnlyMemory<char>>((memory, context) =>
new PlainTextFormatter<ReadOnlyMemory<char>>((memory, context) =>
{
context.Writer.Write(memory.Span.ToString());
context.Writer.Write(memory.Span.ToString());
return true;
}),

Expand Down Expand Up @@ -236,7 +234,7 @@ bool FormatTuple(T target, FormatContext context)
var array = toArray.Invoke(null, new[] { obj });
array.FormatTo(context, PlainTextFormatter.MimeType);
return true;
}),

Expand Down Expand Up @@ -273,23 +271,6 @@ bool FormatTuple(T target, FormatContext context)
return true;
}),

new PlainTextFormatter<HttpResponseMessage>((value, context) =>
{
// Formatter.Register() doesn't support async formatters yet.
// Prevent SynchronizationContext-induced deadlocks given the following sync-over-async code.
ExecutionContext.SuppressFlow();
try
{
value.FormatAsPlainText(context).Wait();
}
finally
{
ExecutionContext.RestoreFlow();
}
return true;
}),

// Fallback for any object
new PlainTextFormatter<object>((obj, context) =>
{
Expand All @@ -304,7 +285,7 @@ bool FormatTuple(T target, FormatContext context)
})
};

private static string IndentAtNewLines(this string s, FormatContext context) =>
private static string IndentAtNewLines(this string s, FormatContext context) =>
Regex.Replace(s, @"^\s+", new string(' ', (context.Depth + 1) * NumberOfSpacesToIndent), RegexOptions.Multiline);

internal static void WriteIndent(FormatContext context, string bonus = " ")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using Microsoft.DotNet.Interactive.Formatting;

namespace Microsoft.DotNet.Interactive.HttpRequest;

internal sealed class HttpResponseFormatterSource : ITypeFormatterSource
{
IEnumerable<ITypeFormatter> ITypeFormatterSource.CreateTypeFormatters()
{
yield return new HttpResponseHtmlFormatter();
yield return new HttpResponsePlainTextFormatter();
}

private sealed class HttpResponseHtmlFormatter : TypeFormatter<HttpResponse>
{
public override string MimeType => HtmlFormatter.MimeType;

public override bool Format(HttpResponse value, FormatContext context)
{
value.FormatAsHtml(context);
return true;
}
}

private sealed class HttpResponsePlainTextFormatter : TypeFormatter<HttpResponse>
{
public override string MimeType => PlainTextFormatter.MimeType;

public override bool Format(HttpResponse value, FormatContext context)
{
value.FormatAsPlainText(context);
return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,15 @@ internal static class HttpResponseFormattingExtensions
font-weight: 700;
}}");

internal static void FormatAsHtml(this HttpResponse response, FormatContext context)
internal static void FormatAsHtml(this HttpResponse? response, FormatContext context)
{
if (response is null)
{
PocketView result = PocketViewTags.pre("null");
result.WriteTo(context);
return;
}

dynamic? requestDiv;
if (response.Request is { } request)
{
Expand Down Expand Up @@ -147,8 +154,14 @@ private static dynamic HeaderTable(Dictionary<string, string[]> headers, Diction
return headerTable;
}

internal static void FormatAsPlainText(this HttpResponse response, FormatContext context)
internal static void FormatAsPlainText(this HttpResponse? response, FormatContext context)
{
if (response is null)
{
context.Writer.WriteLine("null");
return;
}

if (response.Request is { } request)
{
context.Writer.WriteLine($"Request Method: {request.Method}");
Expand Down
Loading

0 comments on commit 9a7dd19

Please sign in to comment.