Skip to content

Commit ed96f5f

Browse files
Merge pull request #56 from Windows10CE/fix-json
Update to .NET 8 and fix float serialization
2 parents 9cc1b6a + f1deb82 commit ed96f5f

File tree

9 files changed

+52
-32
lines changed

9 files changed

+52
-32
lines changed

CSharpRepl.Tests/CSharpRepl.Tests.csproj

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,19 @@
33
<PropertyGroup>
44
<EnablePreviewFeatures>true</EnablePreviewFeatures>
55
<LangVersion>preview</LangVersion>
6-
<TargetFramework>net7.0</TargetFramework>
6+
<TargetFramework>net8.0</TargetFramework>
77
<RootNamespace>CSDiscordService.Tests</RootNamespace>
88
</PropertyGroup>
99

1010
<ItemGroup>
1111
<FrameworkReference Include="Microsoft.AspNetCore.App" />
1212
</ItemGroup>
1313
<ItemGroup>
14-
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.0-rc.2.22476.2" />
15-
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0-preview-20221003-04" />
16-
<PackageReference Include="xunit" Version="2.4.2" />
17-
<PackageReference Include="xunit.runner.reporters" Version="2.4.2" />
18-
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
14+
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" />
15+
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
16+
<PackageReference Include="xunit" Version="2.6.2" />
17+
<PackageReference Include="xunit.runner.reporters" Version="2.6.2" />
18+
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4">
1919
<PrivateAssets>all</PrivateAssets>
2020
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
2121
</PackageReference>

CSharpRepl.Tests/EvalTests.cs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,22 +69,33 @@ public EvalTests(ITestOutputHelper outputHelper)
6969
[InlineData(@"var a = ""thing""; return a;", "thing", "string")]
7070
[InlineData("Math.Pow(1,2)", 1D, "double")]
7171
[InlineData(@"Enumerable.Range(0,1).Select(a=>""@"");", null, null)]
72-
[InlineData("typeof(int)", "System.Int32, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "RuntimeType")]
72+
[InlineData("typeof(int)", "System.Int32, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "RuntimeType")]
7373
[InlineData("Assembly.GetExecutingAssembly()", true, "RuntimeAssembly")]
7474
[InlineData("TimeSpan.FromSeconds(2310293892)", "26739.12:18:12", "TimeSpan")]
75+
[InlineData("float.PositiveInfinity", "Infinity", "float")]
76+
[InlineData("List<int> l = [1, 2, 3]; l", "[1,2,3]", "List<int>")]
7577
public async Task Eval_WellFormattedCodeExecutes(string expr, object expected, string type)
7678
{
7779
var (result, statusCode) = await Execute(expr);
7880
var res = result.ReturnValue as JsonElement?;
7981
object convertedValue;
80-
if (expected is string || expected is null)
82+
if (res.Value.ValueKind == JsonValueKind.Array)
83+
{
84+
convertedValue = res.Value.GetRawText();
85+
}
86+
else if (expected is string || expected is null)
8187
{
8288
convertedValue = res?.GetString();
8389
}
8490
else if (res.Value.ValueKind == JsonValueKind.Object)
8591
{
8692
convertedValue = res.HasValue;
8793
}
94+
else if (result.ReturnTypeName == "RuntimeAssembly")
95+
{
96+
// nothing to do here, value is random for this test
97+
convertedValue = expected;
98+
}
8899
else
89100
{
90101
var value = res.Value.GetRawText();
@@ -185,8 +196,8 @@ public async Task Eval_ConsoleOutputIsCaptured(string expr, string consoleOut, o
185196
[Fact]
186197
public async Task Eval_LoadDLLThatExposesTypeOfADependency()
187198
{
188-
var expr = "#nuget CK.ActivityMonitor\nvar m = new ActivityMonitor();";
189-
var (_, statusCode) = await Execute(expr);
199+
var expr = "#nuget CK.ActivityMonitor\nvar m = new CK.Core.ActivityMonitor();";
200+
var (result, statusCode) = await Execute(expr);
190201

191202
Assert.Equal(HttpStatusCode.OK, statusCode);
192203
}

CSharpRepl/CSharpRepl.csproj

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<PropertyGroup>
44
<EnablePreviewFeatures>true</EnablePreviewFeatures>
55
<LangVersion>preview</LangVersion>
6-
<TargetFramework>net7.0</TargetFramework>
6+
<TargetFramework>net8.0</TargetFramework>
77
<OutputType>Exe</OutputType>
88
<UserSecretsId>03629088-8bb9-4faf-8162-debf93066bc4</UserSecretsId>
99
</PropertyGroup>
@@ -14,12 +14,10 @@
1414

1515
<ItemGroup>
1616
<PackageReference Include="AngouriMath" Version="1.3.0" />
17-
<PackageReference Include="ICSharpCode.Decompiler" Version="3.2.0.3856" />
18-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.5.0-1.22524.5" />
19-
<PackageReference Include="Newtonsoft.Json" Version="13.0.2-beta2" />
20-
<PackageReference Include="NuGet.Packaging" Version="6.5.0-preview.1.35" />
21-
<PackageReference Include="NuGet.Protocol" Version="6.5.0-preview.1.35" />
22-
<PackageReference Include="NuGet.Resolver" Version="6.5.0-preview.1.35" />
17+
<PackageReference Include="ICSharpCode.Decompiler" Version="8.2.0.7535" />
18+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.8.0" />
19+
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
20+
<PackageReference Include="NuGet.Resolver" Version="6.8.0" />
2321
<PackageReference Include="Seq.Extensions.Logging" Version="6.1.0" />
2422
</ItemGroup>
2523
<ItemGroup>

CSharpRepl/Eval/DisassemblyService.cs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using ICSharpCode.Decompiler.Disassembler;
33
using Microsoft.CodeAnalysis;
44
using Microsoft.CodeAnalysis.CSharp;
5-
using Mono.Cecil;
65
using Newtonsoft.Json;
76
using System;
87
using System.Collections.Generic;
@@ -15,6 +14,7 @@
1514
using System.Text;
1615
using System.Text.RegularExpressions;
1716
using System.Threading;
17+
using ICSharpCode.Decompiler.Metadata;
1818

1919
namespace CSDiscordService.Eval
2020
{
@@ -65,7 +65,7 @@ public string GetIl(string code)
6565
6666
namespace Eval
6767
{{
68-
public class Code
68+
public unsafe class Code
6969
{{
7070
public object Main()
7171
{{
@@ -75,17 +75,22 @@ public object Main()
7575
}}
7676
";
7777

78-
var opts = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview).WithKind(SourceCodeKind.Regular);
78+
var opts = CSharpParseOptions.Default
79+
.WithLanguageVersion(LanguageVersion.Preview)
80+
.WithKind(SourceCodeKind.Regular);
7981

8082
var scriptSyntaxTree = CSharpSyntaxTree.ParseText(toExecute, opts);
81-
var compOpts = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithOptimizationLevel(OptimizationLevel.Debug).WithAllowUnsafe(true).WithPlatform(Platform.AnyCpu);
83+
var compOpts = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
84+
.WithOptimizationLevel(OptimizationLevel.Debug)
85+
.WithAllowUnsafe(true)
86+
.WithPlatform(Platform.AnyCpu);
8287

83-
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString(), options: compOpts, references: References).AddSyntaxTrees(scriptSyntaxTree);
88+
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString(), options: compOpts, references: References)
89+
.AddSyntaxTrees(scriptSyntaxTree);
8490

8591
var sb = new StringBuilder();
86-
using var pdb = new MemoryStream();
8792
using var dll = new MemoryStream();
88-
var result = compilation.Emit(dll, pdb);
93+
var result = compilation.Emit(dll);
8994
if (!result.Success)
9095
{
9196
sb.AppendLine("Emit Failed");
@@ -94,19 +99,22 @@ public object Main()
9499
else
95100
{
96101
dll.Seek(0, SeekOrigin.Begin);
97-
using var module = ModuleDefinition.ReadModule(dll);
102+
using var file = new PEFile(compilation.AssemblyName!, dll);
98103
using var writer = new StringWriter(sb);
99-
module.Name = compilation.AssemblyName;
100104
var plainOutput = new PlainTextOutput(writer);
101105
var rd = new ReflectionDisassembler(plainOutput, CancellationToken.None)
102106
{
103107
DetectControlStructure = true
104108
};
105109
var ignoredMethods = new[] { ".ctor" };
106-
var methods = module.Types.SelectMany(a => a.Methods).Where(a => !ignoredMethods.Contains(a.Name));
110+
var methods = file.Metadata.MethodDefinitions.Where(a =>
111+
{
112+
var methodName = file.Metadata.GetString(file.Metadata.GetMethodDefinition(a).Name);
113+
return !ignoredMethods.Contains(methodName);
114+
});
107115
foreach (var method in methods)
108116
{
109-
rd.DisassembleMethod(method);
117+
rd.DisassembleMethod(file, method);
110118
plainOutput.WriteLine();
111119
}
112120
}

CSharpRepl/Eval/NugetDirectiveProcessor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public async Task PreProcess(string directive, ScriptExecutionContext context, A
3232
{
3333
var actionLogger = new NugetLogger(logger);
3434
var nugetDirective = NugetPreProcessorDirective.Parse(directive);
35-
string frameworkName = Assembly.GetEntryAssembly()!.GetCustomAttributes(true)
35+
string frameworkName = typeof(NugetDirectiveProcessor).Assembly.GetCustomAttributes(true)
3636
.OfType<System.Runtime.Versioning.TargetFrameworkAttribute>()
3737
.Select(x => x.FrameworkName)
3838
.FirstOrDefault()!;

CSharpRepl/Eval/ResultModels/EvalResult.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ public override string ToString()
8787
IncludeFields = true,
8888
PropertyNameCaseInsensitive = true,
8989
ReferenceHandler = ReferenceHandler.IgnoreCycles,
90+
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
9091
Converters = {
9192
new TypeJsonConverter(), new TypeInfoJsonConverter(),
9293
new RuntimeTypeHandleJsonConverter(), new TypeJsonConverterFactory(), new AssemblyJsonConverter(),

CSharpRepl/Infrastructure/JsonFormatters/TypeJsonConverter.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer
122122

123123
public class AssemblyJsonConverterFactory : JsonConverterFactory
124124
{
125-
public override bool CanConvert(Type typeToConvert) => typeToConvert == Type.GetType("System.RuntimeAssembly");
125+
public override bool CanConvert(Type typeToConvert) => typeToConvert == Type.GetType("System.Reflection.RuntimeAssembly");
126126
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
127127
{
128128
return new RuntimeAssemblyJsonConverter();

CSharpRepl/Startup.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ public void ConfigureServices(IServiceCollection services)
3636
IncludeFields = true,
3737
PropertyNameCaseInsensitive = true,
3838
ReferenceHandler = ReferenceHandler.IgnoreCycles,
39+
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
3940
Converters = {
4041
new TypeJsonConverter(), new TypeInfoJsonConverter(),
4142
new RuntimeTypeHandleJsonConverter(), new TypeJsonConverterFactory(), new AssemblyJsonConverter(),
@@ -57,6 +58,7 @@ public void ConfigureServices(IServiceCollection services)
5758
o.JsonSerializerOptions.IncludeFields = true;
5859
o.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
5960
o.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
61+
o.JsonSerializerOptions.NumberHandling |= JsonNumberHandling.AllowNamedFloatingPointLiterals;
6062
o.JsonSerializerOptions.Converters.Add(new TypeJsonConverter());
6163
o.JsonSerializerOptions.Converters.Add(new TypeInfoJsonConverter());
6264
o.JsonSerializerOptions.Converters.Add(new RuntimeTypeHandleJsonConverter());

Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0 as dotnet-build
1+
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 as dotnet-build
22
ARG TARGETPLATFORM
33
ARG BUILDPLATFORM
44
WORKDIR /src
@@ -10,7 +10,7 @@ RUN dotnet build --configuration Release --no-restore
1010
#RUN dotnet test --configuration Release CSharpRepl.Tests/CSharpRepl.Tests.csproj --no-build --no-restore
1111
RUN dotnet publish --configuration Release CSharpRepl/CSharpRepl.csproj --no-build --no-restore -o /app
1212

13-
FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/aspnet:7.0
13+
FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/aspnet:8.0
1414
ARG TARGETPLATFORM
1515
ARG BUILDPLATFORM
1616
WORKDIR /app

0 commit comments

Comments
 (0)