Skip to content
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Text.Json;
using System.Threading.Channels;

namespace BackGroundQueueService;

class BackGroundQueue : BackgroundService
{
private Channel<Stream> _queue;

public BackGroundQueue(Channel<Stream> queue)
{
_queue = queue;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{

await foreach (var dataStream in _queue.Reader.ReadAllAsync())
{
// reset the stream to the beginning
dataStream.Position = 0;

var reader = new StreamReader(dataStream);
try
{
var Person = JsonSerializer.Deserialize<Person>(await reader.ReadToEndAsync())!;
Console.WriteLine($"{Person.Name} is {Person.Age} years and from {Person.Country}");
// you could do something else with the data
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}


return;

}
}

class Person
{
public string Name { get; set; } = String.Empty;
public int Age { get; set; }
public string Country { get; set; } = String.Empty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Threading.Channels;
using BackGroundQueueService;
var builder = WebApplication.CreateBuilder(args);
// create a channel to send data to the background queue
builder.Services.AddSingleton<Channel<Stream>>((_)=>Channel.CreateUnbounded<Stream>());

// create a background queue service
builder.Services.AddHostedService<BackGroundQueue>();
var app = builder.Build();

app.Use(async (context, next) =>
{
await next();
// read the stream from the request body
var reader = new StreamReader(context.Request.Body);

//.. you could decide to do some logging here

});

app.MapGet("/", () => "Hello World!");

// curl --request POST 'http://localhost:5256/register' --header 'Content-Type: application/json' --data-raw '{ "Name":"Samson", "Age": 23, "Country":"Nigeria" }'
app.MapPost("/register", async (Stream body, HttpRequest req, Channel<Stream> queue) =>
{
// create a rewindable stream to be able to reuse the body stream
var reusableStream = new MemoryStream();

// copy the request body to the reusable stream
await body.CopyToAsync(reusableStream);

// reset the stream to the beginning
reusableStream.Position = 0;

// send the stream to the background queue
await queue.Writer.WriteAsync(reusableStream);

// reset the stream to the beginning
reusableStream.Position = 0;

// set the response body to the reusable stream
req.Body = new MemoryStream(reusableStream.ToArray());

return "registered";
});


app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
// map the /weatherforecast endpoint to a custom action
app.MapWeatherApi();
app.Run();



public static class WeatherApi
{
public static string[] summaries =
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

public static WebApplication MapWeatherApi(this WebApplication routes)
{
routes.MapGet("/weatherforecast", GetAllWeathers);

return routes;
}
public static IResult GetAllWeathers()
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
// return a typed result
return TypedResults.Ok(forecast); ;
}
}

public record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.8" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.8" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\TypedResultApi\TypedResultApi.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Microsoft.VisualStudio.TestTools.UnitTesting;
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Http.HttpResults;

namespace Tests
{
[TestClass()]
public class WeatherApiTests
{
[TestMethod()]
public void MapWeatherApiTest()
{
var result = WeatherApi.GetAllWeathers();
// assert that the result is a typed result of type WeatherForecast[]
Assert.IsInstanceOfType(result, typeof(Ok<WeatherForecast[]>));
}

}

}

This file was deleted.