public void Constructor_Exceptions () { HostFileChangeMonitor monitor; string relPath = Path.Combine ("relative", "file", "path"); var paths = new List<string> { relPath }; AssertExtensions.Throws<ArgumentException> (() => { monitor = new HostFileChangeMonitor (paths); }, "#A1"); paths.Clear (); paths.Add (null); AssertExtensions.Throws<ArgumentException> (() => { monitor = new HostFileChangeMonitor (paths); }, "#A2"); paths.Clear (); paths.Add (String.Empty); AssertExtensions.Throws<ArgumentException> (() => { monitor = new HostFileChangeMonitor (paths); }, "#A3"); AssertExtensions.Throws<ArgumentNullException> (() => { monitor = new HostFileChangeMonitor (null); }, "#A4"); paths.Clear (); AssertExtensions.Throws<ArgumentException> (() => { monitor = new HostFileChangeMonitor (paths); }, "#A5"); }
static CacheItemPolicy GetCacheItemPolicy() { var cachePolicy = new CacheItemPolicy() { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1)) }; var filePath = Path.Combine(Directory.GetCurrentDirectory(), "../../App.config"); var changeMonitor = new HostFileChangeMonitor(new string[] { filePath }); //changeMonitor.NotifyOnChanged(state => //{ // Console.WriteLine("Has Changed"); // cache.Add(filePath, File.ReadAllText(filePath), cachePolicy); //}); cachePolicy.ChangeMonitors.Add(changeMonitor); return cachePolicy; }
void InitForMemoryCache(bool isPublic, string[] filenamesArg, string[] cachekeysArg, CacheDependency dependency, DateTime utcStart) { bool dispose = true; try { MemCache memCache = HttpRuntime.CacheInternal as MemCache; _bits = new SafeBitVector32(0); _utcLastModified = DateTime.MinValue; IList<String> files = filenamesArg; IList<String> keys = cachekeysArg; if (dependency != null) { ReadOnlyCollection<string> filePaths = (dependency._fileChangeMonitor != null) ? dependency._fileChangeMonitor.FilePaths : null; ReadOnlyCollection<string> cacheKeys = (dependency._entryChangeMonitor != null) ? dependency._entryChangeMonitor.CacheKeys : null; if (filePaths != null || filenamesArg != null) { if (filePaths == null) { files = filenamesArg; } else if (filenamesArg == null) { files = filePaths; } else { files = new List<String>(filenamesArg.Length + filePaths.Count); foreach (string f in filenamesArg) { files.Add(f); } foreach (string f in filePaths) { files.Add(f); } } } if (cacheKeys != null || cachekeysArg != null) { if (cacheKeys == null) { keys = cachekeysArg; } else if (cachekeysArg == null) { keys = cacheKeys; } else { keys = new List<String>(cachekeysArg.Length + cacheKeys.Count); foreach (string f in cachekeysArg) { keys.Add(f); } foreach (string f in cacheKeys) { keys.Add(f); } } } } _fileChangeMonitor = (files != null) ? new HostFileChangeMonitor(files) : null; _entryChangeMonitor = (keys != null) ? memCache.CreateCacheEntryChangeMonitor(keys, isPublic) : null; string uniqueId = null; if (_fileChangeMonitor != null) { _utcLastModified = _fileChangeMonitor.LastModified.UtcDateTime; uniqueId = _fileChangeMonitor.UniqueId; _fileChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback)); } if (_entryChangeMonitor != null) { DateTime utcLastModified = _entryChangeMonitor.LastModified.UtcDateTime; if (utcLastModified > _utcLastModified) { _utcLastModified = utcLastModified; } uniqueId += _entryChangeMonitor.UniqueId; _entryChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback)); } _uniqueID = uniqueId; #if DBG _isUniqueIDInitialized = true; #endif // check if file has changed since the start time if (utcStart < DateTime.MaxValue) { if (_utcLastModified > utcStart && !(_utcLastModified - DateTime.UtcNow > FUTURE_FILETIME_BUFFER)) { // See VSWhidbey 400917 _bits[CHANGED] = true; } } _bits[BASE_INIT] = true; if (dependency != null && dependency._bits[CHANGED]) { _bits[CHANGED] = true; } if (_bits[WANTS_DISPOSE] || _bits[CHANGED]) { Debug.Trace("CacheDependencyInit", "WANTS_DISPOSE or CHANGED. InitForMemoryCache calling DisposeInternal"); DisposeInternal(); } dispose = false; } finally { if (dispose) { _bits[BASE_INIT] = true; Debug.Trace("CacheDependencyInit", "\n\nERROR in CacheDependency.InitForMemoryCache, calling DisposeInternal"); DisposeInternal(); } } }
static void Constructor_MissingFiles_Handler () { HostFileChangeMonitor monitor; PlatformID pid = Environment.OSVersion.Platform; bool runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); string missingFile = Path.Combine ("missing", "file", "path"); if (runningOnWindows) missingFile = "c:\\" + missingFile; else missingFile = "/" + missingFile; var paths = new List<string> { missingFile }; // Actually thrown by FileSystemWatcher constructor - note that the exception message suggests the file's // parent directory is being watched, not the file itself: // // MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles: // System.ArgumentException : The directory name c:\missing\file is invalid. // at System.IO.FileSystemWatcher..ctor(String path, String filter) // at System.IO.FileSystemWatcher..ctor(String path) // at System.Runtime.Caching.FileChangeNotificationSystem.System.Runtime.Caching.Hosting.IFileChangeNotificationSystem.StartMonitoring(String filePath, OnChangedCallback onChangedCallback, Object& state, DateTimeOffset& lastWriteTime, Int64& fileSize) // at System.Runtime.Caching.HostFileChangeMonitor.InitDisposableMembers() // at System.Runtime.Caching.HostFileChangeMonitor..ctor(IList`1 filePaths) // at MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles() in c:\users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\HostFileChangeMonitorTest.cs:line 68 AssertExtensions.Throws<ArgumentException> (() => { monitor = new HostFileChangeMonitor (paths); }, "#A1"); if (runningOnWindows) missingFile = "c:\\file.txt"; else missingFile = "/file.txt"; paths.Clear (); paths.Add (missingFile); monitor = new HostFileChangeMonitor (paths); Assert.AreEqual (1, monitor.FilePaths.Count, "#A2-1"); Assert.AreEqual (missingFile, monitor.FilePaths [0], "#A2-2"); Assert.AreEqual (missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A2-4"); paths.Add (missingFile); monitor = new HostFileChangeMonitor (paths); Assert.AreEqual (2, monitor.FilePaths.Count, "#A3-1"); Assert.AreEqual (missingFile, monitor.FilePaths [0], "#A3-2"); Assert.AreEqual (missingFile, monitor.FilePaths [1], "#A3-3"); Assert.AreEqual (missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A3-4"); }
public void UniqueId () { Tuple<string, string, string, IList<string>> setup = null; try { setup = SetupMonitoring (); FileInfo fi; var monitor = new HostFileChangeMonitor (setup.Item4); var sb = new StringBuilder (); fi = new FileInfo (setup.Item2); sb.AppendFormat ("{0}{1:X}{2:X}", setup.Item2, fi.LastWriteTimeUtc.Ticks, fi.Length); fi = new FileInfo (setup.Item3); sb.AppendFormat ("{0}{1:X}{2:X}", setup.Item3, fi.LastWriteTimeUtc.Ticks, fi.Length); Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A1"); var list = new List<string> (setup.Item4); list.Add (setup.Item1); monitor = new HostFileChangeMonitor (list); var di = new DirectoryInfo (setup.Item1); sb.AppendFormat ("{0}{1:X}{2:X}", setup.Item1, di.LastWriteTimeUtc.Ticks, -1L); Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A2"); list.Add (setup.Item1); monitor = new HostFileChangeMonitor (list); Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A3"); } finally { CleanupMonitoring (setup); } }
static void Dispose_NullState_NoStopMonitoring_Handler () { Tuple<string, string, string, IList<string>> setup = null; try { var tns = new TestNotificationSystem (); tns.UseNullState = true; ObjectCache.Host = tns; setup = SetupMonitoring (); var monitor = new HostFileChangeMonitor (setup.Item4); tns.FakeChanged (setup.Item2); Assert.IsFalse (tns.StopMonitoringCalled, "#A1-1"); Assert.AreEqual (0, tns.StopMonitoringCallCount, "#A1-2"); } finally { CleanupMonitoring (setup); } }
static void Constructor_Calls_StartMonitoring_Handler () { Tuple<string, string, string, IList<string>> setup = null; try { var tns = new TestNotificationSystem (); ObjectCache.Host = tns; setup = SetupMonitoring (); var monitor = new HostFileChangeMonitor (setup.Item4); Assert.IsTrue (tns.StartMonitoringCalled, "#A1-1"); Assert.AreEqual (2, tns.StartMonitoringCallCount, "#A1-2"); } finally { CleanupMonitoring (setup); } }
public void Constructor_Duplicates () { HostFileChangeMonitor monitor; PlatformID pid = Environment.OSVersion.Platform; bool runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); string missingFile = Path.Combine ("missing", "file", "path"); if (runningOnWindows) missingFile = "c:\\file.txt"; else missingFile = "/file.txt"; var paths = new List<string> { missingFile, missingFile }; // Just checks if it doesn't throw any exception for dupes monitor = new HostFileChangeMonitor (paths); }
/// <summary> /// 添加到缓存 /// </summary> /// <param name="value">被缓存的数据</param> /// <param name="cacheKey">缓存key</param> /// <param name="filePath">依赖缓存文件的绝对路径</param> public static void SetCache_M(this object value, string cacheKey, string dependency_filePath) { if (!File.Exists(dependency_filePath)) { throw new FileNotFoundException("缓存依赖文件不存在"); } ObjectCache cache = MemoryCache.Default; CacheItemPolicy policy = new CacheItemPolicy(); //缓存优先级别 policy.Priority = System.Runtime.Caching.CacheItemPriority.Default; cache.Set(cacheKey, value, policy); //设置监视对象 HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List<string>() { dependency_filePath }); //设置监视对象的回调操作 //依赖文件发生变化 即删除缓存 monitor.NotifyOnChanged(new OnChangedCallback(o => { RemoveCache_M(cacheKey); })); //添加到监视器 policy.ChangeMonitors.Add(monitor); }