Commit 8e330617 authored by doc. Ing. Jaroslav Porubän PhD.'s avatar doc. Ing. Jaroslav Porubän PhD.
Browse files

Upravy pre rok 2020, task 5, 6

parent df62e05b
...@@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NPuzzleConsole", "NPuzzleCo ...@@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NPuzzleConsole", "NPuzzleCo
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NPuzzleTest", "NPuzzleTest\NPuzzleTest.csproj", "{B11AE1C1-3E0D-49C5-B597-B376FE2B259C}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NPuzzleTest", "NPuzzleTest\NPuzzleTest.csproj", "{B11AE1C1-3E0D-49C5-B597-B376FE2B259C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NPuzzleWeb", "NPuzzleWeb\NPuzzleWeb.csproj", "{0336981B-9C07-4BE7-A410-A303AB752E32}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -27,6 +29,10 @@ Global ...@@ -27,6 +29,10 @@ Global
{B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Debug|Any CPU.Build.0 = Debug|Any CPU {B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Release|Any CPU.ActiveCfg = Release|Any CPU {B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Release|Any CPU.Build.0 = Release|Any CPU {B11AE1C1-3E0D-49C5-B597-B376FE2B259C}.Release|Any CPU.Build.0 = Release|Any CPU
{0336981B-9C07-4BE7-A410-A303AB752E32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0336981B-9C07-4BE7-A410-A303AB752E32}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0336981B-9C07-4BE7-A410-A303AB752E32}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0336981B-9C07-4BE7-A410-A303AB752E32}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
......
...@@ -9,7 +9,8 @@ namespace NPuzzle.ConsoleUI ...@@ -9,7 +9,8 @@ namespace NPuzzle.ConsoleUI
{ {
private readonly Field field; private readonly Field field;
private readonly IScoreService scoreService = new ScoreServiceFile(); //private readonly IScoreService scoreService = new ScoreServiceFile();
private readonly IScoreService scoreService = new ScoreServiceEF();
public ConsoleUI(Field field) public ConsoleUI(Field field)
{ {
......
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NPuzzle.Service;
namespace NPuzzleCore.Migrations
{
[DbContext(typeof(NPuzzleDbContext))]
[Migration("20200410180215_Mig1")]
partial class Mig1
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("NPuzzle.Entity.Score", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Player")
.HasColumnType("nvarchar(max)");
b.Property<int>("Points")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Scores");
});
#pragma warning restore 612, 618
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
namespace NPuzzleCore.Migrations
{
public partial class Mig1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Scores",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Player = table.Column<string>(nullable: true),
Points = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Scores", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Scores");
}
}
}
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NPuzzle.Service;
namespace NPuzzleCore.Migrations
{
[DbContext(typeof(NPuzzleDbContext))]
partial class NPuzzleContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("NPuzzle.Entity.Score", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Player")
.HasColumnType("nvarchar(max)");
b.Property<int>("Points")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Scores");
});
#pragma warning restore 612, 618
}
}
}
...@@ -4,4 +4,12 @@ ...@@ -4,4 +4,12 @@
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project> </Project>
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using NPuzzle.Entity;
namespace NPuzzle.Service
{
public class NPuzzleDbContext : DbContext
{
public DbSet<Score> Scores { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=NPuzzle;Trusted_Connection=True;");
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NPuzzle.Entity;
namespace NPuzzle.Service
{
public class ScoreServiceEF : IScoreService
{
public void AddScore(Score score)
{
using (var context = new NPuzzleDbContext())
{
context.Scores.Add(score);
context.SaveChanges();
}
}
public IList<Score> GetTopScores()
{
using (var context = new NPuzzleDbContext())
{
return (from s in context.Scores
orderby s.Points
descending
select s).Take(5).ToList();
}
}
public void ClearScores()
{
using (var context = new NPuzzleDbContext())
{
context.Database.ExecuteSqlCommand("DELETE FROM Scores");
}
}
}
}
...@@ -14,14 +14,16 @@ namespace NPuzzle.Service ...@@ -14,14 +14,16 @@ namespace NPuzzle.Service
public void AddScore(Score score) public void AddScore(Score score)
{ {
GetTopScores();
scores.Add(score); scores.Add(score);
SaveScore(); SaveScores();
} }
public IList<Score> GetTopScores() public IList<Score> GetTopScores()
{ {
LoadScore(); LoadScores();
return (from s in scores orderby s.Points return (from s in scores orderby s.Points
descending select s).Take(3).ToList(); descending select s).Take(3).ToList();
...@@ -36,7 +38,7 @@ namespace NPuzzle.Service ...@@ -36,7 +38,7 @@ namespace NPuzzle.Service
} }
private void SaveScore() private void SaveScores()
{ {
using (var fs = File.OpenWrite(FileName)) using (var fs = File.OpenWrite(FileName))
{ {
...@@ -45,7 +47,7 @@ namespace NPuzzle.Service ...@@ -45,7 +47,7 @@ namespace NPuzzle.Service
} }
} }
private void LoadScore() private void LoadScores()
{ {
if (File.Exists(FileName)) if (File.Exists(FileName))
{ {
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPuzzle.Entity;
using NPuzzle.Service;
namespace NPuzzleWeb.APIControllers
{
[Route("api/[controller]")]
[ApiController]
public class ScoreController : ControllerBase
{
private IScoreService _scoreService = new ScoreServiceEF();
// GET: api/Score
[HttpGet]
public IEnumerable<Score> Get()
{
return _scoreService.GetTopScores();
}
// POST: api/Score
[HttpPost]
public void Post([FromBody] Score score)
{
_scoreService.AddScore(score);
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPuzzleWeb.Models;
namespace NPuzzleWeb.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
using System;
namespace NPuzzleWeb.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NPuzzleCore\NPuzzleCore.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace NPuzzleWeb
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61598",
"sslPort": 44384
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"NPuzzleWeb": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace NPuzzleWeb
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - NPuzzleWeb</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">NPuzzleWeb</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - NPuzzleWeb - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment