Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Дейнов, Аткишкин, Рогачев #7

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
36 changes: 36 additions & 0 deletions BadNews/Components/ArchiveLinksViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using BadNews.Repositories.News;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace BadNews.Components
{
public class ArchiveLinksViewComponent : ViewComponent
{
private readonly IMemoryCache memoryCache;
private readonly INewsRepository newsRepository;

public ArchiveLinksViewComponent(INewsRepository newsRepository, IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
this.newsRepository = newsRepository;
}

public IViewComponentResult Invoke()
{
string cacheKey = nameof(ArchiveLinksViewComponent);
if (!memoryCache.TryGetValue(cacheKey, out var years))
{
years = newsRepository.GetYearsWithArticles();
if (years != null)
{
memoryCache.Set(cacheKey, years, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30)
});
}
}
return View(years);
}
}
}
23 changes: 23 additions & 0 deletions BadNews/Components/WeatherViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Threading.Tasks;
using BadNews.Repositories.News;
using BadNews.Repositories.Weather;
using Microsoft.AspNetCore.Mvc;

namespace BadNews.Components
{
public class WeatherViewComponent : ViewComponent
{
private readonly IWeatherForecastRepository _weatherForecastRepository;

public WeatherViewComponent(IWeatherForecastRepository weatherForecastRepository)
{
this._weatherForecastRepository = weatherForecastRepository;
}

public async Task<IViewComponentResult> InvokeAsync()
{
var weatherForecast = await _weatherForecastRepository.GetWeatherForecastAsync();
return View(weatherForecast);
}
}
}
49 changes: 49 additions & 0 deletions BadNews/Controllers/EditorController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using BadNews.Elevation;
using BadNews.Models.Editor;
using BadNews.Repositories.News;
using Microsoft.AspNetCore.Mvc;

namespace BadNews.Controllers
{
[ElevationRequiredFilter]
public class EditorController : Controller
{
private readonly INewsRepository newsRepository;

public EditorController(INewsRepository newsRepository)
{
this.newsRepository = newsRepository;
}

public IActionResult Index()
{
return View(new IndexViewModel());
}

[HttpPost]
public IActionResult CreateArticle([FromForm] IndexViewModel model)
{
if (!ModelState.IsValid)
return View("Index", model);

var id = newsRepository.CreateArticle(new NewsArticle {
Date = DateTime.Now.Date,
Header = model.Header,
Teaser = model.Teaser,
ContentHtml = model.ContentHtml,
});

return RedirectToAction("FullArticle", "News", new {
id = id
});
}

[HttpPost]
public IActionResult DeleteArticle(Guid id)
{
newsRepository.DeleteArticleById(id);
return RedirectToAction("Index", "News");
}
}
}
28 changes: 28 additions & 0 deletions BadNews/Controllers/ErrorsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Serilog;

namespace BadNews.Controllers
{
public class ErrorsController : Controller
{
private readonly ILogger<ErrorsController> _logger;

public ErrorsController(ILogger<ErrorsController> logger)
{
_logger = logger;
}

public IActionResult StatusCode(int? code)
{
_logger.LogWarning("status-code {code} at {time}", code, DateTime.Now);
return View(code);
}

public IActionResult Exception()
{
return View(null, HttpContext.TraceIdentifier);
}
}
}
49 changes: 49 additions & 0 deletions BadNews/Controllers/NewsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using BadNews.ModelBuilders.News;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace BadNews.Controllers
{
[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Client, VaryByHeader = "Cookie")]
public class NewsController : Controller
{
private IMemoryCache memoryCache;
private readonly INewsModelBuilder newsModelBuilder;

public NewsController(INewsModelBuilder newsModelBuilder, IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
this.newsModelBuilder = newsModelBuilder;
}

public IActionResult Index(int? year, int pageIndex = 0)
{
var model = newsModelBuilder.BuildIndexModel(pageIndex, true, year);

return View(model);
}

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult FullArticle(Guid id)
{
string cacheKey = nameof(NewsController) + id;
if (!memoryCache.TryGetValue(cacheKey, out var model))
{
model = newsModelBuilder.BuildFullArticleModel(id);
if (model == null)
{
return NotFound();
}
else
{
memoryCache.Set(cacheKey, model, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromSeconds(30)
});
}
}
return View(model);
}
}
}
20 changes: 19 additions & 1 deletion BadNews/Elevation/ElevationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,25 @@ public ElevationMiddleware(RequestDelegate next)

public async Task InvokeAsync(HttpContext context)
{
throw new NotImplementedException();
if (context.Request.Path != "/elevation")
{
//await next(context);
await next(context);
return;
}
if (context.Request.Query.ContainsKey("up"))
{
context.Response.Cookies.Append(ElevationConstants.CookieName, ElevationConstants.CookieValue, new CookieOptions()
{
HttpOnly = true
});
context.Response.Redirect("/");
}
else
{
context.Response.Cookies.Delete(ElevationConstants.CookieName);
context.Response.Redirect("/");
}
}
}
}
36 changes: 35 additions & 1 deletion BadNews/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Linq;
using BadNews.Repositories.News;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace BadNews
{
Expand All @@ -10,7 +13,31 @@ public class Program
public static void Main(string[] args)
{
InitializeDataBase();
CreateHostBuilder(args).Build().Run();

Log.Logger = new LoggerConfiguration()
.WriteTo.File(".logs/start-host-log-.txt",
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
.CreateLogger();

try
{
Log.Information("Creating web host builder");
var hostBuilder = CreateHostBuilder(args);
Log.Information("Building web host");
var host = hostBuilder.Build();
Log.Information("Running web host");
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}

public static IHostBuilder CreateHostBuilder(string[] args)
Expand All @@ -19,6 +46,13 @@ public static IHostBuilder CreateHostBuilder(string[] args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseEnvironment(Environments.Development);
})
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.ConfigureHostConfiguration(config =>
{
config.AddJsonFile("appsettings.Secret.json", optional: true, reloadOnChange: false);
});
}

Expand Down
5 changes: 1 addition & 4 deletions BadNews/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
"BadNews": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
Loading