mediatr, api, refit

This commit is contained in:
Michele 2020-11-07 23:37:08 +00:00
parent cdabe27b0b
commit dbc2a6d35e
13 changed files with 177 additions and 70 deletions

11
.vscode/launch.json vendored
View File

@ -35,6 +35,17 @@
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": "Identity.API",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build identity",
"program": "${workspaceFolder}/Identity/bin/Debug/netcoreapp3.1/WebApi.dll",
"args": [],
"cwd": "${workspaceFolder}/Identity",
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",

17
.vscode/tasks.json vendored
View File

@ -1,6 +1,23 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build identity",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Identity/WebApi.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "build sledgemapper",

View File

@ -1,32 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/WebApi.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

View File

@ -1,17 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/WebApi.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}

BIN
Identity/LocalDatabase.db Normal file

Binary file not shown.

View File

@ -0,0 +1,23 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Sledgemapper.Api.Handlers;
using Sledgemapper.Shared.Entities;
using System.Threading.Tasks;
namespace Sledgemapper.Api.Controllers
{
[Route("map")]
public class MapController : ControllerBase
{
private readonly IMediator _mediator;
public MapController(IMediator mediator) { _mediator = mediator; }
[HttpPost]
[ActionName("tile")]
public async Task Post(string sessionName, Tile tile)
{
await _mediator.Publish(new NewTileNotification(sessionName, tile));
}
}
}

View File

@ -0,0 +1,64 @@
using MediatR;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR;
using SignalRChat.Hubs;
using Sledgemapper.Api.Data;
using Sledgemapper.Clients;
using Sledgemapper.Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Sledgemapper.Api.Handlers
{
public class NewTileNotification: INotification
{
public double Timestamp { get; private set; }
public Tile Tile { get; private set; }
public string SessionName { get; private set; }
public NewTileNotification(string sessionName, Tile tile)
{
Tile = tile;
Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
SessionName = sessionName;
}
}
public class SendNewTileMessage : INotificationHandler<NewTileNotification>
{
private readonly IHubContext<SledgemapperHub, ISledgemapperClient> _hub;
public SendNewTileMessage(IHubContext<SledgemapperHub, ISledgemapperClient> hub) => _hub = hub;
public async Task Handle(NewTileNotification notification, CancellationToken cancellationToken)
{
await _hub.Clients.Groups(notification.SessionName).NewTile(notification.Tile);
}
}
public class SaveNewTile : INotificationHandler<NewTileNotification>
{
private readonly MyDbContext _dbcontext;
public SaveNewTile(MyDbContext dbcontext) => _dbcontext = dbcontext;
public async Task Handle(NewTileNotification notification, CancellationToken cancellationToken)
{
var jsonString = JsonSerializer.Serialize<Tile>(notification.Tile);
_dbcontext.MapLogs.Add(new Sledgemapper.Api.Models.MapLog
{
Operation = "N",
SessionName = notification.SessionName,
Type = "T",
Timestamp = notification.Timestamp,
Object = jsonString
});
await _dbcontext.SaveChangesAsync();
}
}
}

Binary file not shown.

View File

@ -22,7 +22,7 @@ namespace SignalRChat
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
@ -32,19 +32,20 @@ namespace SignalRChat
{
services.AddRazorPages();
services.AddSignalR();
services.AddMediatR(typeof(Startup));
services.AddDbContext<MyDbContext>(options => options.UseSqlite("Data Source=sledgemapper.db"));
// services.AddEntityFrameworkSqlite().AddDbContext<MyDbContext>();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
services.AddMediatR(typeof(Startup));
services.AddDbContext<MyDbContext>(options => options.UseSqlite("Data Source=sledgemapper.db"));
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
// services.AddEntityFrameworkSqlite().AddDbContext<MyDbContext>();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
}
@ -69,10 +70,10 @@ namespace SignalRChat
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseEndpoints(endpoints =>
{

16
Sledgemapper/IMapApi.cs Normal file
View File

@ -0,0 +1,16 @@
using Refit;
using Sledgemapper.Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sledgemapper
{
public interface IMapApi
{
[Post("/map/tile")]
Task NewTile([Body] Tile tile, string sessionName);
}
}

BIN
Sledgemapper/MyDatabase.db Normal file

Binary file not shown.

View File

@ -14,6 +14,8 @@ using System.Linq;
using System;
using System.Collections.Concurrent;
using Sledgemapper.Shared.Entities;
using Refit;
using System.Net.Http;
namespace Sledgemapper
{
@ -40,6 +42,7 @@ namespace Sledgemapper
private SpriteFont font;
private Dictionary<string, SpriteFont> _fonts;
private SessionData _sessionData;
private IMapApi _api;
public Sledgemapper()
{
@ -65,6 +68,23 @@ namespace Sledgemapper
// .WithUrl("http://hub.michelescandura.com:5000/SledgemapperHub")
.Build();
var httpClientHandler = new HttpClientHandler();
//if (myConfigurationService.VerifySslCertificate == false)
//{
httpClientHandler.ServerCertificateCustomValidationCallback =
(message, certificate, chain, sslPolicyErrors) => true;
//}
_api = RestService.For<IMapApi>(
new HttpClient(httpClientHandler)
{
BaseAddress = new Uri ("http://localhost:5000")
}
);
connection.On<SessionData>("UpdateMap", (map) =>
{
_sessionData.Map = map.Map;
@ -920,20 +940,23 @@ namespace Sledgemapper
{
var newTile = new Tile { X = _selectedTile.X, Y = _selectedTile.Y, ID = tileId, Rotation = (tile.Rotation + 1) % 4 };
_sessionData.Map.TryAdd(newTile.ToString(), newTile);
connection?.InvokeAsync("NewTile", _session, newTile);
_api.NewTile(newTile, _session);
//connection?.InvokeAsync("NewTile", _session, newTile);
}
else
{
var newTile = new Tile { X = _selectedTile.X, Y = _selectedTile.Y, ID = tileId };
_sessionData.Map.TryAdd(newTile.ToString(), newTile);
connection?.InvokeAsync("NewTile", _session, newTile);
_api.NewTile(newTile, _session);
// connection?.InvokeAsync("NewTile", _session, newTile);
}
}
else
{
var newTile = new Tile { X = _selectedTile.X, Y = _selectedTile.Y, ID = tileId };
_sessionData.Map.TryAdd(newTile.ToString(), newTile);
connection?.InvokeAsync("NewTile", _session, newTile);
_api.NewTile(newTile, _session);
// connection?.InvokeAsync("NewTile", _session, newTile);
}
}

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
@ -42,6 +42,7 @@
</PackageReference>
<PackageReference Include="Myra" Version="1.0.2.211" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Refit.HttpClientFactory" Version="5.2.1" />
</ItemGroup>
<ItemGroup>