|
| 1 | +// Copyright (c) Source Tree Solutions, LLC. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using cloudscribe.Web.Navigation.Caching; |
| 5 | +using Microsoft.AspNetCore.Mvc; |
| 6 | +using Microsoft.AspNetCore.Mvc.Infrastructure; |
| 7 | +using Microsoft.AspNetCore.Mvc.Razor; |
| 8 | +using Microsoft.AspNetCore.Mvc.Routing; |
| 9 | +using Microsoft.AspNetCore.Mvc.ViewEngines; |
| 10 | +using Microsoft.AspNetCore.Mvc.ViewFeatures; |
| 11 | +using Microsoft.Extensions.Logging; |
| 12 | +using System; |
| 13 | +using System.Collections.Generic; |
| 14 | +using System.Threading.Tasks; |
| 15 | + |
| 16 | +namespace cloudscribe.Web.Navigation |
| 17 | +{ |
| 18 | + public class CachingNavigationViewComponent : ViewComponent |
| 19 | + { |
| 20 | + public CachingNavigationViewComponent( |
| 21 | + NavigationTreeBuilderService siteMapTreeBuilder, |
| 22 | + IEnumerable<INavigationNodePermissionResolver> permissionResolvers, |
| 23 | + IEnumerable<IFindCurrentNode> nodeFinders, |
| 24 | + IUrlHelperFactory urlHelperFactory, |
| 25 | + IActionContextAccessor actionContextAccesor, |
| 26 | + INodeUrlPrefixProvider prefixProvider, |
| 27 | + ILogger<NavigationViewComponent> logger, |
| 28 | + IDOMTreeCache DomCache, |
| 29 | + IRazorViewEngine viewEngine, |
| 30 | + NavViewRenderer viewRenderer, |
| 31 | + ITempDataProvider tempDataProvider) |
| 32 | + { |
| 33 | + _builder = siteMapTreeBuilder; |
| 34 | + _permissionResolvers = permissionResolvers; |
| 35 | + _nodeFinders = nodeFinders; |
| 36 | + _urlHelperFactory = urlHelperFactory; |
| 37 | + _actionContextAccesor = actionContextAccesor; |
| 38 | + _prefixProvider = prefixProvider; |
| 39 | + _log = logger; |
| 40 | + _domCache = DomCache; |
| 41 | + _viewEngine = viewEngine; |
| 42 | + _viewRenderer = viewRenderer; |
| 43 | + _tempDataProvider = tempDataProvider; |
| 44 | + } |
| 45 | + |
| 46 | + private ILogger _log; |
| 47 | + private readonly IDOMTreeCache _domCache; |
| 48 | + private readonly IRazorViewEngine _viewEngine; |
| 49 | + private readonly NavViewRenderer _viewRenderer; |
| 50 | + private readonly ITempDataProvider _tempDataProvider; |
| 51 | + private NavigationTreeBuilderService _builder; |
| 52 | + private IEnumerable<INavigationNodePermissionResolver> _permissionResolvers; |
| 53 | + private IEnumerable<IFindCurrentNode> _nodeFinders; |
| 54 | + private IUrlHelperFactory _urlHelperFactory; |
| 55 | + private IActionContextAccessor _actionContextAccesor; |
| 56 | + private INodeUrlPrefixProvider _prefixProvider; |
| 57 | + |
| 58 | + |
| 59 | + // intention here is not to re-compute the whole navigation DOM tree repeatedly |
| 60 | + // when you get a large number of unauthenticated page requests e.g. from a PWA |
| 61 | + // The main problem is clearing this cache again on new page creation etc |
| 62 | + // since .Net memory cache has no method for enumerating its keys - |
| 63 | + // you need to know the specific key name. |
| 64 | + // In a simplecontent system I'd probably need to use the IHandlePageCreated (etc) |
| 65 | + // hooks to clear a navcache of known name. |
| 66 | + |
| 67 | + public async Task<IViewComponentResult> InvokeAsync(string viewName, |
| 68 | + string filterName, |
| 69 | + string startingNodeKey, |
| 70 | + int expirationSeconds = 60, |
| 71 | + bool testMode = false) |
| 72 | + { |
| 73 | + NavigationViewModel model = null; |
| 74 | + |
| 75 | + string cacheKey = $"{viewName}_{filterName}_{startingNodeKey}"; |
| 76 | + |
| 77 | + // authenticated users - always do what the stadard version of this component does: |
| 78 | + // build the tree afresh |
| 79 | + if (User.Identity.IsAuthenticated) |
| 80 | + { |
| 81 | + // maybe kill cache key here under certain circumstances? |
| 82 | + // if(User.IsInRole("Administrators") || User.IsInRole("Content Administrators")) |
| 83 | + // { |
| 84 | + // // await _domCache.ClearDOMTreeCache(cacheKey); |
| 85 | + // } |
| 86 | + |
| 87 | + model = await CreateNavigationTree(filterName, startingNodeKey); |
| 88 | + return View(viewName, model); |
| 89 | + } |
| 90 | + else |
| 91 | + { |
| 92 | + var result = await _domCache.GetDOMTree(cacheKey); // use the viewname as the key in the cache |
| 93 | + |
| 94 | + if (string.IsNullOrEmpty(result)) |
| 95 | + { |
| 96 | + model = await CreateNavigationTree(filterName, startingNodeKey); |
| 97 | + |
| 98 | + ViewEngineResult viewResult = null; |
| 99 | + var actionContext = _actionContextAccesor.ActionContext; |
| 100 | + var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider); |
| 101 | + |
| 102 | + string fullViewName = $"Components/CachingNavigation/{viewName}"; |
| 103 | + try |
| 104 | + { |
| 105 | + // beware the 'IFeatureCollection has been disposed' System.ObjectDisposedException error here |
| 106 | + viewResult = _viewEngine.FindView(actionContext, fullViewName, true); |
| 107 | + } |
| 108 | + catch (Exception ex) |
| 109 | + { |
| 110 | + _log.LogError(ex, $"CachingNavigationViewComponent: Failed to search for View {fullViewName}"); |
| 111 | + } |
| 112 | + |
| 113 | + if (viewResult == null || !viewResult.Success || viewResult.View == null) |
| 114 | + { |
| 115 | + _log.LogError($"CachingNavigationViewComponent: Failed to find a matching view {fullViewName}"); |
| 116 | + } |
| 117 | + else |
| 118 | + { |
| 119 | + try |
| 120 | + { |
| 121 | + result = await _viewRenderer.RenderViewAsStringWithActionContext(fullViewName, |
| 122 | + model, |
| 123 | + viewResult, |
| 124 | + actionContext, |
| 125 | + tempData |
| 126 | + ); |
| 127 | + |
| 128 | + if (!string.IsNullOrEmpty(result)) |
| 129 | + { |
| 130 | + if(testMode) |
| 131 | + { |
| 132 | + await _domCache.StoreDOMTree(cacheKey, $"<h2>Cached copy from {cacheKey}</h2> {result}", expirationSeconds); |
| 133 | + } |
| 134 | + else |
| 135 | + { |
| 136 | + await _domCache.StoreDOMTree(cacheKey, result, expirationSeconds); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + _log.LogInformation($"CachingNavigationViewComponent: Rendered view successfully for {fullViewName}"); |
| 141 | + } |
| 142 | + catch (Exception ex) |
| 143 | + { |
| 144 | + _log.LogError(ex, $"CachingNavigationViewComponent: Failed to render view for {fullViewName}"); |
| 145 | + throw (ex); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + return View("CachedNav", result); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + /// <summary> |
| 154 | + /// The expensive thing... |
| 155 | + /// </summary> |
| 156 | + private async Task<NavigationViewModel> CreateNavigationTree(string filterName, string startingNodeKey) |
| 157 | + { |
| 158 | + var rootNode = await _builder.GetTree(); |
| 159 | + var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccesor.ActionContext); |
| 160 | + NavigationViewModel model = new NavigationViewModel( |
| 161 | + startingNodeKey, |
| 162 | + filterName, |
| 163 | + Request.HttpContext, |
| 164 | + urlHelper, |
| 165 | + rootNode, |
| 166 | + _permissionResolvers, |
| 167 | + _nodeFinders, |
| 168 | + _prefixProvider.GetPrefix(), |
| 169 | + _log); |
| 170 | + return model; |
| 171 | + } |
| 172 | + } |
| 173 | +} |
0 commit comments