Creating an Orchard CMS widget/module with caching enabled - caching

I have been searching high and low for this, but can't seem to find the right answer.
I have been writing a module in Orchard together with some widgets that I use for it, and now I want to enable caching of the database queries in my classes.
Is there any documentation on how to add caching to my modules and widgets?
I've tried to just enable the Output cache and the syscache, but it seems that it only works for the modules that came with Orchard (I checked with SQL Server Profiler, and my queries are still being sent all the time to the database, while the normal Orchard queries for content and such, are not, and seems to be cached).

You can use the ICacheManager.
Inject an instance of ICacheManager into your constructor and then in your method you can cache a value using:
var myCachedValue = _cacheManager.Get("My-Value-Cache-Key", ctx => {
ctx.Monitor(_clock.When(TimeSpan.FromMinutes(20)));
return SlowFunctionSoNeedsCaching();
});
I've written a more detailed example in my blog post: caching in Orchard.

Related

Caching options in ASP.NET Web API

Why doesn't Web API come with caching features like MVC actions?
Is it because these are HTTP based services so no state in between calls?
I have seen a few open sources like CacheCow and Strathweb, but not sure whom to pick and why?
What are the best and standard options for caching with ASP.NET Web API?
This is an extensive article that explains the principal options, and contains links to many more information:
EXPLORING WEB API 2 CACHING
It includes information about:
CacheCow, explained also in this article by Scott Hanselmman.
AspNetWebApi-OutputCache
Your own implementation
The poor man's implementation consist in:
implement a cache store that supports storing and retrieving values by key
generate a key from the request properties, like action parameters, method, headers, and so on, to generate a key
check if a value for that key is available in the cache store:
if it is available, return it
if it isn't generate it, store it and return it
var result = cacheStore.GetValue(keyFromRequest);
if (result == null)
{
result = MyClass.ExpensiveFunctionCall(params);
cacheStore.Store(keyFromRequest, result);
}
return result;
The cache store can be, for example, a database, a memory cache like MemoryCache class, or a Redis server.
The evolution of this idea is to use MVC action filters to make this cache cheking automatic, or to use a fully implemented solution like the aforementioned CacheCow

How can I log how long each ASP.NET WebAPI call takes?

Is there a way to attack some sort of global logger so that I know how long each WebAPI request took?
Yes, check out MiniProfiler.
It's got a lot of different adapters too- for example, I've used it with ServiceStack / Dapper, but it also works with MS vanilla WebApi / EF.
On localhost (or whatever criteria you use to turn the profiler on in your global app class), when you hit your site url's in the browser, you'll get a ui widget in the top right corner detailing total request time, serialization time, and database execution time (including the actual sql executed).
To view the last 100 requests, browse:
~/mini-profiler-resources/results
For more robust storage there are options here - sql server is supported out of the box. Use this create script and then set the storage provider for MiniProfiler:
MiniProfiler.Settings.Storage = new SqlServerStorage("..connectionstring...");
Or use Sqlite out of the box
You can even set multiple storage options.
Examples here
When adding the profiler ui to view requests, it should look something like this

Why is ServiceStack caching in Service, not FilterAttribute?

In MVC and most other service frameworks I tried, caching is done via attribute/filter, either on the controller/action or request, and can be controlled through caching profile in config file. It seems offer more flexibility and also leave the core service code cleaner.
But ServiceStack has it inside the service. Are there any reason why it's done this way?
Can I add a CacheFilterAttribute, but delegate to service instead?
ToOptimizedResultUsingCache(base.Cache,cacheKey,()=> {
// Delegate to Request/Service being decorated?
});
I searched around but couldn't find an answer. Granted, it probably won't make much difference because the ServiceStack caching via delegate method is quite clean. And you seldom change caching strategy on the fly in real world. So this is mostly out of curiosity. Thanks.
Because the caching pattern involves, checking first to see if it is cached, if not to then execute the service, populate the cache, then return the result.
A Request Filter doesn't allow you to execute the service and a Response Filter means that the Service will always execute (i.e. mitigating the usefulness of the Cache), so the alternative would require a Request + Response filter combination where the logic would be split into 2 disjointed parts. Having it inside the Service, lets you see and reason about how it works and what exactly is going on, it also allows full access to calculate the uniqueHashKey used and exactly what and when (or even if) to Cache, which is harder to control with a generic black-box caching solution.
Although we are open to 'baking-in' built-in generic caching solutions (either via an attribute or ServiceRunner / base class). Add a feature request if you'd like to see this, specifying the preferred functionality/use-case (e.g. cache based on Time / Validity / Cache against user-defined Aggregate root / etc).

Grails store and fetch data on client side

Background: We are using grails 2.1.1. We are not using any DB as of now. We make a web service call for each response on another server.
Now the problem is, there is web service call which returns some static data in XML form and this data is usable throughout the application. The size of the xml is around 40kb. This xml contains static data like, project_list, status_type_list etc. and we have to use this in various dropdowns and menu items in different gsp pages.
So, please suggest us the best way to handle this data. So that it doesn't effect our page load time and browsing experience. And also we can easily use the data on client side.
responding to your comment on the question. I would prefer using annotation based caching over the plugin, if the requirement is as simple as you state that it is.
If the calls are being made from server-side and you want to cache the results of the parsed XML then you can do something like:
#Cacheable("staticDataCache")
def getStaticDataFromXML() {}
You can then use the above method to pull the maps, lists whatever data structure you've used to store the result and it will pull it from the cache.
and then another service method to flush the cache, which you can call frequently from a Job.
#CacheFlush("staticDataCache")
def flushStaticDataCache() {}
Use the cache plugin to cache the static xml data. And then add some policy as to when the cache should be updated... (i.e. using a job to check if the xml has changed every hour)

couchdb public interface authentication through rewrites

I have a website set on a specific domain which is completely separated from my couchdb url through rewrites and virtual hosts, and I got to a point where I need to add some user authentication using _sessions API but I'm afraid I can't do it with rewrites:
{
"from": "auth",
"to": "../../../_session"
}
gives me:
{"error":"insecure_rewrite_rule","reason":"too many ../.. segments"}
which is acceptable, but now I'm wondering how would I get the session authentication to work from my domain without exposing couchdb url, and also, the session seems to be related to the domain so if I login through couchdb.example.com it won't work when using mywebsite.com as the public interface?
Thanks
PS. I've just found this post where there's an alternative by disabling secure_rewrites on the httpd config file, which seems to work, although, I was wondering that perhaps might be not a good approach and if is there something else which is ideal for this kind of problem.
I recommend to set secure_rewrites=false and don't worry about it.
We had a great discussion about CouchDB rewrites and security in the Iris Couch forum. Also see my post later about using Audit CouchDB. These are the highlights:
The secure_rewrites option is not the ultimate source of security for your data. At best, it is one layer in a multi-layer solution
The ultimate source of security is the _security object in the database. So that is where you should focus your attention
The Audit CouchDB tool scans every detail about your couch and it will tell you if any red-flags are present. It is implemented in Javascript so if you have NodeJS, you can run it; or simply reading the source code gives you an idea of what it is looking for.
If you are using vhost, than /_session handler is available at the vhost root without any rewrite rules (by default).
See the section [httpd] of default.ini:
vhost_global_handlers = _utils, _uuids, _session, _oauth, _users

Resources