db + migrations

This commit is contained in:
Aleksandr Popov
2023-06-25 17:56:30 +02:00
parent 944712df97
commit 751982beff
11 changed files with 110 additions and 172 deletions
-38
View File
@@ -1,38 +0,0 @@
using System;
using System.Text;
using NLog;
using NLog.Targets;
namespace TURN.Libraries.Core
{
public static class LoggerFactory
{
public static Logger GetLogger()
{
return LogManager.Setup().LoadConfiguration(c =>
{
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget()
{
Layout = "${date}|${level:uppercase=true}|${message:withexception=true}"
};
FileTarget fileTarget = new FileTarget()
{
FileName = Environment.GetEnvironmentVariable("LOG_FILE_PATH"),
Layout = "${date}|${level:uppercase=true}|${message:withexception=true}",
Encoding = Encoding.UTF8,
LineEnding = LineEndingMode.CRLF,
KeepFileOpen = true,
ConcurrentWrites = true,
ArchiveAboveSize = long.Parse(Environment.GetEnvironmentVariable("LOG_FILE_SIZE")),
MaxArchiveFiles = 10,
MaxArchiveDays = 365
};
_ = c.ForLogger("consoleAndFile")
.FilterMinLevel(LogLevel.Debug)
.WriteTo(consoleTarget)
.WriteTo(fileTarget);
}).GetLogger("consoleAndFile");
}
}
}
@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TURN.Libraries.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("*")]
[assembly: AssemblyProduct("TURN.Libraries.Core")]
[assembly: AssemblyCopyright("Copyright © * 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("54acf6b1-2512-47c4-877a-5b78e9001b8c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -1,57 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{54ACF6B1-2512-47C4-877A-5B78E9001B8C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TURN.Libraries.Core</RootNamespace>
<AssemblyName>TURN.Libraries.Core</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.5.2.0\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LoggerFactory.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
-4
View File
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="5.2.0" targetFramework="net48" />
</packages>
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using ChessDotNet;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TURN.Services.Chess.DBModel;
namespace TURN.Services.Chess.Controllers
{
@@ -11,6 +13,13 @@ namespace TURN.Services.Chess.Controllers
{
public const string AuthSchemes = JwtBearerDefaults.AuthenticationScheme;
private readonly ModelBaseContext _db;
public TurnController(ModelBaseContext db)
{
_db = db;
}
/// <summary>
/// Тестовый гет.
/// </summary>
@@ -19,6 +28,8 @@ namespace TURN.Services.Chess.Controllers
{
try
{
ChessGame game = new();
return Ok(param);
}
catch (Exception ex)
@@ -26,5 +37,33 @@ namespace TURN.Services.Chess.Controllers
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
/// <summary>
/// Создать игру.
/// </summary>
[HttpGet("startgame/{blackUser}/{whiteUser}")]
public ActionResult<string> StartGame(string blackUser, string whiteUser)
{
try
{
ChessGame game = new();
Game obj = new()
{
BlackUserName = blackUser,
WhiteUserName = whiteUser,
StartDate = DateTime.Now.ToString()
};
_ = _db.Add(obj);
_ = _db.SaveChanges();
return Ok($"Game {obj.GameId} started.");
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace TURN.Services.Chess.DBModel
{
public partial class Game
{
public long? GameId { get; set; }
public string? BlackUserName { get; set; }
public string? WhiteUserName { get; set; }
public string? StartDate { get; set; }
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore;
namespace TURN.Services.Chess.DBModel
{
public partial class ModelBaseContext : DbContext
{
public ModelBaseContext()
{
}
public ModelBaseContext(DbContextOptions<ModelBaseContext> options)
: base(options)
{
}
public virtual DbSet<Game> Games { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
_ = optionsBuilder.UseNpgsql("Server=localhost;Port=5432;Database=TURNChess;UserId=postgres;Password=example;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
_ = modelBuilder.Entity<Game>(entity =>
{
_ = entity.HasKey(e => e.GameId);
_ = entity.Property(e => e.GameId)
.ValueGeneratedOnAdd()
.HasColumnName("GameId");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
@@ -1,32 +0,0 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5110"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"publishAllPorts": true
}
},
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12777",
"sslPort": 0
}
}
}
+4 -2
View File
@@ -1,7 +1,9 @@
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using TURN.Services.Chess.DBModel;
namespace TURN.Services.Chess
{
@@ -16,8 +18,8 @@ namespace TURN.Services.Chess
{
jsonOptions.SerializerSettings.Converters.Add(new StringEnumConverter());
});
//_ = services.AddDbContext<ModelBaseContext>(
// options => options.UseSqlServer(Environment.GetEnvironmentVariable("DB")));
_ = services.AddDbContext<ModelBaseContext>(
options => options.UseNpgsql(Environment.GetEnvironmentVariable("DB")));
}
public void Configure(IApplicationBuilder app)
@@ -11,12 +11,23 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ChessDotNet" Version="0.12.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.31.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="5.2.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.5.0" />
@@ -24,4 +35,8 @@
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.31.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
</Project>
+3 -2
View File
@@ -9,6 +9,7 @@ services:
- LOG_FILE_PATH=/logs/log.log
- LOG_FILE_SIZE=50000000
- AUTH_API_KEY=asdasdasd
- DB=Server=postgresdb;Port=5432;Database=TURNChess;UserId=postgres;Password=example;
ports:
- 80:80
volumes:
@@ -22,11 +23,11 @@ services:
ports:
- 5432:5432
environment:
- POSTGRES_DB=TURNChese
- POSTGRES_DB=TURNChess
- POSTGRES_PASSWORD=example
- PGDATA=/var/lib/postgresql/data/pgdata
volumes:
- /d/programming/ChessData/pgdata:/var/lib/postgresql/data
- /d/programming/ChessData/db:/var/lib/postgresql/data
networks:
- app-network