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

ФТ-304 Унисихин Никита #24

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion BadNews/BadNews.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<LangVersion>9</LangVersion>
</PropertyGroup>

Expand Down
37 changes: 37 additions & 0 deletions BadNews/Components/ArchiveLinksViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using BadNews.Repositories.News;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

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

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

public IViewComponentResult Invoke()
{
const string cacheKey = nameof(ArchiveLinksViewComponent);
if (memoryCache.TryGetValue(cacheKey, out var years))
return View(years);

years = newsRepository.GetYearsWithArticles();
if (years != null)
{
memoryCache.Set(cacheKey, years, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30)
});
}

return View(years);
}
}
}
21 changes: 21 additions & 0 deletions BadNews/Components/WeatherViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Threading.Tasks;
using BadNews.Repositories.Weather;
using Microsoft.AspNetCore.Mvc;

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

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

public async Task<IViewComponentResult> InvokeAsync()
{
return View(await _weatherForecastRepository.GetWeatherForecastAsync());
}
}
}
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
});
}
[HttpPost]
public IActionResult DeleteArticle(Guid id)
{
newsRepository.DeleteArticleById(id);
return RedirectToAction("Index", "News");
}
}
}
28 changes: 28 additions & 0 deletions BadNews/Controllers/ErrorController.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;

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

public ErrorsController(ILogger<ErrorsController> logger)
{
this.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);
}
}
}
43 changes: 43 additions & 0 deletions BadNews/Controllers/NewsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Threading.Tasks;
using BadNews.ModelBuilders.News;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace BadNews.Controllers
{
public class NewsController : Controller
{
private readonly INewsModelBuilder newsModelBuilder;
private readonly IMemoryCache memoryCache;

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

[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Client, VaryByHeader = "Cookie")]
public async Task<IActionResult> Index(int? year, int pageIndex = 0)
{
var model = newsModelBuilder.BuildIndexModel(pageIndex!, true, year);
return View(model);
}

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> FullArticle(Guid id)
{
if (memoryCache.TryGetValue(id, out var model)) return View(model);

model = newsModelBuilder.BuildFullArticleModel(id);

if (model is null) return NotFound();

memoryCache.Set(id, model, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromSeconds(30)
});
return View(model);
}
}
}
29 changes: 25 additions & 4 deletions BadNews/Elevation/ElevationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,36 @@ namespace BadNews.Elevation
public class ElevationMiddleware
{
private readonly RequestDelegate next;

public ElevationMiddleware(RequestDelegate next)
{
this.next = next;
}

public async Task InvokeAsync(HttpContext context)
{
throw new NotImplementedException();
if (context.Request.Path != "/elevation")
{
await next(context);
return;
}

if (context.Request.Query.ContainsKey("up"))
{
context
.Response
.Cookies
.Append
(
ElevationConstants.CookieName,
ElevationConstants.CookieValue,
new CookieOptions { HttpOnly = true }
);
}
else
context.Response.Cookies.Delete(ElevationConstants.CookieName);

context.Response.Redirect("/");
}
}
}
}
51 changes: 41 additions & 10 deletions 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,30 +13,58 @@ 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)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.ConfigureHostConfiguration(config =>
{
config.AddJsonFile("appsettings.Secret.json", optional: true, reloadOnChange: false);
});
}

private static void InitializeDataBase()
{
const int newsArticleCount = 100;
const int newsArticleCount = 20000;

var generator = new NewsGenerator();
var articles = generator.GenerateNewsArticles()
.Take(newsArticleCount)
.OrderBy(it => it.Id)
.ToList();
.Take(newsArticleCount)
.OrderBy(it => it.Id)
.ToList();

var repository = new NewsRepository();
repository.InitializeDataBase(articles);
}
}
}
}
12 changes: 6 additions & 6 deletions BadNews/Repositories/Weather/OpenWeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ public class WeatherInfo

public class MainInfo
{
public int Temp { get; set; }
public decimal Temp { get; set; }
public decimal FeelsLike { get; set; }
public int TempMin { get; set; }
public int TempMax { get; set; }
public int Pressure { get; set; }
public int Humidity { get; set; }
public decimal TempMin { get; set; }
public decimal TempMax { get; set; }
public decimal Pressure { get; set; }
public decimal Humidity { get; set; }
}
}
}
}
4 changes: 2 additions & 2 deletions BadNews/Repositories/Weather/WeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ public static WeatherForecast CreateFrom(OpenWeatherForecast forecast)
{
return new WeatherForecast
{
TemperatureInCelsius = forecast.Main.Temp,
TemperatureInCelsius = (int)forecast.Main.Temp,
IconUrl = forecast.Weather.FirstOrDefault()?.IconUrl ?? defaultWeatherImageUrl
};
}
}
}
}
Loading