Skip to content

Commit

Permalink
Add netstandard2.0,2.1
Browse files Browse the repository at this point in the history
drasticactions committed Feb 22, 2024

Verified

This commit was signed with the committer’s verified signature.
mike182uk Michael Barrett
1 parent cb5b6e4 commit 10f3b89
Showing 13 changed files with 411 additions and 11 deletions.
3 changes: 3 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -19,6 +19,9 @@
<PackageVersion Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.8" />
<PackageVersion Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.8" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageVersion Include="System.Memory" Version="4.5.5" />
<PackageVersion Include="System.Memory.Data" Version="8.0.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.2" />
<PackageVersion Include="xunit" Version="2.7.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
4 changes: 2 additions & 2 deletions samples/FishyFlip.Firehose/FishyFlip.Firehose.csproj
Original file line number Diff line number Diff line change
@@ -2,9 +2,10 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFrameworks>net462;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot Condition="'$(TargetFramework)' != 'net462'">true</PublishAot>
</PropertyGroup>

<ItemGroup>
@@ -13,7 +14,6 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Sharprompt" />
<PackageReference Include="Drastic.Utilities" />
<PackageReference Include="MimeTypes">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
26 changes: 23 additions & 3 deletions samples/FishyFlip.Firehose/Program.cs
Original file line number Diff line number Diff line change
@@ -2,7 +2,6 @@
// Copyright (c) Drastic Actions. All rights reserved.
// </copyright>

using Drastic.Tools;
using FishyFlip;
using FishyFlip.Models;
using FishyFlip.Tools;
@@ -23,7 +22,7 @@

atWebProtocol.OnSubscribedRepoMessage += (sender, args) =>
{
Task.Run(() => HandleMessageAsync(args.Message)).FireAndForgetSafeAsync();
Task.Run(() => HandleMessageAsync(args.Message)).FireAndForget();
};

await atWebProtocol.StartSubscribeReposAsync();
@@ -60,7 +59,7 @@ async Task HandleMessageAsync(SubscribeRepoMessage message)
// Commit.Ops are the actions used when creating the message.
// In this case, it's a create record for the post.
// The path contains the post action and path, we need the path, so we split to get it.
var url = $"https://bsky.app/profile/{did}/post/{message.Commit.Ops![0]!.Path!.Split("/").Last()}";
var url = $"https://bsky.app/profile/{did}/post/{message.Commit.Ops![0]!.Path!.Split('/').Last()}";
Console.WriteLine($"Post URL: {url}, from {repo.Handle}");

if (post.Reply is not null)
@@ -70,4 +69,25 @@ async Task HandleMessageAsync(SubscribeRepoMessage message)
}
}
}
}

public static class TaskExtensions
{
public static void FireAndForget(this Task task, Action<Exception> errorHandler = null)
{
if (task == null)
throw new ArgumentNullException(nameof(task));

task.ContinueWith(t =>
{
if (errorHandler != null && t.IsFaulted)
errorHandler(t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);

// Avoiding warning about not awaiting the fire-and-forget task.
// However, since the method is intended to fire and forget, we don't actually await it.
#pragma warning disable CS4014
task.ConfigureAwait(false);
#pragma warning restore CS4014
}
}
1 change: 1 addition & 0 deletions src/FishyFlip.Tests/AuthorizedTests.cs
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@

using FishyFlip.Models;
using Microsoft.Extensions.Logging.Debug;
using System.Net.Http;

namespace FishyFlip.Tests;

2 changes: 1 addition & 1 deletion src/FishyFlip.Tests/FishyFlip.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>net462;net7.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

12 changes: 12 additions & 0 deletions src/FishyFlip/ATWebSocketProtocol.cs
Original file line number Diff line number Diff line change
@@ -280,6 +280,17 @@ private async Task ReceiveMessages(ClientWebSocket webSocket, CancellationToken
{
try
{
#if NETSTANDARD
var result =
await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), token);
if (result is not { MessageType: WebSocketMessageType.Binary, EndOfMessage: true })
{
continue;
}

byte[] newArray = new byte[result.Count];
Array.Copy(receiveBuffer, 0, newArray, 0, result.Count);
#else
var result =
await webSocket.ReceiveAsync(new Memory<byte>(receiveBuffer), token);
if (result is not { MessageType: WebSocketMessageType.Binary, EndOfMessage: true })
@@ -289,6 +300,7 @@ private async Task ReceiveMessages(ClientWebSocket webSocket, CancellationToken

byte[] newArray = new byte[result.Count];
Array.Copy(receiveBuffer, 0, newArray, 0, result.Count);
#endif

Task.Run(() => this.HandleMessage(newArray)).FireAndForgetSafeAsync(this.logger);
}
9 changes: 7 additions & 2 deletions src/FishyFlip/FishyFlip.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;netstandard2.1;net7.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>true</IsPackable>
@@ -16,4 +16,9 @@
<PackageReference Include="IpfsShipyard.Ipfs.Core" />
<PackageReference Include="PeterO.Cbor" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0' Or '$(TargetFramework)' == 'netstandard2.1'">
<PackageReference Include="System.Memory" />
<PackageReference Include="System.Memory.Data" />
<PackageReference Include="System.Text.Json" />
</ItemGroup>
</Project>
13 changes: 13 additions & 0 deletions src/FishyFlip/Globals.cs
Original file line number Diff line number Diff line change
@@ -22,3 +22,16 @@
global using Microsoft.IdentityModel.Tokens;
global using PeterO.Cbor;
global using ATCid = System.String;

#if NETSTANDARD
namespace System.Runtime.CompilerServices
{
#pragma warning disable SA1600 // Elements should be documented
#pragma warning disable SA1649 // File name should match first type name
internal static class IsExternalInit
{
}
#pragma warning restore SA1649 // File name should match first type name
#pragma warning restore SA1600 // Elements should be documented
}
#endif
6 changes: 5 additions & 1 deletion src/FishyFlip/Tools/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -18,7 +18,11 @@ internal static class ExceptionExtensions
/// <exception cref="ArgumentNullException">Thrown when the provided object is null.</exception>
internal static T ThrowIfNull<T>(this T? t)
{
ArgumentNullException.ThrowIfNull(t);
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}

return t;
}
}
2 changes: 1 addition & 1 deletion src/FishyFlip/Tools/HandleValidator.cs
Original file line number Diff line number Diff line change
@@ -52,7 +52,7 @@ internal static bool EnsureValidHandle(string handle, ILogger? logger = default)
return false;
}

if (l.EndsWith('-') || l.StartsWith('-'))
if (l.EndsWith("-") || l.StartsWith("-"))
{
logger?.LogError("Handle parts can not start or end with hyphens");
return false;
37 changes: 36 additions & 1 deletion src/FishyFlip/Tools/HttpClientExtensions.cs
Original file line number Diff line number Diff line change
@@ -45,7 +45,11 @@ internal static async Task<Result<TK>> Post<T, TK>(
return atError!;
}

#if NETSTANDARD
string response = await message.Content.ReadAsStringAsync();
#else
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif
if (response.IsNullOrEmpty() && message.IsSuccessStatusCode)
{
response = "{ }";
@@ -85,7 +89,11 @@ internal static async Task<Result<TK>> Post<TK>(
return atError!;
}

#if NETSTANDARD
string response = await message.Content.ReadAsStringAsync();
#else
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif
if (response.IsNullOrEmpty() && message.IsSuccessStatusCode)
{
response = "{ }";
@@ -123,7 +131,11 @@ internal static async Task<Result<TK>> Post<TK>(
return atError!;
}

#if NETSTANDARD
string response = await message.Content.ReadAsStringAsync();
#else
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif
if (response.IsNullOrEmpty() && message.IsSuccessStatusCode)
{
response = "{ }";
@@ -158,8 +170,13 @@ internal static async Task<Result<TK>> Post<TK>(
return atError!;
}

#if NETSTANDARD
var blob = await message.Content.ReadAsByteArrayAsync();
string response = await message.Content.ReadAsStringAsync();
#else
var blob = await message.Content.ReadAsByteArrayAsync(cancellationToken);
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif

logger?.LogDebug($"GET BLOB {url}: {response}");
return new Blob(blob);
@@ -191,7 +208,11 @@ internal static async Task<Result<TK>> Post<TK>(
return atError!;
}

#if NETSTANDARD
using var stream = await message.Content.ReadAsStreamAsync();
#else
await using var stream = await message.Content.ReadAsStreamAsync(cancellationToken);
#endif
await CarDecoder.DecodeCarAsync(stream, progress);
return new Success();
}
@@ -226,11 +247,17 @@ internal static async Task<Result<TK>> Post<TK>(
}

var fileDownload = Path.Combine(filePath, StringExtensions.GenerateValidFilename(fileName));
await using (var content = File.Create(fileDownload))
#if NETSTANDARD
using var content = File.Create(fileDownload);
using var stream = await message.Content.ReadAsStreamAsync();
await stream.CopyToAsync(content);
#else
await using (FileStream content = File.Create(fileDownload))
{
await using var stream = await message.Content.ReadAsStreamAsync(cancellationToken);
await stream.CopyToAsync(content, cancellationToken);
}
#endif

return new Success();
}
@@ -262,7 +289,11 @@ internal static async Task<Result<TK>> Post<TK>(
return atError!;
}

#if NETSTANDARD
string response = await message.Content.ReadAsStringAsync();
#else
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif
if (response.IsNullOrEmpty() && message.IsSuccessStatusCode)
{
response = "{ }";
@@ -274,7 +305,11 @@ internal static async Task<Result<TK>> Post<TK>(

private static async Task<ATError> CreateError(HttpResponseMessage message, JsonSerializerOptions options, CancellationToken cancellationToken, ILogger? logger = default)
{
#if NETSTANDARD
string response = await message.Content.ReadAsStringAsync();
#else
string response = await message.Content.ReadAsStringAsync(cancellationToken);
#endif
ATError atError;
ErrorDetail? detail = default;
if (string.IsNullOrEmpty(response))
42 changes: 42 additions & 0 deletions src/FishyFlip/Tools/StreamExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// <copyright file="StreamExtensions.cs" company="Drastic Actions">
// Copyright (c) Drastic Actions. All rights reserved.
// </copyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FishyFlip.Tools;

/// <summary>
/// Stream Extensions.
/// </summary>
public static class StreamExtensions
{
#if NETSTANDARD
/// <summary>
/// Asynchronously reads exactly the specified number of bytes from the stream into the buffer.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="buffer">The buffer to store the read bytes.</param>
/// <param name="offset">The zero-based byte offset in the buffer at which to begin storing the data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count)
{
int totalRead = 0;
while (totalRead < count)
{
int bytesRead = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead);
if (bytesRead == 0)
{
throw new EndOfStreamException("End of stream reached before fulfilling read request.");
}

totalRead += bytesRead;
}
}
#endif
}
Loading

0 comments on commit 10f3b89

Please sign in to comment.