School Commit Init

This commit is contained in:
2024-08-31 12:07:21 +03:00
commit 0b130ee18c
2801 changed files with 4720552 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lab9", "Lab9\Lab9.csproj", "{079CCEEA-51C7-4415-8EDA-4941C9E3C147}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{079CCEEA-51C7-4415-8EDA-4941C9E3C147}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{079CCEEA-51C7-4415-8EDA-4941C9E3C147}.Debug|Any CPU.Build.0 = Debug|Any CPU
{079CCEEA-51C7-4415-8EDA-4941C9E3C147}.Release|Any CPU.ActiveCfg = Release|Any CPU
{079CCEEA-51C7-4415-8EDA-4941C9E3C147}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1656763D-0168-458C-A65C-595CF9CA609B}
EndGlobalSection
EndGlobal
@@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Lab9.Models;
namespace Lab9.Context
{
public class NewsContext : DbContext
{
public NewsContext(DbContextOptions<NewsContext> options) : base(options)
{
}
public DbSet<News> News { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<News>().ToTable("News");
modelBuilder.Entity<User>().ToTable("Users");
}
}
}
@@ -0,0 +1,143 @@
using Lab9.Models;
using Lab9.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace Lab9.Controllers
{
[Route("/")]
public class MainController : Controller
{
private readonly IRepository _repository;
public MainController(IRepository repository)
{
_repository = repository;
}
public IActionResult Index()
{
return View("Views/Index.cshtml");
}
[Route("login")]
[HttpGet]
public IActionResult Login()
{
return View("Views/Login.cshtml");
}
[Route("login")]
[HttpPost]
public IActionResult Login(string username, string password)
{
if (_repository.ValidateUser(username, password))
{
HttpContext.Session.SetString("username", username);
return RedirectToAction("admin");
}
ViewBag.Error = "Invalid username or password";
return View("Views/Login.cshtml");
}
[Route("logout")]
[HttpGet]
public IActionResult Logout()
{
HttpContext.Session.Remove("username");
return Redirect("/");
}
[Route("view")]
[HttpGet]
public IActionResult News()
{
return View("Views/View.cshtml", _repository.GetAllNews());
}
[Route("admin")]
[HttpGet]
public IActionResult Admin()
{
if (HttpContext.Session.GetString("username") == null)
{
return Redirect("/login");
}
return View("Views/Admin.cshtml",_repository.GetAllNews());
}
[Route("add")]
[HttpGet]
public IActionResult Add()
{
if (HttpContext.Session.GetString("username") == null)
{
return Redirect("/login");
}
return View("Views/Add.cshtml");
}
[Route("edit/{id}")]
[HttpGet]
public IActionResult Edit(int id)
{
if (HttpContext.Session.GetString("username") == null)
{
return Redirect("/login");
}
return View("Views/Edit.cshtml", _repository.GetNewsById(id));
}
[Route("edit")]
[HttpPost]
public IActionResult Edit(News news)
{
if (HttpContext.Session.GetString("username") == null)
{
return Redirect("/login");
}
if (_repository.UpdateNews(news))
{
return RedirectToAction("Admin");
}
ViewBag.Error = "Failed to update news";
return View("Views/Edit.cshtml", news);
}
[Route("add")]
[HttpPost]
public IActionResult Add(News news)
{
if (HttpContext.Session.GetString("username") == null)
{
return Redirect("/login");
}
if (_repository.InsertNews(news))
{
return RedirectToAction("Admin");
}
ViewBag.Error = "Failed to add news";
return View("Views/Add.cshtml", news);
}
[Route("getnews")]
[HttpPost]
public IActionResult GetNews(string category, string date)
{
if (category != null && date != null)
{
return Ok(_repository.GetAllNewsByCategoryAndDate(category, DateTime.Parse(date)));
}
if (category != null)
{
return Ok(_repository.GetAllNewsByCategory(category));
}
if (date != null)
{
return Ok(_repository.GetAllNewsByDate(DateTime.Parse(date)));
}
return Ok(_repository.GetAllNews());
}
}
}
@@ -0,0 +1,18 @@
using System.Text.Json;
namespace Lab9.Extensions
{
public static class SessionExtension
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T? Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.2" />
</ItemGroup>
</Project>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
<View_SelectedScaffolderID>RazorViewScaffolder</View_SelectedScaffolderID>
<View_SelectedScaffolderCategoryPath>root/Common/MVC/View</View_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ViewDialogWidth>650</WebStackScaffolding_ViewDialogWidth>
<WebStackScaffolding_IsLayoutPageSelected>False</WebStackScaffolding_IsLayoutPageSelected>
<WebStackScaffolding_IsPartialViewSelected>False</WebStackScaffolding_IsPartialViewSelected>
<WebStackScaffolding_IsReferencingScriptLibrariesSelected>False</WebStackScaffolding_IsReferencingScriptLibrariesSelected>
</PropertyGroup>
</Project>
@@ -0,0 +1,15 @@
using Newtonsoft.Json;
using System.ComponentModel;
namespace Lab9.Models
{
public class News
{
public int Id { get; set; }
public required string Title { get; set; }
public required string NewsText { get; set; }
public DateTime Date { get; set; }
public required string Category { get; set; }
public required string Producer { get; set; }
}
}
@@ -0,0 +1,9 @@
namespace Lab9.Models
{
public class User
{
public int Id { get; set; }
public required string Username { get; set; }
public required string Password { get; set; }
}
}
@@ -0,0 +1,48 @@
using Lab9.Context;
using Lab9.Repositories;
using Microsoft.EntityFrameworkCore;
namespace Lab9
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSession(options =>
{
options.Cookie.Name = "SessionId";
options.Cookie.IsEssential = true;
});
builder.Services.AddDbContext<NewsContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("NewsDB")));
builder.Services.AddScoped<IRepository,Repository>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseSession();
app.MapControllers();
app.Run();
}
}
}
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:27278",
"sslPort": 44380
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5225",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7041;http://localhost:5225",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -0,0 +1,18 @@
using Lab9.Models;
namespace Lab9.Repositories
{
public interface IRepository
{
public IList<News> GetAllNews();
public IList<News> GetAllNewsByDate(DateTime date);
public IList<News> GetAllNewsByCategory(string category);
public IList<News> GetAllNewsByCategoryAndDate(string category, DateTime date);
public bool ValidateUser(string username, string password);
public bool InsertNews(News news);
public bool UpdateNews(News news);
public News? GetNewsById(int id);
}
}
@@ -0,0 +1,74 @@
using Lab9.Context;
using Lab9.Models;
namespace Lab9.Repositories
{
public class Repository : IRepository
{
private readonly NewsContext _context;
public Repository(NewsContext context)
{
_context = context;
}
public IList<News> GetAllNews()
{
return _context.News.ToList();
}
public IList<News> GetAllNewsByCategory(string category)
{
return _context.News.Where(n => n.Category == category).ToList();
}
public IList<News> GetAllNewsByCategoryAndDate(string category, DateTime date)
{
return _context.News.Where(n => n.Category == category && n.Date == date).ToList();
}
public IList<News> GetAllNewsByDate(DateTime date)
{
return _context.News.Where(n => n.Date == date).ToList();
}
public News? GetNewsById(int id)
{
return _context.News.FirstOrDefault(n => n.Id == id);
}
public bool InsertNews(News news)
{
try
{
_context.News.Add(news);
_context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public bool UpdateNews(News news)
{
try
{
_context.News.Update(news);
_context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public bool ValidateUser(string username, string password)
{
return _context.Users.Any(u => u.Username == username && u.Password == password);
}
}
}
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Add
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container" id="addFormDiv">
<div class="row">
<div class="col-sm">
<div class="container text-left">
<form method="post" action="/add" id="addForm">
<h3>Add a news:</h3>
<div class="mb-1">
<label for="titleField" class="form-label">Title: </label><input type="text"
id="titleField"
class="form-control"
name="Title"
required
pattern="[0-9A-Za-z-.\:;]{5,30}" />
</div>
<div class="mb-1">
<label for="contentField" class="form-label">Content: </label><input type="text"
id="contentField"
class="form-control"
name="NewsText"
required
pattern="[0-9A-Za-z-.\:;]{10,256}" />
</div>
<div class="mb-1">
<label for="dateField" class="form-label">Date: </label><input type="date" id="dateField" class="form-control" required name="Date"/>
</div>
<div class="mb-1">
<label for="producerField" class="form-label">Producer: </label><input type="text"
id="producerField"
class="form-control"
name="Producer"
required
pattern="[0-9A-Za-z-]{5,30}" />
</div>
<div class="mb-1">
<label for="categoryField" class="form-label">Category: </label><input type="text"
id="categoryField"
class="form-control"
name="Category"
required
pattern="[0-9A-Za-z-]{5,30}" />
</div>
<button id="insertNewsButton"
type="submit"
class="btn btn-success mb-1">
Add News
</button>
</form>
<a type="submit"
class="btn btn-secondary mb-1"
name="returnButton"
href="/admin">
Return to admin
</a>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Lab9.Views
{
public class AddModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,68 @@
@model IList<Lab9.Models.News>
<!DOCTYPE <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Admin
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container text-center">
<h3>Welcome</h3>
<table class="container"
id="newsTable"
style="
margin: 30px;
border: 1px solid;
border-color: black;
border-collapse: collapse;
">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Category</th>
<th>Date</th>
<th>Producer</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach(var item in Model)
{
<tr>
<td>@item.Title </td>
<td>@item.NewsText </td>
<td>@item.Category </td>
<td>@item.Date.ToString("dd-MM-yyyy") </td>
<td>@item.Producer</td>
<td>
<a class="btn btn-danger"
name="deleteButton"
href="/edit/@item.Id">
Edit
</a>
</td>
</tr>
}
</tbody>
<a type="button"
class="btn btn-primary"
name="addNewsButton"
href="/add"
style="margin: 30px">
Add news
</a>
<a type="button"
class="btn btn-dark"
name="logoutButton"
href="/logout"
style="margin: 30px">
Log out
</a>
</table>
</div>
</body>
</html>
@@ -0,0 +1,83 @@
@model Lab9.Models.News
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Edit
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container" id="addFormDiv">
<div class="row">
<div class="col-sm">
<div class="container text-left">
<form method="post" action="/edit" id="addForm">
<h3>Edit a news:</h3>
<div class="mb-1">
<input type="hidden" id="idField" value="@Model.Id" name="Id" />
<label for="titleField" class="form-label">Title: </label><input type="text"
id="titleField"
class="form-control"
required
name="Title"
pattern="[0-9A-Za-z-.\:;]{5,30}"
value="@Model.Title" />
</div>
<div class="mb-1">
<label for="contentField" class="form-label">Content: </label><input type="text"
id="contentField"
class="form-control"
required
name="NewsText"
pattern="[0-9A-Za-z-.\:;]{10,256}"
value="@Model.NewsText" />
</div>
<div class="mb-1">
<label for="dateField" class="form-label">Date: </label><input type="date"
id="dateField"
class="form-control"
required
name="Date"
value="@Model.Date.ToString("yyyy-MM-dd")" />
</div>
<div class="mb-1">
<label for="producerField" class="form-label">Producer: </label><input type="text"
id="producerField"
class="form-control"
required
name="Producer"
pattern="[0-9A-Za-z-]{5,30}"
value="@Model.Producer" />
</div>
<div class="mb-1">
<label for="categoryField" class="form-label">Category: </label><input type="text"
id="categoryField"
class="form-control"
required
name="Category"
pattern="[0-9A-Za-z-]{5,30}"
value="@Model.Category" />
</div>
<button id="insertNewsButton"
type="submit"
class="btn btn-success mb-1">
Edit News
</button>
</form>
<a
class="btn btn-secondary mb-1"
name="returnButton"
href="/admin">
Return to admin
</a>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Lab9.Views
{
public class EditModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>News</title>
</head>
<body>
<div class="container text-center" id="index-page">
<h2>News</h2>
<a type="button"
class="btn btn-primary btn-block"
href="/login">
Login
</a>
<a type="button"
class="btn btn-primary btn-block"
href="/view">
View
</a>
</div>
</body>
</html>
@@ -0,0 +1,42 @@
<!DOCTYPE <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Login
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<form method="post" action="/login" class="container">
<h2>Login</h2>
<div class="mb-3 mt-3">
<label for="username" class="form-label">Username:</label>
<input type="text"
class="form-control"
id="username"
placeholder="Enter username"
name="username" />
</div>
<div class="mb-3">
<label for="password" class="form-label">Password:</label>
<input type="password"
class="form-control"
id="password"
placeholder="Enter password"
name="password" />
</div>
<button class="btn btn-primary" name="loginButton" type="submit">
Login
</button>
<a class="btn btn-secondary" name="indexPage" href="/">
Cancel
</a>
</form>
@if(ViewBag.Error != null)
{
<script>
alert("@ViewBag.Error");
</script>
})
</body>
</html>
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Lab9.Views
{
public class LoginModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,83 @@
@model IList<Lab9.Models.News>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
View
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</head>
<body>
<div class="container text-center">
<h3>Welcome</h3>
<div class='dropdown'>
<button class='btn btn-secondary dropdown-toggle' type='button' id='dropdownMenuButton'
data-bs-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>
Filter
</button>
<div class='dropdown-menu' aria-labelledby='dropdownMenuButton'>
<input class='dropdown-item' type="date" id="dateField" class="form-control" required>
<input class='dropdown-item' placeholder="Category" type="text" id="categoryField" class="form-control"
required>
<input class='dropdown-item' type="button" class="btn btn-primary" id="filterButton" value="Filter">
</div>
</div>
<table class="container" id="newsTable"
style="margin: 30px; border: 1px solid;border-color: black; border-collapse: collapse;">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Category</th>
<th>Date</th>
<th>Producer</th>
</tr>
</thead>
<tbody id='tableBody'>
@foreach(var item in Model){
<tr>
<td>@item.Title </td>
<td>@item.NewsText </td>
<td>@item.Category </td>
<td>@item.Date.ToString("yyyy-MM-dd") </td>
<td>@item.Producer</td>
</tr>
}
</tbody>
<a class="btn btn-dark" name="backButton" href="/" style=" margin: 30px">Back</a>
</div>
<script>
$(document).ready(function () {
$('#filterButton').click(function () {
var date = $('#dateField').val();
var category = $('#categoryField').val();
$.ajax({
url: '/getnews',
type: 'POST',
data: {
date: date,
category: category,
},
success: function (response) {
$('#tableBody').empty();
for (var i = 0; i < response.length; i++) {
var newRow = "<tr><td>" + response[i].title + "</td><td>" + response[i].newsText +
"</td><td>" + response[i].category + "</td><td>" + response[i].date.slice(0,10) +
"</td><td>" + response[i].producer + "</td></tr>";
$('#tableBody').append(newRow);
}
}
});
});
});
</script>
</body>
</html>
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Lab9.Views
{
public class ViewModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"NewsDb": "Data Source=danielcujba\\sqlexpress;Initial Catalog=NewsDb;Integrated Security=True;Trust Server Certificate=True"
}
}
@@ -0,0 +1,22 @@
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

@@ -0,0 +1,4 @@
// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.