Skip to content

Commit

Permalink
Target .NET 7 and System.Text.Json
Browse files Browse the repository at this point in the history
1. Do not use Newtonsoft.Json any more.
2. Test for message validation.
  • Loading branch information
anfomin committed Dec 22, 2022
1 parent 5809451 commit d19591f
Show file tree
Hide file tree
Showing 17 changed files with 179 additions and 54 deletions.
2 changes: 1 addition & 1 deletion RaygunCore.AspNetCore/RaygunCore.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<AssemblyName>RaygunCore.AspNetCore</AssemblyName>
<Description>Raygun provider for ASP.NET Core.</Description>
<PackageTags>raygun;core;netcore;aspnetcore;aspnetcoremvc</PackageTags>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
74 changes: 74 additions & 0 deletions RaygunCore.Test/RaygunClientTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
using RaygunCore.Messages;
using RaygunCore.Services;

namespace RaygunCore.Test;

public class RaygunClientTest
{
[Fact]
public async Task Index()
{
string serverUrl = "http://localhost:8888/";
var server = new HttpListener();
server.Prefixes.Add(serverUrl);
server.Start();
var resultTask = server.GetContextAsync().ContinueWith(task =>
{
var context = task.Result;
string content;
using (var sr = new StreamReader(context.Request.InputStream, Encoding.UTF8))
content = sr.ReadToEnd();
context.Response.ContentLength64 = 0;
context.Response.Close();
return (
Method: context.Request.HttpMethod,
ContentType: context.Request.ContentType,
Headers: context.Request.Headers,
Content: content
);
});

string message = "Test message";
var severity = RaygunSeverity.Critical;
var tags = new string[] { "tag1", "tag2" };
var httpClientFactory = new TestHttpClientFactory();
var raygunOptions = new RaygunOptions
{
ApiKey = "API_KEY",
ApiEndpoint = new Uri(serverUrl),
AppVersion = "1.0",
ThrowOnError = true
};
var raygunMessageBuilder = new DefaultRaygunMessageBuilder(new IRaygunMessageProvider[]
{
new MainMessageProvider(Options.Create(raygunOptions)),
new TestUserMessageProvider()
});
var raygunClient = new DefaultRaygunClient(httpClientFactory, raygunMessageBuilder, Enumerable.Empty<IRaygunValidator>(), Options.Create(raygunOptions));
await raygunClient.SendAsync(message, severity, tags);
server.Stop();

var result = await resultTask;
result.Method.Should().Be("POST");
result.Headers["X-ApiKey"].Should().Be(raygunOptions.ApiKey);
result.ContentType.Should().StartWith("application/json");
result.Content.Should().NotBeNullOrEmpty();
result.Content.Should().NotContain("\t");

var resultMessage = JsonSerializer.Deserialize<RaygunMessage>(result.Content, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
})!;
resultMessage.Details.Version.Should().Be(raygunOptions.AppVersion);
resultMessage.Details.Tags.Should().BeEquivalentTo(tags.Prepend(severity.ToString()));
resultMessage.Details.Error.Message.Should().Be(message);
resultMessage.Details.User?.Identifier.Should().Be(TestUserMessageProvider.Email);
resultMessage.Details.User?.Email.Should().Be(TestUserMessageProvider.Email);
resultMessage.Details.User?.IsAnonymous.Should().BeFalse();
}
}
22 changes: 22 additions & 0 deletions RaygunCore.Test/RaygunCore.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../RaygunCore.props" />

<PropertyGroup>
<AssemblyName>RaygunCore.Test</AssemblyName>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Using Include="FluentAssertions" />
<Using Include="Xunit" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../RaygunCore/RaygunCore.csproj" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
<PackageReference Include="FluentAssertions" Version="6.8.0" />
</ItemGroup>
</Project>
15 changes: 15 additions & 0 deletions RaygunCore.Test/TestHttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace RaygunCore.Test;

sealed class TestHttpClientFactory: IHttpClientFactory, IDisposable
{
private readonly Lazy<HttpMessageHandler> _handlerLazy = new(() => new HttpClientHandler());

public HttpClient CreateClient(string name)
=> new (_handlerLazy.Value, disposeHandler: false);

public void Dispose()
{
if (_handlerLazy.IsValueCreated)
_handlerLazy.Value.Dispose();
}
}
17 changes: 17 additions & 0 deletions RaygunCore.Test/TestUserMessageProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using RaygunCore.Messages;

namespace RaygunCore.Test;

class TestUserMessageProvider : IRaygunMessageProvider
{
public const string Email = "[email protected]";

public void Apply(RaygunMessageDetails details)
{
details.User = new(Email)
{
Email = Email,
IsAnonymous = false
};
}
}
2 changes: 1 addition & 1 deletion RaygunCore.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<RepositoryUrl>https://github.com/anfomin/rayguncore</RepositoryUrl>
<PackageProjectUrl>https://github.com/anfomin/rayguncore</PackageProjectUrl>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<VersionPrefix>2.0.0</VersionPrefix>
<VersionPrefix>2.1.0</VersionPrefix>
<VersionSuffix Condition="'$(VERSION_SUFFIX)'!=''">$(VERSION_SUFFIX)</VersionSuffix>
<NoWarn>$(NoWarn);1573;1591</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
Expand Down
16 changes: 15 additions & 1 deletion RaygunCore.sln
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
Expand All @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RaygunCore", "RaygunCore\Ra
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RaygunCore.AspNetCore", "RaygunCore.AspNetCore\RaygunCore.AspNetCore.csproj", "{FFF7285C-4EF8-4EF6-8480-6865CEB61089}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RaygunCore.Test", "RaygunCore.Test\RaygunCore.Test.csproj", "{436221A5-06B9-4508-8A2F-BD32B3ADEF48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -44,5 +46,17 @@ Global
{FFF7285C-4EF8-4EF6-8480-6865CEB61089}.Release|x64.Build.0 = Release|x64
{FFF7285C-4EF8-4EF6-8480-6865CEB61089}.Release|x86.ActiveCfg = Release|x86
{FFF7285C-4EF8-4EF6-8480-6865CEB61089}.Release|x86.Build.0 = Release|x86
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|x64.ActiveCfg = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|x64.Build.0 = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|x86.ActiveCfg = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Debug|x86.Build.0 = Debug|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|Any CPU.Build.0 = Release|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|x64.ActiveCfg = Release|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|x64.Build.0 = Release|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|x86.ActiveCfg = Release|Any CPU
{436221A5-06B9-4508-8A2F-BD32B3ADEF48}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
2 changes: 1 addition & 1 deletion RaygunCore/Messages/RaygunEnvironmentMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class RaygunEnvironmentMessage
public string? Architecture { get; set; }
public ulong? TotalVirtualMemory { get; set; }
public ulong? AvailableVirtualMemory { get; set; }
public IList<double>? DiskSpaceFree { get; set; }
public List<double>? DiskSpaceFree { get; set; }
public ulong? TotalPhysicalMemory { get; set; }
public ulong? AvailablePhysicalMemory { get; set; }
public double? UtcOffset { get; set; }
Expand Down
4 changes: 1 addition & 3 deletions RaygunCore/Messages/RaygunErrorMessage.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
using System.Collections;

namespace RaygunCore.Messages;

public class RaygunErrorMessage
{
public string? ClassName { get; set; }
public string Message { get; set; } = "";
public IDictionary? Data { get; set; }
public Dictionary<object, object?>? Data { get; set; }
public RaygunErrorMessage? InnerError { get; set; }
public RaygunErrorMessage[]? InnerErrors { get; set; }
public RaygunErrorStackTraceLineMessage[]? StackTrace { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion RaygunCore/Messages/RaygunErrorStackTraceLineMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ public class RaygunErrorStackTraceLineMessage
{
public int LineNumber { get; set; }
public string ClassName { get; set; } = "";
public string FileName { get; set; } = "";
public string MethodName { get; set; } = "";
public string? FileName { get; set; }
}
2 changes: 1 addition & 1 deletion RaygunCore/Messages/RaygunMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
public class RaygunMessage
{
public DateTime OccurredOn { get; set; } = DateTime.UtcNow;
public RaygunMessageDetails Details { get; } = new RaygunMessageDetails();
public RaygunMessageDetails Details { get; set; } = new();
}
10 changes: 5 additions & 5 deletions RaygunCore/Messages/RaygunMessageDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ public class RaygunMessageDetails
public string? MachineName { get; set; }
public string? GroupingKey { get; set; }
public string? Version { get; set; }
public RaygunClientMessage Client { get; } = new RaygunClientMessage();
public RaygunEnvironmentMessage Environment { get; } = new RaygunEnvironmentMessage();
public List<string> Tags { get; } = new List<string>();
public Dictionary<string, object> UserCustomData { get; } = new Dictionary<string, object>();
public RaygunErrorMessage Error { get; set; } = null!;
public RaygunClientMessage Client { get; set; } = new();
public RaygunEnvironmentMessage Environment { get; set; } = new();
public List<string> Tags { get; set; } = new();
public Dictionary<string, object> UserCustomData { get; set; } = new();
public RaygunErrorMessage Error { get; set; } = new();
public RaygunUserMessage? User { get; set; }
public RaygunRequestMessage? Request { get; set; }
public RaygunResponseMessage? Response { get; set; }
Expand Down
10 changes: 5 additions & 5 deletions RaygunCore/Messages/RaygunRequestMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ public class RaygunRequestMessage
public string? Url { get; set; }
public string? HttpMethod { get; set; }
public string? IPAddress { get; set; }
public IDictionary<string, object>? Headers { get; set; }
public IDictionary<string, object>? Cookies { get; set; }
public IDictionary<string, object>? QueryString { get; set; }
public IDictionary<string, object>? Form { get; set; }
public IDictionary<string, object>? Data { get; set; }
public Dictionary<string, object>? Headers { get; set; }
public Dictionary<string, object>? Cookies { get; set; }
public Dictionary<string, object>? QueryString { get; set; }
public Dictionary<string, object>? Form { get; set; }
public Dictionary<string, object>? Data { get; set; }
public string? RawData { get; set; }
}
15 changes: 7 additions & 8 deletions RaygunCore/RaygunCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@
<AssemblyName>RaygunCore</AssemblyName>
<Description>Raygun provider for .NET Core projects.</Description>
<PackageTags>raygun;core;netcore</PackageTags>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
</Project>
17 changes: 4 additions & 13 deletions RaygunCore/Services/DefaultRaygunClient.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Text;
using RaygunCore.Messages;
using System.Net.Http.Json;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using RaygunCore.Messages;

namespace RaygunCore.Services;

Expand Down Expand Up @@ -65,11 +64,9 @@ protected virtual HttpClient CreateClient()
/// <param name="message">Custom text.</param>
/// <param name="exception">The exception to deliver.</param>
protected virtual bool ShouldSend(string message, Exception? exception)
{
return (exception == null || !exception.IsSent())
=> (exception == null || !exception.IsSent())
&& exception is not RaygunException
&& _validators.All(v => v.ShouldSend(message, exception));
}

/// <summary>
/// Transmits a message to Raygun.
Expand All @@ -80,7 +77,7 @@ protected async Task TransmitMessageAsync(RaygunMessage message)
{
try
{
var result = await CreateClient().PostAsync(_options.ApiEndpoint, new JsonContent(message));
var result = await CreateClient().PostAsync(_options.ApiEndpoint, JsonContent.Create(message));
result.EnsureSuccessStatusCode();
}
catch (Exception ex)
Expand All @@ -89,10 +86,4 @@ protected async Task TransmitMessageAsync(RaygunMessage message)
throw new RaygunException(ex);
}
}

class JsonContent : StringContent
{
public JsonContent(object obj)
: base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json") { }
}
}
11 changes: 5 additions & 6 deletions RaygunCore/Services/DefaultRaygunMessageBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,12 @@ protected RaygunErrorMessage CreateErrorMessage(Exception exception)

if (exception.Data != null)
{
var data = new Dictionary<object, object?>();
message.Data = new();
foreach (object key in exception.Data.Keys)
{
if (!ExceptionExtensions.SentKey.Equals(key))
data[key] = exception.Data[key];
message.Data[key] = exception.Data[key];
}
message.Data = data;
}

if (exception is AggregateException ae && ae.InnerExceptions != null)
Expand Down Expand Up @@ -118,7 +117,7 @@ RaygunErrorStackTraceLineMessage[] BuildStackTrace(StackTrace stackTrace, bool i

lines.Add(new RaygunErrorStackTraceLineMessage
{
FileName = frame.GetFileName() ?? string.Empty,
FileName = frame.GetFileName(),
LineNumber = lineNumber,
ClassName = method.DeclaringType?.FullName ?? "(unknown)",
MethodName = GenerateMethodName(method)
Expand All @@ -138,12 +137,12 @@ string GenerateMethodName(MethodBase method)
if (method is MethodInfo && method.IsGenericMethod)
{
sb.Append("<");
sb.Append(String.Join(",", method.GetGenericArguments().Select(a => a.Name)));
sb.Append(string.Join(",", method.GetGenericArguments().Select(a => a.Name)));
sb.Append(">");
}

sb.Append("(");
sb.Append(String.Join(", ", method.GetParameters().Select(p => $"{p.ParameterType?.Name ?? "<UnknownType>"} {p.Name}")));
sb.Append(string.Join(", ", method.GetParameters().Select(p => $"{p.ParameterType?.Name ?? "<UnknownType>"} {p.Name}")));
sb.Append(")");
return sb.ToString();
}
Expand Down
Loading

0 comments on commit d19591f

Please sign in to comment.