Flushing the templatecache programatically - caching

we have some sites running Umbraco9, where we have a few templates that are updated by outside developers. We are hooking up to an FTP and downloading their templates (.cshtml), and in backend their editors can choose from these templates to be inserted in a partial.
var setting = JsonConvert.DeserializeObject<CustomTemplateSettings>(Model.Value); // Getting the settings
thetemplate = setting.templateName;// Getting the selected template
showContent = _service.TemplateExists(thetemplate, forcereload);// Checking the selected template exists (physically), possibly downloading it to server
thetemplate = "/Views/CustomViews/" + thetemplate; // creating the path to the template
//Calling template - with some data
<partial name="#thetemplate" model="Model as ContentStructureField" />
Everything is great.... until they want to update their templates. Umbraco has them cached, and I need to either recycle App or hit save on a random Document Type in settings.
I have tried different things, like using #Html.Partial, #Html.CachedPartialAsync, using the tag. I cannot find a way to affect the lifespan or refresh the content of the partial
All googling results in explanations on how to cache specific content. And most Umbraco 9 specific documentation seems to have been lost with the emerging of version 10/11
I need some way to refresh the cache like when saving Document Templates. I do not care about the momentary effect on website performance, as the updates can be planned by the external developers to be non-peak hours.
Thanks in advance

Cannot figure out how to delete the question....
Turned out, that I had constructed the path to the template with a double slash ("/Views/CustomViews//TemplateName.cshtml")
While rendering engine did manage to handle this error and show the content apparently the cache did then not properly subscribe to changes to the file and kept the cached version, requiring a complete flush. Fixing the error in the path made the issue go away.

Related

How to prevent browser from loading the old source

Edit : I don't know if it actually loads from cache, so I can't create the question named "prevent from loading cache".
Problem : Browsers sometimes save my code and keep loading only the code they saved(Maybe it saves in the cache). When this problem occurs, browser is like caching the old code and won't change anything. This is to say, It won't load any new code I updated.
Information: This occurs in HTML, CSS, Javascript on all browsers. I am using Apache in XAMPP as an appserv.
Deleting cache in all browsers won't fix this.
My first way to stop this is to delete the file, refresh browser and replace it.
The second ways is changing the pathname.
After the fix, the problem will occur again at anytime :(, so I would like to know how to prevent this.
Edited: If possible, please explain for newbie because I am very young beginner.
Try adding a variable like current timestamp to each url in its query string.
Just use querystring e.g. http://www.domain.com/style.css?version=1 for first version.
Now you update the stylesheet and you would like to reflact changes to all users browser who have cached version of old stylesheet. for this just change version querystring value to 1.1
e.g. http://www.domain.com/style.css?version=1.1
This works for javascript, css and all other files called in by your html page.
Also for all files like html, css, js, you can eTag header. More information can be found here.
http://www.w3.org/2005/MWI/BPWG/techs/CachingWithETag.html

tx_news, manipulate DB, cache issue

We use the tx_news 2.3.0 (not the newest version! - right now not possible to update..) and there is a strange bug, that does not publish news when Publish Date is set (or better, it publish them days later).
As a work around I created a small script and run it with a cronjob:
UPDATE `tx_news_domain_model_news` SET `datetime` = `starttime`, `starttime` = 0 WHERE `starttime` <>0 and `starttime` < UNIX_TIMESTAMP()
Basicly it sets the Date & Time field = Publish Date and clears the Publish Date field if that is older then now. This workaround did a good job until we enabled some caches.
Now there is a problem that sometimes the new published article does not show up in the frontend in a news listview plugin. After Flush frontend caches it is there. But sometimes it works without clear the cache. And sometimes when not clearing the cache the article is there after some hours.
I do not want to disable the cache for the site with the news listview plugin on it.
So what would be the best way to handle this? Is there a way to only clear the cache for the tx_news plugin? Maybe even better only for a specific site or news folder? Maybe direct via the database?
Any ideas?
Edit: If I am right the cache should be deleted automaticly when you change something in the news article. As I do it via DB the cache is not deleted for this articles. So I tested it, I run the script, see that the articles are not published, go to backend, open onen one of this article and saved it (without any change), and after that all articles are published.
Maybe there is a way to simulate that?
I found a solution:
As I manipulate the database directly the cache system does not know about this change. So if you save an article after this change the cachesystem delete the entries for this site (and only for this site).
To force the cache to create a new cacheentry for this site I can manipulate the table cf_cache_pagesection and set the expires field to 1 (that means this cache entry is expired. I use the following SQl for it:
update `cf_cache_pagesection` set expires = 1 where identifier like '44_%'
(the page I want to change got the uid 44, that is used in the identifier)

Kentico Output Caching issue - content couldn't get updated

I am working with a Kentico site and I have a problem with page output caching.
We have a custom webpart which loads the records from a Bizform's record data and displays those data in a page. The problem is that after giving it several tries, we couldn't figure out the problem why the webpart couldn't get the latest data from the bizfrom data and we suspect it was because of output caching.
We tried to:
Disable webpart output caching in webpart configuration
Disable page output caching in CMSDesk > General > Output Caching
Disable site output caching in Settings > System > Performance
Disable IIS cache for both User-mode and Kernel cache
Create cache dependencies for cms.form|byid| touched key (which I found is not supported in current kentico version)
And going to try create event handler to add touched key on bizform insert event
We encounter a similar problem with Shopping Cart Mini Preview Webpart with Ecommerce.CurrentContext.CurrentShoppingCart which returns different result for service handler (.ashx - gets updated) and for webpart (.ascx - does not get updated)
If you ever experienced these problems, please help.
The last place where it could be cached is the content cache. It can be set either in Settings->System->Performance or at the web part level under System settings section.
Only web parts that utilize the content caching have this section available. (E.g. some repeaters and data source web parts.) It might be a little bit confusing because then there are two sections (System settings and Performance) where you can influence caching. However the Performance section is used to set up the Partial output cache.
Anyway, you should definitely try to check Cache debug to see what is actually cached.
Additional resources:
Deep dive – Kentico CMS Caching
New in 5.5: Caching API changes
Deep dive: Cache dependencies
Kentico caching and cache dependencies explained
ASP.NET Caching Dependencies
I have faced issue similar to second one (with Shopping Cart Mini Preview Webpart) recently. Only web service (.asmx) was used instead of HTTP handler. In my case issue was solved by setting the EnableSession property of WebMethod attribute to true for all the CRUD webservice methods.
[System.Web.Services.WebMethod(EnableSession = true)]
So I think the matter is that handler should be able to access current Session.
In case of HTTP handler you could try to add IRequiresSessionState on the handler declaration to attach it with the session.
I am also using Kentico 8, I see that your Kentico version is older. That might also have impact but I am not sure about that.

How to force the browser to show the most up to date files instead of relying on application cache?

It's very important for the website I'm working on to be offline-functional. I'm using a Cache Manifest to store all the files on the application cache, so that takes care of that and all is good and well.
BUT, as I read and noticed myself, the browser first shows the cached version of the site before checking for an update online. Hitting refresh reloads the cache again, with the new cached files this time (or what it had time to update for the swift refreshers).
I'm aware of this fix : http://www.html5rocks.com/en/tutorials/appcache/beginner/, where the user is told an update is available and is asked to refresh the page. Not a bad method, but still sketchy for user experience.
Is there any other way to force the browser to show the most up to date files if online? Would cache busting all files manually AND using a cache manifest fix this problem, or will it conflict with the cache manifest and cause problem to the offline functionality?
I found something that works well for me:
The URL linking to the web page contains a parameter. If there is ever a change to the page or related files, the url is changed to something like this: http:/ /www.mywebsite.com/mypage.html?v=3 where v=3 is changed depending on updates.
This is a longer fix to implement (finding every page affected by a change & changing all their cache busting links), but the pages at least show what they're supposed to on the first load and the cache manifest still load the update for offline viewing.

Clearing IIS Cache from MVC3 App

I need to clear the IIS cache on my server. The exact reason is detailed below; but the reason doesn't matter. I'm 100% sure that this is the solution I need; as detailed below, I have used the process of elimination to determine that this is, indeed, the problem I'm facing, and the solution I need.
I have an MVC3 app that's themeable (skinnable architecture). Think of it as Wordpress; users can develop a theme, download it, and activate it on their site. The theme controls exactly the final HTML output. This is an over-simplification, since I provide an API with useful functions to be consumed by themes.
Anyway, users can change the theme of the site. The theme is currently stored in a static variable. When a view page is rendered, the name of the theme determines the location of the layout file (which contains references to the CSS files, etc.) and the view files. The theme is a setting that persists in the DB.
For example, if I have a theme called "Foo", then when requesting the /Admin page, I might use /Themes/Foo/Admin.cshtml. If I have another theme called "Bar" which does not have that file, then for /Admin it might request /Themes/Bar/Generic.cshtml as the layout.
The problem is that changing a theme means that every single page on the site is outdated. This means that any sites cached on IIS7 will show the old theme; this is incorrect. I need them to show the new theme.
Anyway, IIS7 uses caching by default. I need essentially a way to clear the cache when a user changes the theme. Currently, this is not happening, and users continue to see the old theme until the cache (somehow) expires itself.
I am not using output caching, or any other form of explicit caching; this is a "vanilla" ASP.NET MVC3 application from a caching perspective (i.e. I didn't add/configure any caching). IIS7 has its own default caching. I know this, because if I disable output caching in IIS7 for my Site, I will always see the correct theme after a change.
How can I flush the cache? Other SO questions point to using Cache.blah, and I tried using HttpContext.Current but that is null during tests (using VS test tool) -- because the ASP.NET pipeline is not used in full.
To explain, in an integration test, I basically:
Go to localhost/Test/
Log in (submit values into the forms)
Change the theme by browsing to the right page and clicking the right link
Request another page
See if the theme changed (based on the layout/css file name).
This is all done by code; I use a C# port of HtmlUnit, and along with deploying my app to /Test in IIS, I can essentially browse it like an end user.
Currently, this test passes around 50% of the time. The problem is that IIS is caching the results, and I can't cleanly reliably reset the cache on the server-side.
Again, I'm not talking about clearing the session or the user-side cache; IIS itself is the culprit guilty of caching my application. Nor do I want to completely disable the cache via the IIS settings, a) because I can't force people who install my application to do that, and b) because caching is good.
So how can I force flushing the cache on the server?
For example, I tried programatically touching web.config; this works, but recycles my application pool, and so, kills my static variables; every request means reloading all the static vars from the DB, which kills my performance.
As you requested I have amended this post:
You can use output cache, you say that the selected theme is stored in the database ( like settings for the site ) Well I would add another column with say a GUID and then use this as the varybycustom value.
Your global.asax file will be able to run code:
void Page_Init() {
///code here to get the GUIDforthissitestheme
var outputCacheSettings = new OutputCacheParameters() {
Duration = Int32.MaxValue, //think its maxvalue
VaryByCustom = GUIDforthissitestheme
};
InitOutputCache(outputCacheSettings);
}
At least here you will have output cache, but also every change of theme, changes the GUID so therefore changes the cache and then your page should be new.
I did something like this on a site that listed products, and when the products database was updated the key would be changed, however I can't find what site I implemented it and I work on a hell of a lot of sites.
hope this helps
Set up 'Cache Rule' in 'Output caching' feature with 'File Cache Monitoring' set to 'Using file change notification'. Then 'touch' the files theme change affects, from .net code you could do:
System.IO.File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
The issues you are describing sound a lot like a client side caching issue. Have you checked this with a HTTP Proxy like Fiddler to verify if this is getting cached on the client?
If you are seeing HTTP 304's after a template change you may want to try configuring IIS (or your site template) to disable client side caching.
I dont think the approach mentioned for themes is correct.
If we are using STATIC variables , then it will affect all the users and all the pages.(Which is certainly not required.)
We can think of two approaches,
Use theme name in url and make it as a prat if RouteData. So the url "http://myHost/BLUE/.." will return in BLUE theme and "http://myHost/RED/.." will return in RED theme. If user will change theme then url will be updated.
The problem with above approach is next time user browse, it will load default theme.
So better approach will be save theme as a part of user preference. Once user logged in read the theme from DB and set the RouteData value.
Just touch web.config. That's the easiest and most reliable way. Flushing the application pool programmatically is overkill.
If you have a problem finding out where web.config is in a test environment (since System.Web.HttpRequest.Current is null, and similar for Server), you can always use an app.config file to point out the location.
Again, there's no other easy way to do it; even disabling output caching, as mentioned in the question, is hard to do through web.config alone.

Resources