Skip to content

Commit

Permalink
Merge pull request #646 from zukomgwili/replace_client_side_caching_#603
Browse files Browse the repository at this point in the history
Replace client side caching #603
  • Loading branch information
poppastring committed Sep 5, 2022
2 parents d7cca03 + c971aa3 commit 7c1435a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 52 deletions.
34 changes: 20 additions & 14 deletions source/DasBlog.Web.UI/Controllers/ArchiveController.cs
Expand Up @@ -13,24 +13,26 @@
using Microsoft.Extensions.Logging;
using EventCodes = DasBlog.Services.ActivityLogs.EventCodes;
using DasBlog.Services.ActivityLogs;
using Microsoft.Extensions.Caching.Memory;

namespace DasBlog.Web.Controllers
{
[Route("archive")]
[ResponseCache(Duration = 14400, Location = ResponseCacheLocation.Any)]
public class ArchiveController : DasBlogBaseController
{
private readonly IArchiveManager archiveManager;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IMapper mapper;
private readonly ILogger<ArchiveController> logger;
private readonly IDasBlogSettings dasBlogSettings;
private readonly IMemoryCache memoryCache;
private const string ARCHIVE = "Archive";

public ArchiveController(IArchiveManager archiveManager, IHttpContextAccessor httpContextAccessor, IMapper mapper,
ILogger<ArchiveController> logger, IDasBlogSettings settings) : base(settings)
ILogger<ArchiveController> logger, IDasBlogSettings settings, IMemoryCache memoryCache) : base(settings)
{
this.dasBlogSettings = settings;
this.memoryCache = memoryCache;
this.archiveManager = archiveManager;
this.httpContextAccessor = httpContextAccessor;
this.mapper = mapper;
Expand Down Expand Up @@ -77,24 +79,28 @@ public IActionResult ArchiveAll()
foreach (var year in listofyears)
{
entries.AddRange(
archiveManager.GetEntriesForYear(new DateTime(year, 1, 1) , languageFilter).OrderByDescending(x => x.CreatedUtc));
archiveManager.GetEntriesForYear(new DateTime(year, 1, 1), languageFilter).OrderByDescending(x => x.CreatedUtc));
}

var alvm = new ArchiveListViewModel();

foreach (var i in entries.ToList().Select(entry => mapper.Map<PostViewModel>(entry)).ToList())
if (!memoryCache.TryGetValue(CACHEKEY_ARCHIVE, out ArchiveListViewModel alvm))
{
var index = int.Parse(string.Format("{0}{1}", i.CreatedDateTime.Year, string.Format("{0:00}", i.CreatedDateTime.Month)));
alvm = new ArchiveListViewModel();

if (alvm.MonthEntries.ContainsKey(index))
{
alvm.MonthEntries[index].Add(i);
}
else
foreach (var i in entries.ToList().Select(entry => mapper.Map<PostViewModel>(entry)).ToList())
{
var list = new List<PostViewModel>() { i };
alvm.MonthEntries.Add(index, list);
var index = int.Parse(string.Format("{0}{1}", i.CreatedDateTime.Year, string.Format("{0:00}", i.CreatedDateTime.Month)));

if (alvm.MonthEntries.ContainsKey(index))
{
alvm.MonthEntries[index].Add(i);
}
else
{
var list = new List<PostViewModel>() { i };
alvm.MonthEntries.Add(index, list);
}
}
memoryCache.Set(CACHEKEY_ARCHIVE, alvm, SiteCacheSettings());
}

return View(alvm);
Expand Down
73 changes: 37 additions & 36 deletions source/DasBlog.Web.UI/Controllers/BlogPostController.cs
Expand Up @@ -34,12 +34,12 @@ public class BlogPostController : DasBlogBaseController
private readonly ILogger<BlogPostController> logger;
private readonly IBlogPostViewModelCreator modelViewCreator;
private readonly IMemoryCache memoryCache;
private readonly IRecaptchaService recaptcha;
private readonly IRecaptchaService recaptcha;


public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpContextAccessor, IDasBlogSettings dasBlogSettings,
public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpContextAccessor, IDasBlogSettings dasBlogSettings,
IMapper mapper, ICategoryManager categoryManager, IFileSystemBinaryManager binaryManager, ILogger<BlogPostController> logger,
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache,IRecaptchaService recaptcha)
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache, IRecaptchaService recaptcha)
: base(dasBlogSettings)
{
this.blogManager = blogManager;
Expand All @@ -51,7 +51,7 @@ public class BlogPostController : DasBlogBaseController
this.logger = logger;
this.modelViewCreator = modelViewCreator;
this.memoryCache = memoryCache;
this.recaptcha = recaptcha;
this.recaptcha = recaptcha;
}

[AllowAnonymous]
Expand Down Expand Up @@ -177,7 +177,7 @@ public IActionResult EditPost(PostViewModel post, string submit)

if (!string.IsNullOrWhiteSpace(post.NewCategory))
{
ModelState.AddModelError(nameof(post.NewCategory),
ModelState.AddModelError(nameof(post.NewCategory),
$"Please click 'Add' to add the category, \"{post.NewCategory}\" or clear the text before continuing");
return LocalRedirect(string.Format("/post/{0}/edit", post.EntryId));
}
Expand Down Expand Up @@ -271,7 +271,7 @@ public IActionResult CreatePost(PostViewModel post, string submit)
}

if (entry != null)
{
{
logger.LogInformation(new EventDataItem(EventCodes.EntryAdded, null, "Blog post created: {0}", entry.Title));
}

Expand Down Expand Up @@ -375,11 +375,11 @@ public IActionResult CommentError(AddCommentViewModel comment, List<string> erro
AllowComments = entry.AllowComments
};

if(comment != null)
lcvm.CurrentComment = comment;
if (comment != null)
lcvm.CurrentComment = comment;
lpvm.Posts.First().Comments = lcvm;
if(errors != null && errors.Count > 0 )
lpvm.Posts.First().ErrorMessages = errors;
if (errors != null && errors.Count > 0)
lpvm.Posts.First().ErrorMessages = errors;
}
}

Expand All @@ -397,7 +397,7 @@ private IActionResult Comment(string posttitle)
[HttpPost("post/comments")]
public IActionResult AddComment(AddCommentViewModel addcomment)
{
List<string> errors = new List<string>();
List<string> errors = new List<string>();

if (!ModelState.IsValid)
{
Expand All @@ -410,30 +410,30 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
}

// Optional in case of Captcha. Commenting the settings in the config file
// Will disable this check. People will typically disable this when using captcha.
if (!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
// Will disable this check. People will typically disable this when using captcha.
if (!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
dasBlogSettings.SiteConfiguration.CheesySpamA.Trim().Length > 0)
{
if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
StringComparison.OrdinalIgnoreCase) != 0)
{
errors.Add("Answer to Spam Question is invalid. Please enter a valid answer for Spam Question and try again.");
errors.Add("Answer to Spam Question is invalid. Please enter a valid answer for Spam Question and try again.");
}
}

if(dasBlogSettings.SiteConfiguration.EnableCaptcha)
{
var recaptchaTask = recaptcha.Validate(Request);
recaptchaTask.Wait();
var recaptchaResult = recaptchaTask.Result;
if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore )
{
errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
}
}
if (dasBlogSettings.SiteConfiguration.EnableCaptcha)
{
var recaptchaTask = recaptcha.Validate(Request);
recaptchaTask.Wait();
var recaptchaResult = recaptchaTask.Result;
if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore)
{
errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
}
}

if (errors.Count > 0)
{
Expand All @@ -446,7 +446,7 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
commt.EntryId = Guid.NewGuid().ToString();
commt.IsPublic = !dasBlogSettings.SiteConfiguration.CommentsRequireApproval;
commt.CreatedUtc = commt.ModifiedUtc = DateTime.Now.ToUniversalTime();

logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment CONTENT DUMP", commt.Content));

var state = blogManager.AddComment(addcomment.TargetEntryId, commt);
Expand Down Expand Up @@ -550,7 +550,7 @@ public IActionResult GetCategory(string category)
}

[AllowAnonymous]
[HttpPost("post/search", Name=Constants.SearcherRouteName)]
[HttpPost("post/search", Name = Constants.SearcherRouteName)]
public IActionResult Search(string searchText)
{
if (string.IsNullOrWhiteSpace(searchText))
Expand All @@ -561,7 +561,7 @@ public IActionResult Search(string searchText)
var lpvm = new ListPostsViewModel();
var entries = blogManager.SearchEntries(WebUtility.HtmlEncode(searchText), Request.Headers["Accept-Language"])?.Where(e => e.IsPublic)?.ToList();

if (entries != null )
if (entries != null)
{
lpvm.Posts = entries.Select(entry => mapper.Map<PostViewModel>(entry)).ToList();
ViewData[Constants.ShowPageControl] = false;
Expand All @@ -579,15 +579,15 @@ private IActionResult HandleNewCategory(PostViewModel post)
ModelState.ClearValidationState("");
if (string.IsNullOrWhiteSpace(post.NewCategory))
{
ModelState.AddModelError(nameof(post.NewCategory),
ModelState.AddModelError(nameof(post.NewCategory),
"To add a category you must enter some text in the box next to the 'Add' button before clicking 'Add'");
return View(post);
}

var newCategory = post.NewCategory?.Trim();
var newCategoryDisplayName = newCategory;
var newCategoryUrl = NBR.Entry.InternalCompressTitle(newCategory);
// Category names should not include special characters #200
// Category names should not include special characters #200
if (post.AllCategories.Any(c => c.CategoryUrl == newCategoryUrl))
{
ModelState.AddModelError(nameof(post.NewCategory), $"The category, {post.NewCategory}, already exists");
Expand All @@ -596,7 +596,7 @@ private IActionResult HandleNewCategory(PostViewModel post)
{
post.AllCategories.Add(new CategoryViewModel { Category = newCategoryDisplayName, CategoryUrl = newCategoryUrl, Checked = true });
post.NewCategory = "";
ModelState.Remove(nameof(post.NewCategory)); // ensure response refreshes page with view model's value
ModelState.Remove(nameof(post.NewCategory)); // ensure response refreshes page with view model's value
}

return View(post);
Expand All @@ -608,7 +608,7 @@ private IActionResult HandleImageUpload(PostViewModel post)
var fileName = post.Image?.FileName;
if (string.IsNullOrEmpty(fileName))
{
ModelState.AddModelError(nameof(post.Image),
ModelState.AddModelError(nameof(post.Image),
$"You must select a file before clicking \"{Constants.UploadImageAction}\" to upload it");
return View(post);
}
Expand Down Expand Up @@ -643,7 +643,7 @@ private void ValidatePostName(PostViewModel post)
var dt = ValidatePostDate(post);
var entry = blogManager.GetBlogPost(post.Title.Replace(" ", string.Empty), dt);

if (entry != null && string.Compare(entry.EntryId, post.EntryId, true) > 0 )
if (entry != null && string.Compare(entry.EntryId, post.EntryId, true) > 0)
{
ModelState.AddModelError(string.Empty, "A post with this title already exists. Titles must be unique");
}
Expand Down Expand Up @@ -680,6 +680,7 @@ private void BreakSiteCache()
{
memoryCache.Remove(CACHEKEY_RSS);
memoryCache.Remove(CACHEKEY_FRONTPAGE);
memoryCache.Remove(CACHEKEY_ARCHIVE);
}

}
Expand Down
5 changes: 3 additions & 2 deletions source/DasBlog.Web.UI/Controllers/DasBlogController.cs
Expand Up @@ -13,14 +13,15 @@ public abstract class DasBlogController : Controller
{
protected const string CACHEKEY_RSS = "CACHEKEY_RSS";
protected const string CACHEKEY_FRONTPAGE = "CACHEKEY_FRONTPAGE";
protected const string CACHEKEY_ARCHIVE = "CACHEKEY_ARCHIVE";

// avoid the exception handling middleware which would log the exception again
public virtual IActionResult HandleError(string message, LoggedException ex)
{
return View(nameof(HomeController.Error),
new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
// a bit of cargo-culting here - Activity is some sort of diagnostic thing
// as presumably is TraceIdentifier
// a bit of cargo-culting here - Activity is some sort of diagnostic thing
// as presumably is TraceIdentifier
}

public virtual MemoryCacheEntryOptions SiteCacheSettings()
Expand Down

0 comments on commit 7c1435a

Please sign in to comment.