// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // // // Represents an in memory collection of keys and values whose operations are concurrent. // // -------------------------------------------------------------------------------------------------------------------- namespace ImageProcessor.Web.Caching { using System.Collections.Generic; using System.IO; using System.Runtime.Caching; /// /// Represents an in memory collection of keys and values whose operations are concurrent. /// internal static class CacheIndexer { #region Public /// /// Gets the associated with the specified key. /// /// /// The cached path of the value to get. /// /// /// The matching the given key if the contains an element with /// the specified key; otherwise, null. /// public static CachedImage GetValue(string cachedPath) { string key = Path.GetFileNameWithoutExtension(cachedPath); CachedImage cachedImage = (CachedImage)MemCache.GetItem(key); if (cachedImage == null) { // FileInfo is thread safe. FileInfo fileInfo = new FileInfo(cachedPath); if (!fileInfo.Exists) { return null; } // Pull the latest info. fileInfo.Refresh(); cachedImage = new CachedImage { Key = Path.GetFileNameWithoutExtension(cachedPath), Path = cachedPath, CreationTimeUtc = fileInfo.CreationTimeUtc }; Add(cachedImage); } return cachedImage; } /// /// Removes the value associated with the specified key. /// /// /// The key of the item to remove. /// /// /// true if the removes an element with /// the specified key; otherwise, false. /// public static bool Remove(string cachedPath) { string key = Path.GetFileNameWithoutExtension(cachedPath); return MemCache.RemoveItem(key); } /// /// Adds the specified key and value to the dictionary or returns the value if it exists. /// /// /// The cached image to add. /// /// /// The value of the item to add or get. /// public static CachedImage Add(CachedImage cachedImage) { // Add the CachedImage. CacheItemPolicy policy = new CacheItemPolicy(); policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List { cachedImage.Path })); MemCache.AddItem(cachedImage.Key, cachedImage, policy); return cachedImage; } #endregion } }