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

Кряжев, Шрейн. ФТ-301 #5

Open
wants to merge 3 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 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)
});
}
}
return View(years);
}
}
}
22 changes: 22 additions & 0 deletions BadNews/Components/WeatherViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Threading.Tasks;
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");
}
}
}
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);
}
}
}
48 changes: 48 additions & 0 deletions BadNews/Controllers/NewsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using BadNews.Components;
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, int pageIndex = 0)
{
var model = newsModelBuilder.BuildIndexModel(pageIndex, true, year);
return View(model);
}

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult FullArticle(Guid id)
{
var cacheKey = $"{nameof(NewsController)}_{nameof(FullArticle)}_{id}";
if (!memoryCache.TryGetValue(cacheKey, out var model))
{
model = newsModelBuilder.BuildFullArticleModel(id);
if (model != null)
{
memoryCache.Set(cacheKey, model, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromSeconds(30)
});
}
}
if (model == null)
return NotFound();

return View(model);
}
}
}
16 changes: 15 additions & 1 deletion BadNews/Elevation/ElevationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,21 @@ public ElevationMiddleware(RequestDelegate next)

public async Task InvokeAsync(HttpContext context)
{
throw new NotImplementedException();
if (context.Request.Path == "/elevation")
{
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("/");
}
else
{
await next(context);
}
}
}
}
39 changes: 36 additions & 3 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,18 @@ public static IHostBuilder CreateHostBuilder(string[] args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}).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 Down
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; }
}
}
}
2 changes: 1 addition & 1 deletion BadNews/Repositories/Weather/WeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class WeatherForecast
{
private const string defaultWeatherImageUrl = "/images/cloudy.png";

public int TemperatureInCelsius { get; set; }
public double TemperatureInCelsius { get; set; }
public string IconUrl { get; set; }

public static WeatherForecast CreateFrom(OpenWeatherForecast forecast)
Expand Down
10 changes: 9 additions & 1 deletion BadNews/Repositories/Weather/WeatherForecastRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;

namespace BadNews.Repositories.Weather
{
Expand All @@ -8,10 +9,17 @@ public class WeatherForecastRepository : IWeatherForecastRepository
private const string defaultWeatherImageUrl = "/images/cloudy.png";

private readonly Random random = new Random();
private readonly OpenWeatherClient openWeatherClient;

public WeatherForecastRepository(IOptions<OpenWeatherOptions> weatherOptions)
{
openWeatherClient = new OpenWeatherClient(weatherOptions?.Value.ApiKey);
}

public async Task<WeatherForecast> GetWeatherForecastAsync()
{
return BuildRandomForecast();
var openWeatherForecast = await openWeatherClient.GetWeatherFromApiAsync();
return openWeatherForecast != null ? WeatherForecast.CreateFrom(openWeatherForecast) : BuildRandomForecast();
}

private WeatherForecast BuildRandomForecast()
Expand Down
Loading