Skip to content

Commit 7c1435a

Browse files
authored
Merge pull request #646 from zukomgwili/replace_client_side_caching_#603
Replace client side caching #603
2 parents d7cca03 + c971aa3 commit 7c1435a

File tree

3 files changed

+60
-52
lines changed

3 files changed

+60
-52
lines changed

source/DasBlog.Web.UI/Controllers/ArchiveController.cs

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,26 @@
1313
using Microsoft.Extensions.Logging;
1414
using EventCodes = DasBlog.Services.ActivityLogs.EventCodes;
1515
using DasBlog.Services.ActivityLogs;
16+
using Microsoft.Extensions.Caching.Memory;
1617

1718
namespace DasBlog.Web.Controllers
1819
{
1920
[Route("archive")]
20-
[ResponseCache(Duration = 14400, Location = ResponseCacheLocation.Any)]
2121
public class ArchiveController : DasBlogBaseController
2222
{
2323
private readonly IArchiveManager archiveManager;
2424
private readonly IHttpContextAccessor httpContextAccessor;
2525
private readonly IMapper mapper;
2626
private readonly ILogger<ArchiveController> logger;
2727
private readonly IDasBlogSettings dasBlogSettings;
28+
private readonly IMemoryCache memoryCache;
2829
private const string ARCHIVE = "Archive";
2930

3031
public ArchiveController(IArchiveManager archiveManager, IHttpContextAccessor httpContextAccessor, IMapper mapper,
31-
ILogger<ArchiveController> logger, IDasBlogSettings settings) : base(settings)
32+
ILogger<ArchiveController> logger, IDasBlogSettings settings, IMemoryCache memoryCache) : base(settings)
3233
{
3334
this.dasBlogSettings = settings;
35+
this.memoryCache = memoryCache;
3436
this.archiveManager = archiveManager;
3537
this.httpContextAccessor = httpContextAccessor;
3638
this.mapper = mapper;
@@ -77,24 +79,28 @@ public IActionResult ArchiveAll()
7779
foreach (var year in listofyears)
7880
{
7981
entries.AddRange(
80-
archiveManager.GetEntriesForYear(new DateTime(year, 1, 1) , languageFilter).OrderByDescending(x => x.CreatedUtc));
82+
archiveManager.GetEntriesForYear(new DateTime(year, 1, 1), languageFilter).OrderByDescending(x => x.CreatedUtc));
8183
}
8284

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

89-
if (alvm.MonthEntries.ContainsKey(index))
90-
{
91-
alvm.MonthEntries[index].Add(i);
92-
}
93-
else
89+
foreach (var i in entries.ToList().Select(entry => mapper.Map<PostViewModel>(entry)).ToList())
9490
{
95-
var list = new List<PostViewModel>() { i };
96-
alvm.MonthEntries.Add(index, list);
91+
var index = int.Parse(string.Format("{0}{1}", i.CreatedDateTime.Year, string.Format("{0:00}", i.CreatedDateTime.Month)));
92+
93+
if (alvm.MonthEntries.ContainsKey(index))
94+
{
95+
alvm.MonthEntries[index].Add(i);
96+
}
97+
else
98+
{
99+
var list = new List<PostViewModel>() { i };
100+
alvm.MonthEntries.Add(index, list);
101+
}
97102
}
103+
memoryCache.Set(CACHEKEY_ARCHIVE, alvm, SiteCacheSettings());
98104
}
99105

100106
return View(alvm);

source/DasBlog.Web.UI/Controllers/BlogPostController.cs

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ public class BlogPostController : DasBlogBaseController
3434
private readonly ILogger<BlogPostController> logger;
3535
private readonly IBlogPostViewModelCreator modelViewCreator;
3636
private readonly IMemoryCache memoryCache;
37-
private readonly IRecaptchaService recaptcha;
37+
private readonly IRecaptchaService recaptcha;
3838

3939

40-
public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpContextAccessor, IDasBlogSettings dasBlogSettings,
40+
public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpContextAccessor, IDasBlogSettings dasBlogSettings,
4141
IMapper mapper, ICategoryManager categoryManager, IFileSystemBinaryManager binaryManager, ILogger<BlogPostController> logger,
42-
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache,IRecaptchaService recaptcha)
42+
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache, IRecaptchaService recaptcha)
4343
: base(dasBlogSettings)
4444
{
4545
this.blogManager = blogManager;
@@ -51,7 +51,7 @@ public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpCon
5151
this.logger = logger;
5252
this.modelViewCreator = modelViewCreator;
5353
this.memoryCache = memoryCache;
54-
this.recaptcha = recaptcha;
54+
this.recaptcha = recaptcha;
5555
}
5656

5757
[AllowAnonymous]
@@ -177,7 +177,7 @@ public IActionResult EditPost(PostViewModel post, string submit)
177177

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

273273
if (entry != null)
274-
{
274+
{
275275
logger.LogInformation(new EventDataItem(EventCodes.EntryAdded, null, "Blog post created: {0}", entry.Title));
276276
}
277277

@@ -375,11 +375,11 @@ public IActionResult CommentError(AddCommentViewModel comment, List<string> erro
375375
AllowComments = entry.AllowComments
376376
};
377377

378-
if(comment != null)
379-
lcvm.CurrentComment = comment;
378+
if (comment != null)
379+
lcvm.CurrentComment = comment;
380380
lpvm.Posts.First().Comments = lcvm;
381-
if(errors != null && errors.Count > 0 )
382-
lpvm.Posts.First().ErrorMessages = errors;
381+
if (errors != null && errors.Count > 0)
382+
lpvm.Posts.First().ErrorMessages = errors;
383383
}
384384
}
385385

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

402402
if (!ModelState.IsValid)
403403
{
@@ -410,30 +410,30 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
410410
}
411411

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

426-
if(dasBlogSettings.SiteConfiguration.EnableCaptcha)
427-
{
428-
var recaptchaTask = recaptcha.Validate(Request);
429-
recaptchaTask.Wait();
430-
var recaptchaResult = recaptchaTask.Result;
431-
if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
432-
recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore )
433-
{
434-
errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
435-
}
436-
}
426+
if (dasBlogSettings.SiteConfiguration.EnableCaptcha)
427+
{
428+
var recaptchaTask = recaptcha.Validate(Request);
429+
recaptchaTask.Wait();
430+
var recaptchaResult = recaptchaTask.Result;
431+
if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
432+
recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore)
433+
{
434+
errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
435+
}
436+
}
437437

438438
if (errors.Count > 0)
439439
{
@@ -446,7 +446,7 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
446446
commt.EntryId = Guid.NewGuid().ToString();
447447
commt.IsPublic = !dasBlogSettings.SiteConfiguration.CommentsRequireApproval;
448448
commt.CreatedUtc = commt.ModifiedUtc = DateTime.Now.ToUniversalTime();
449-
449+
450450
logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment CONTENT DUMP", commt.Content));
451451

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

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

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

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

602602
return View(post);
@@ -608,7 +608,7 @@ private IActionResult HandleImageUpload(PostViewModel post)
608608
var fileName = post.Image?.FileName;
609609
if (string.IsNullOrEmpty(fileName))
610610
{
611-
ModelState.AddModelError(nameof(post.Image),
611+
ModelState.AddModelError(nameof(post.Image),
612612
$"You must select a file before clicking \"{Constants.UploadImageAction}\" to upload it");
613613
return View(post);
614614
}
@@ -643,7 +643,7 @@ private void ValidatePostName(PostViewModel post)
643643
var dt = ValidatePostDate(post);
644644
var entry = blogManager.GetBlogPost(post.Title.Replace(" ", string.Empty), dt);
645645

646-
if (entry != null && string.Compare(entry.EntryId, post.EntryId, true) > 0 )
646+
if (entry != null && string.Compare(entry.EntryId, post.EntryId, true) > 0)
647647
{
648648
ModelState.AddModelError(string.Empty, "A post with this title already exists. Titles must be unique");
649649
}
@@ -680,6 +680,7 @@ private void BreakSiteCache()
680680
{
681681
memoryCache.Remove(CACHEKEY_RSS);
682682
memoryCache.Remove(CACHEKEY_FRONTPAGE);
683+
memoryCache.Remove(CACHEKEY_ARCHIVE);
683684
}
684685

685686
}

source/DasBlog.Web.UI/Controllers/DasBlogController.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ public abstract class DasBlogController : Controller
1313
{
1414
protected const string CACHEKEY_RSS = "CACHEKEY_RSS";
1515
protected const string CACHEKEY_FRONTPAGE = "CACHEKEY_FRONTPAGE";
16+
protected const string CACHEKEY_ARCHIVE = "CACHEKEY_ARCHIVE";
1617

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

2627
public virtual MemoryCacheEntryOptions SiteCacheSettings()

0 commit comments

Comments
 (0)