ImageResizer  3.4.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events
Public Member Functions | Protected Member Functions | Protected Attributes | Properties | List of all members
ImageResizer.Plugins.DiskCache.DiskCache Class Reference

Provides methods for creating, maintaining, and securing the disk cache. More...

Inheritance diagram for ImageResizer.Plugins.DiskCache.DiskCache:
Inheritance graph
[legend]
Collaboration diagram for ImageResizer.Plugins.DiskCache.DiskCache:
Collaboration graph
[legend]

Public Member Functions

 DiskCache ()
 Creates a disk cache in the /imagecache folder More...
 
 DiskCache (string virtualDir)
 Creates a DiskCache instance at the specified location. Must be installed as a plugin to be operational. More...
 
void LoadSettings (Config c)
 Uses the defaults from the resizing.diskcache section in the specified configuration. Throws an invalid operation exception if the DiskCache is already started. More...
 
IPlugin Install (Config c)
 Loads the settings from 'c', starts the cache, and registers the plugin. Will throw an invalidoperationexception if already started. More...
 
bool Uninstall (Config c)
 Uninstalls the plugin. Should reverse all changes made during Install More...
 
bool IsConfigurationValid ()
 Returns true if the configured settings are valid and .NET (not NTFS) permissions will work. More...
 
bool Start ()
 Attempts to start the DiskCache using the current settings. Returns true if succesful or if already started. Returns false on a configuration error. Called by Install() More...
 
bool Stop ()
 Returns true if stopped succesfully. Cannot be restarted More...
 
bool CanProcess (HttpContext current, IResponseArgs e)
 Returns false if the cache is unable to process the request. If false, the caller should fall back to a different cache More...
 
void Process (HttpContext context, IResponseArgs e)
 Must update the cache if needed, then either rewrite, redirect or serve the cached data. More...
 
CacheResult Process (IResponseArgs e)
 
IEnumerable< IIssueGetIssues ()
 

Protected Member Functions

void BeforeSettingChanged ()
 Throws an exception if the class is already modified More...
 
bool HasFileIOPermission ()
 Returns true if .NET permissions allow writing to the cache directory. Does not check NTFS permissions. More...
 
bool HasNTFSPermission ()
 
string GetExecutingUser ()
 

Protected Attributes

int cacheAccessTimeout = 15000
 
string virtualDir = HostingEnvironment.ApplicationVirtualPath.TrimEnd('/') + "/imagecache"
 
ILogger log = null
 
CustomDiskCache cache = null
 
CleanupManager cleaner = null
 
WebConfigWriter writer = null
 
readonly object _startSync = new object()
 
volatile bool _started = false
 

Properties

int Subfolders [get, set]
 Controls how many subfolders to use for disk caching. Rounded to the next power of to. (1->2, 3->4, 5->8, 9->16, 17->32, 33->64, 65->128,129->256,etc.) NTFS does not handle more than 8,000 files per folder well. Larger folders also make cleanup more resource-intensive. Defaults to 32, which combined with the default setting of 400 images per folder, allows for scalability to 12,800 actively used image versions. For example, given a desired cache size of 100,000 items, this should be set to 256. More...
 
bool Enabled [get, set]
 Allows disk caching to be disabled for debuginng purposes. Defaults to true. More...
 
bool AutoClean [get, set]
 If true, items from the cache folder will be automatically 'garbage collected' if the cache size limits are exceeded. Defaults to false. More...
 
CleanupStrategy CleanupStrategy [get, set]
 Only relevant when AutoClean=true. Settings about how background cache cleanup are performed. It is best not to modify these settings. There are very complicated and non-obvious factors involved in their choice. More...
 
int CacheAccessTimeout [get, set]
 How many milliseconds to wait for a cached item to be available. Values below 0 are set to 0. Defaults to 15 seconds. Actual time spent waiting may be 2 or 3x this value, if multiple layers of synchronization require a wait. More...
 
bool HashModifiedDate [get, set]
 If true, when a source file is changed, a new file will be created instead of overwriting the old cached file. This helps prevent file lock contention on high-traffic servers. Defaults to true. Do NOT set this to false in a Web Garden or if you have overlapped recycle enabled, as you may risk having occasional failed requests due to write contention by separate proccesses. Changes the hash function, so you should delete the cache folder whenever this setting is modified. More...
 
bool AsyncWrites [get, set]
 If true, writes to the disk cache will be performed outside the request thread, allowing responses to return to the client quicker. More...
 
int AsyncBufferSize [get, set]
 If more than this amount of memory (in bytes) is currently allocated by queued writes, the request will be processed synchronously instead of asynchronously. More...
 
string VirtualCacheDir [get, set]
 Sets the location of the cache directory. Can be a virtual path (like /App/imagecache) or an application-relative path (like ~/imagecache, the default). Relative paths are assummed to be relative to the application root. All values are converted to virtual path format upon assignment (/App/imagecache) Will throw an InvalidOperationException if changed after the plugin is installed. More...
 
string PhysicalCacheDir [get]
 Returns the physical path of the cache directory specified in VirtualCacheDir. More...
 
ILogger Logger [get]
 
bool Started [get]
 Returns true if the DiskCache instance is operational. More...
 
- Properties inherited from ImageResizer.Configuration.Logging.ILoggerProvider
ILogger Logger [get]
 

Detailed Description

Provides methods for creating, maintaining, and securing the disk cache.

Definition at line 36 of file DiskCache.cs.

Constructor & Destructor Documentation

ImageResizer.Plugins.DiskCache.DiskCache.DiskCache ( )
inline

Creates a disk cache in the /imagecache folder

Definition at line 162 of file DiskCache.cs.

162 {}
ImageResizer.Plugins.DiskCache.DiskCache.DiskCache ( string  virtualDir)
inline

Creates a DiskCache instance at the specified location. Must be installed as a plugin to be operational.

Parameters
virtualDir

Definition at line 168 of file DiskCache.cs.

168  {
169  VirtualCacheDir = virtualDir;
170  }
string VirtualCacheDir
Sets the location of the cache directory. Can be a virtual path (like /App/imagecache) or an applicat...
Definition: DiskCache.cs:131

Member Function Documentation

void ImageResizer.Plugins.DiskCache.DiskCache.BeforeSettingChanged ( )
inlineprotected

Throws an exception if the class is already modified

Definition at line 155 of file DiskCache.cs.

155  {
156  if (_started) throw new InvalidOperationException("DiskCache settings may not be adjusted after it is started.");
157  }
bool ImageResizer.Plugins.DiskCache.DiskCache.CanProcess ( HttpContext  current,
IResponseArgs  e 
)
inline

Returns false if the cache is unable to process the request. If false, the caller should fall back to a different cache

Parameters
current
e

Implements ImageResizer.Caching.ICache.

Definition at line 288 of file DiskCache.cs.

288  {
289  //Disk caching will 'pass on' caching requests if 'cache=no'.
290  if (((ResizeSettings)e.RewrittenQuerystring).Cache == ServerCacheMode.No) return false;
291  return Started;//Add support for nocache
292  }
NameValueCollection RewrittenQuerystring
The rewritten querystring. Can be useful for caching systems that accept querystring arguments...
ServerCacheMode
When to disk cache the image
Definition: Enumerations.cs:36
bool Started
Returns true if the DiskCache instance is operational.
Definition: DiskCache.cs:249
bool ImageResizer.Plugins.DiskCache.DiskCache.HasFileIOPermission ( )
inlineprotected

Returns true if .NET permissions allow writing to the cache directory. Does not check NTFS permissions.

Returns

Definition at line 234 of file DiskCache.cs.

234  {
235  FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess,new string[]{PhysicalCacheDir, Path.Combine(PhysicalCacheDir,"web.config")});
236  return SecurityManager.IsGranted(writePermission);
237  }
string PhysicalCacheDir
Returns the physical path of the cache directory specified in VirtualCacheDir.
Definition: DiskCache.cs:145
IPlugin ImageResizer.Plugins.DiskCache.DiskCache.Install ( Config  c)
inline

Loads the settings from 'c', starts the cache, and registers the plugin. Will throw an invalidoperationexception if already started.

Parameters
c
Returns

Implements ImageResizer.Plugins.IPlugin.

Definition at line 195 of file DiskCache.cs.

195  {
196  if (c.get("diskcache.logging", false)) {
197  if (c.Plugins.LogManager != null)
198  log = c.Plugins.LogManager.GetLogger("ImageResizer.Plugins.DiskCache");
199  else
200  c.Plugins.LoggingAvailable += delegate(ILogManager mgr) {
201  if (log != null) log = c.Plugins.LogManager.GetLogger("ImageResizer.Plugins.DiskCache");
202  };
203  }
204  LoadSettings(c);
205  Start();
206  c.Pipeline.AuthorizeImage += Pipeline_AuthorizeImage;
207  c.Plugins.add_plugin(this);
208  return this;
209  }
ILogManager LogManager
Returns the most recently registered Logging plugin, or null.
bool Start()
Attempts to start the DiskCache using the current settings. Returns true if succesful or if already s...
Definition: DiskCache.cs:254
void LoadSettings(Config c)
Uses the defaults from the resizing.diskcache section in the specified configuration. Throws an invalid operation exception if the DiskCache is already started.
Definition: DiskCache.cs:175
PluginConfig Plugins
Access and modify plugins
Definition: Config.cs:85
bool ImageResizer.Plugins.DiskCache.DiskCache.IsConfigurationValid ( )
inline

Returns true if the configured settings are valid and .NET (not NTFS) permissions will work.

Returns

Definition at line 227 of file DiskCache.cs.

227  {
228  return !string.IsNullOrEmpty(VirtualCacheDir) && this.Enabled && HasFileIOPermission();
229  }
bool Enabled
Allows disk caching to be disabled for debuginng purposes. Defaults to true.
Definition: DiskCache.cs:54
string VirtualCacheDir
Sets the location of the cache directory. Can be a virtual path (like /App/imagecache) or an applicat...
Definition: DiskCache.cs:131
bool HasFileIOPermission()
Returns true if .NET permissions allow writing to the cache directory. Does not check NTFS permission...
Definition: DiskCache.cs:234
void ImageResizer.Plugins.DiskCache.DiskCache.LoadSettings ( Config  c)
inline

Uses the defaults from the resizing.diskcache section in the specified configuration. Throws an invalid operation exception if the DiskCache is already started.

Definition at line 175 of file DiskCache.cs.

175  {
176  Subfolders = c.get("diskcache.subfolders", Subfolders);
177  Enabled = c.get("diskcache.enabled", Enabled);
178  AutoClean = c.get("diskcache.autoClean", AutoClean);
179  VirtualCacheDir = c.get("diskcache.dir", VirtualCacheDir);
180  HashModifiedDate = c.get("diskcache.hashModifiedDate", HashModifiedDate);
181  CacheAccessTimeout = c.get("diskcache.cacheAccessTimeout", CacheAccessTimeout);
182  AsyncBufferSize = c.get("diskcache.asyncBufferSize", AsyncBufferSize);
183  AsyncWrites = c.get("diskcache.asyncWrites", AsyncWrites);
184  CleanupStrategy.LoadFrom(c.getNode("cleanupStrategy"));
185  }
bool AutoClean
If true, items from the cache folder will be automatically &#39;garbage collected&#39; if the cache size limi...
Definition: DiskCache.cs:65
bool Enabled
Allows disk caching to be disabled for debuginng purposes. Defaults to true.
Definition: DiskCache.cs:54
int CacheAccessTimeout
How many milliseconds to wait for a cached item to be available. Values below 0 are set to 0...
Definition: DiskCache.cs:85
bool HashModifiedDate
If true, when a source file is changed, a new file will be created instead of overwriting the old cac...
Definition: DiskCache.cs:98
string VirtualCacheDir
Sets the location of the cache directory. Can be a virtual path (like /App/imagecache) or an applicat...
Definition: DiskCache.cs:131
bool AsyncWrites
If true, writes to the disk cache will be performed outside the request thread, allowing responses to...
Definition: DiskCache.cs:107
int Subfolders
Controls how many subfolders to use for disk caching. Rounded to the next power of to...
Definition: DiskCache.cs:45
int AsyncBufferSize
If more than this amount of memory (in bytes) is currently allocated by queued writes, the request will be processed synchronously instead of asynchronously.
Definition: DiskCache.cs:117
void ImageResizer.Plugins.DiskCache.DiskCache.Process ( HttpContext  current,
IResponseArgs  e 
)
inline

Must update the cache if needed, then either rewrite, redirect or serve the cached data.

Parameters
current
e

Implements ImageResizer.Caching.ICache.

Definition at line 295 of file DiskCache.cs.

295  {
296 
297  CacheResult r = Process(e);
298  context.Items["FinalCachedFile"] = r.PhysicalPath;
299 
300  if (r.Data == null) {
301 
302  //Calculate the virtual path
303  string virtualPath = VirtualCacheDir.TrimEnd('/') + '/' + r.RelativePath.Replace('\\', '/').TrimStart('/');
304 
305  //Rewrite to cached, resized image.
306  context.RewritePath(virtualPath, false);
307  } else {
308  //Remap the response args writer to use the existing stream.
309  ((ResponseArgs)e).ResizeImageToStream = delegate(Stream s) {
310  ((MemoryStream)r.Data).WriteTo(s);
311  };
312  context.RemapHandler(new NoCacheHandler(e));
313  }
314  }
void Process(HttpContext context, IResponseArgs e)
Must update the cache if needed, then either rewrite, redirect or serve the cached data...
Definition: DiskCache.cs:295
Implements IHttpHandler, serves content for the NoCache plugin
IResponseArgs implementation
Definition: ResponseArgs.cs:12
bool ImageResizer.Plugins.DiskCache.DiskCache.Start ( )
inline

Attempts to start the DiskCache using the current settings. Returns true if succesful or if already started. Returns false on a configuration error. Called by Install()

Definition at line 254 of file DiskCache.cs.

254  {
255  if (!IsConfigurationValid()) return false;
256  lock (_startSync) {
257  if (_started) return true;
258  if (!IsConfigurationValid()) return false;
259 
260  //Init the writer.
261  writer = new WebConfigWriter(this,PhysicalCacheDir);
262  //Init the inner cache
263  cache = new CustomDiskCache(this, PhysicalCacheDir, Subfolders, HashModifiedDate,AsyncBufferSize);
264  //Init the cleanup strategy
265  if (AutoClean && cleanupStrategy == null) cleanupStrategy = new CleanupStrategy(); //Default settings if null
266  //Init the cleanup worker
267  if (AutoClean) cleaner = new CleanupManager(this, cache, cleanupStrategy);
268  //If we're running with subfolders, enqueue the cache root for cleanup (after the 5 minute delay)
269  //so we don't eternally 'skip' files in the root or in other unused subfolders (since only 'accessed' subfolders are ever cleaned ).
270  if (cleaner != null) cleaner.CleanAll();
271 
272  if (log != null) log.Info("DiskCache started successfully.");
273  //Started successfully
274  _started = true;
275  return true;
276  }
277  }
bool AutoClean
If true, items from the cache folder will be automatically &#39;garbage collected&#39; if the cache size limi...
Definition: DiskCache.cs:65
string PhysicalCacheDir
Returns the physical path of the cache directory specified in VirtualCacheDir.
Definition: DiskCache.cs:145
bool HashModifiedDate
If true, when a source file is changed, a new file will be created instead of overwriting the old cac...
Definition: DiskCache.cs:98
int Subfolders
Controls how many subfolders to use for disk caching. Rounded to the next power of to...
Definition: DiskCache.cs:45
bool IsConfigurationValid()
Returns true if the configured settings are valid and .NET (not NTFS) permissions will work...
Definition: DiskCache.cs:227
CleanupStrategy CleanupStrategy
Only relevant when AutoClean=true. Settings about how background cache cleanup are performed...
Definition: DiskCache.cs:74
int AsyncBufferSize
If more than this amount of memory (in bytes) is currently allocated by queued writes, the request will be processed synchronously instead of asynchronously.
Definition: DiskCache.cs:117
bool ImageResizer.Plugins.DiskCache.DiskCache.Stop ( )
inline

Returns true if stopped succesfully. Cannot be restarted

Returns

Definition at line 282 of file DiskCache.cs.

282  {
283  if (cleaner != null) cleaner.Dispose();
284  cleaner = null;
285  return true;
286  }
bool ImageResizer.Plugins.DiskCache.DiskCache.Uninstall ( Config  c)
inline

Uninstalls the plugin. Should reverse all changes made during Install

Parameters
c
Returns

Implements ImageResizer.Plugins.IPlugin.

Definition at line 216 of file DiskCache.cs.

216  {
217  c.Plugins.remove_plugin(this);
218  c.Pipeline.AuthorizeImage -= Pipeline_AuthorizeImage;
219  return this.Stop();
220  }

Property Documentation

int ImageResizer.Plugins.DiskCache.DiskCache.AsyncBufferSize
getset

If more than this amount of memory (in bytes) is currently allocated by queued writes, the request will be processed synchronously instead of asynchronously.

Definition at line 117 of file DiskCache.cs.

bool ImageResizer.Plugins.DiskCache.DiskCache.AsyncWrites
getset

If true, writes to the disk cache will be performed outside the request thread, allowing responses to return to the client quicker.

Definition at line 107 of file DiskCache.cs.

bool ImageResizer.Plugins.DiskCache.DiskCache.AutoClean
getset

If true, items from the cache folder will be automatically 'garbage collected' if the cache size limits are exceeded. Defaults to false.

Definition at line 65 of file DiskCache.cs.

int ImageResizer.Plugins.DiskCache.DiskCache.CacheAccessTimeout
getset

How many milliseconds to wait for a cached item to be available. Values below 0 are set to 0. Defaults to 15 seconds. Actual time spent waiting may be 2 or 3x this value, if multiple layers of synchronization require a wait.

Definition at line 85 of file DiskCache.cs.

CleanupStrategy ImageResizer.Plugins.DiskCache.DiskCache.CleanupStrategy
getset

Only relevant when AutoClean=true. Settings about how background cache cleanup are performed. It is best not to modify these settings. There are very complicated and non-obvious factors involved in their choice.

Definition at line 74 of file DiskCache.cs.

bool ImageResizer.Plugins.DiskCache.DiskCache.Enabled
getset

Allows disk caching to be disabled for debuginng purposes. Defaults to true.

Definition at line 54 of file DiskCache.cs.

bool ImageResizer.Plugins.DiskCache.DiskCache.HashModifiedDate
getset

If true, when a source file is changed, a new file will be created instead of overwriting the old cached file. This helps prevent file lock contention on high-traffic servers. Defaults to true. Do NOT set this to false in a Web Garden or if you have overlapped recycle enabled, as you may risk having occasional failed requests due to write contention by separate proccesses. Changes the hash function, so you should delete the cache folder whenever this setting is modified.

Definition at line 98 of file DiskCache.cs.

string ImageResizer.Plugins.DiskCache.DiskCache.PhysicalCacheDir
get

Returns the physical path of the cache directory specified in VirtualCacheDir.

Definition at line 145 of file DiskCache.cs.

bool ImageResizer.Plugins.DiskCache.DiskCache.Started
get

Returns true if the DiskCache instance is operational.

Definition at line 249 of file DiskCache.cs.

int ImageResizer.Plugins.DiskCache.DiskCache.Subfolders
getset

Controls how many subfolders to use for disk caching. Rounded to the next power of to. (1->2, 3->4, 5->8, 9->16, 17->32, 33->64, 65->128,129->256,etc.) NTFS does not handle more than 8,000 files per folder well. Larger folders also make cleanup more resource-intensive. Defaults to 32, which combined with the default setting of 400 images per folder, allows for scalability to 12,800 actively used image versions. For example, given a desired cache size of 100,000 items, this should be set to 256.

Definition at line 45 of file DiskCache.cs.

string ImageResizer.Plugins.DiskCache.DiskCache.VirtualCacheDir
getset

Sets the location of the cache directory. Can be a virtual path (like /App/imagecache) or an application-relative path (like ~/imagecache, the default). Relative paths are assummed to be relative to the application root. All values are converted to virtual path format upon assignment (/App/imagecache) Will throw an InvalidOperationException if changed after the plugin is installed.

Definition at line 131 of file DiskCache.cs.


The documentation for this class was generated from the following file: