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

Косарева & Пичугин & Сычев & Титаренко #18

Open
wants to merge 7 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
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 readonly IMemoryCache memoryCache;

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

public IViewComponentResult Invoke()
{
var 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)
});
}
}
years = newsRepository.GetYearsWithArticles();
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.Weather;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

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

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

public async Task<IViewComponentResult> InvokeAsync()
{
var data = await weatherForecastRepository.GetWeatherForecastAsync();
return View(data);
}
}
}
62 changes: 62 additions & 0 deletions BadNews/Controllers/EditorController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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");
}
}

// public class IndexViewModel
// {
// [Required(ErrorMessage = "У новости должен быть заголовок")]
// public string Header { get; set; }
//
// [StopWords("действительно", "реально", "на самом деле", "поверьте", "без обмана",
// ErrorMessage = "Нельзя использовать стоп-слова")]
// public string Teaser { get; set; }
//
// [StopWords("действительно", "реально", "на самом деле", "поверьте", "без обмана",
// ErrorMessage = "Нельзя использовать стоп-слова")]
// public string ContentHtml { get; set; }
// }
}
27 changes: 27 additions & 0 deletions BadNews/Controllers/ErrorsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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);
}
}
}
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 readonly INewsModelBuilder newsModelBuilder;
private readonly IMemoryCache memoryCache;

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

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

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult FullArticle(Guid id)
{
if (memoryCache.TryGetValue(id, out var model)) return View(model);
model = newsModelBuilder.BuildFullArticleModel(id);
if (model != null)
{
memoryCache.Set(id, model, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromSeconds(10)
});
}

else
{
return NotFound();
}


return View(model);
}
}
}
6 changes: 3 additions & 3 deletions BadNews/Elevation/ElevationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ public static class ElevationExtensions
{
public static bool IsElevated(this HttpRequest request)
{
bool isElevated = request.Cookies.TryGetValue(ElevationConstants.CookieName, out var value)
&& value == ElevationConstants.CookieValue;
var isElevated = request.Cookies.TryGetValue(ElevationConstants.CookieName, out var value)
&& value == ElevationConstants.CookieValue;
return isElevated;
}

Expand All @@ -17,4 +17,4 @@ public static bool IsElevated(this ViewContext viewContext)
return viewContext.HttpContext.Request.IsElevated();
}
}
}
}
27 changes: 23 additions & 4 deletions BadNews/Elevation/ElevationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,34 @@ 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.Equals("/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("/");
}
}
}
}
42 changes: 38 additions & 4 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,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,12 +46,19 @@ public static IHostBuilder CreateHostBuilder(string[] args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
// webBuilder.UseEnvironment(Environments.Development);
})
.ConfigureHostConfiguration(config =>
{
config.AddJsonFile("appsettings.Secret.json", optional: true, reloadOnChange: false);
})
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration));
}

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

var generator = new NewsGenerator();
var articles = generator.GenerateNewsArticles()
Expand All @@ -36,4 +70,4 @@ private static void InitializeDataBase()
repository.InitializeDataBase(articles);
}
}
}
}
10 changes: 5 additions & 5 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 double 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 double TempMin { get; set; }
public double TempMax { get; set; }
public double Pressure { get; set; }
public double Humidity { get; set; }
}
}
}
3 changes: 2 additions & 1 deletion BadNews/Repositories/Weather/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Linq;

namespace BadNews.Repositories.Weather
Expand All @@ -13,7 +14,7 @@ public static WeatherForecast CreateFrom(OpenWeatherForecast forecast)
{
return new WeatherForecast
{
TemperatureInCelsius = forecast.Main.Temp,
TemperatureInCelsius = (int)forecast.Main.Temp,
IconUrl = forecast.Weather.FirstOrDefault()?.IconUrl ?? defaultWeatherImageUrl
};
}
Expand Down
Loading