File: Cache.cs

package info (click to toggle)
mono 2.6.7-5.1%2Bdeb6u2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 327,392 kB
  • ctags: 413,647
  • sloc: cs: 2,472,296; xml: 1,768,594; ansic: 350,669; sh: 13,676; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (446 lines) | stat: -rw-r--r-- 11,898 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//
// System.Web.Caching.Cache
//
// Author(s):
//  Lluis Sanchez (lluis@ximian.com)
//
// (C) 2005 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Threading;
using System.Collections;
using System.Security.Permissions;
#if NET_2_0
using System.Collections.Generic;
#endif

namespace System.Web.Caching
{
	// CAS - no InheritanceDemand here as the class is sealed
	[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	public sealed class Cache: IEnumerable
	{
#if NET_2_0
		Dictionary <string, CacheItem> cache;
#else
		Hashtable cache;
#endif
		Cache dependencyCache;
		public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
		public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
		
		public Cache ()
		{
#if NET_2_0
			cache = new Dictionary <string, CacheItem> ();
#else
			cache = new Hashtable ();
#endif
		}
		
		public int Count {
			get { return cache.Count; }
		}
		
		public object this [string key] {
			get { return Get (key); }
			set { Insert (key, value); }
		}
		
		public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
		{
			if (key == null)
				throw new ArgumentNullException ("key");

			lock (cache) {
				CacheItem it;

#if NET_2_0
				cache.TryGetValue (key, out it);
#else
				it = (CacheItem) cache [key];
#endif
				if (it != null)
					return it.Value;
				Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, false);
			}
			return null;
		}
		
		public object Get (string key)
		{
			lock (cache) {
				CacheItem it;
#if NET_2_0
				if (!cache.TryGetValue (key, out it))
					return null;
#else
				it = (CacheItem) cache [key];
				if (it == null)
					return null;
#endif
				
				if (it.Dependency != null && it.Dependency.HasChanged) {
					Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false);
					return null;
				}

				if (it.SlidingExpiration != NoSlidingExpiration) {
					it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
					// Cast to long is ok since we know that sliding expiration
					// is less than 365 days (31536000000ms)
					it.Timer.Change ((long)it.SlidingExpiration.TotalMilliseconds, Timeout.Infinite);
				} else if (DateTime.Now >= it.AbsoluteExpiration) {
					Remove (key, CacheItemRemovedReason.Expired, false);
					return null;
				}

				return it.Value;
			}
		}
		
		public void Insert (string key, object value)
		{
			Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
		}
		
		public void Insert (string key, object value, CacheDependency dependencies)
		{
			Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
		}
		
		public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
		{
			Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, true);
		}
		
		public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
				    CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
		{
			Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, onRemoveCallback, true);
		}

		void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
			     CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, bool doLock)
		{
			if (key == null)
				throw new ArgumentNullException ("key");
			if (value == null)
				throw new ArgumentNullException ("value");
			if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
				throw new ArgumentNullException ("slidingExpiration");
			if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
				throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
				
			CacheItem ci = new CacheItem ();
			ci.Value = value;
			ci.Key = key;
			
			if (dependencies != null) {
				ci.Dependency = dependencies;
				dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
				dependencies.SetCache (DependencyCache);
			}

			ci.Priority = priority;
			SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, key, doLock);
		}
		
		internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
		{
			CacheItem ci = null;

			try {
				if (doLock)
					Monitor.Enter (cache);
#if NET_2_0
				cache.TryGetValue (key, out ci);
#else
				ci = (CacheItem) cache [key];
#endif

				if (ci != null)
					SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, false);
			} finally {
				if (doLock)
					Monitor.Exit (cache);
			}
		}

		void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback,
				     string key, bool doLock)
		{
			ci.SlidingExpiration = slidingExpiration;
			if (slidingExpiration != NoSlidingExpiration)
				ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
			else
				ci.AbsoluteExpiration = absoluteExpiration;			

			ci.OnRemoveCallback = onRemoveCallback;
			
			try {
				if (doLock)
					Monitor.Enter (cache);
				
				if (ci.Timer != null) {
					ci.Timer.Dispose ();
					ci.Timer = null;
				}

				if (key != null)
					cache [key] = ci;
				
				ci.LastChange = DateTime.Now;
				if (ci.AbsoluteExpiration != NoAbsoluteExpiration) {
					long remaining = Math.Max (0, (long)(ci.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
					if (remaining > 4294967294L)
						// Maximum due time for timer
						// Item will expire properly anyway, as the timer will be
						// rescheduled for the item's expiration time once that item is
						// bubbled to the top of the priority queue.
						remaining = 4294967294L;
					ci.Timer = new Timer (new TimerCallback (ItemExpired), ci, remaining, Timeout.Infinite);
				}
			} finally {
				if (doLock)
					Monitor.Exit (cache);
			}
		}
		
		public object Remove (string key)
		{
			return Remove (key, CacheItemRemovedReason.Removed, true);
		}
		
		object Remove (string key, CacheItemRemovedReason reason, bool doLock)
		{
			CacheItem it = null;

			try {
				if (doLock)
					Monitor.Enter (cache);
#if NET_2_0
				cache.TryGetValue (key, out it);
#else
				it = (CacheItem) cache [key];
#endif
				cache.Remove (key);
			} finally {
				if (doLock)
					Monitor.Exit (cache);
			}

			if (it != null) {
				Timer t = it.Timer;
				if (t != null)
					t.Dispose ();
				
				if (it.Dependency != null) {
#if NET_2_0
					it.Dependency.SetCache (null);
#endif
					it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
					it.Dependency.Dispose ();
				}
				if (it.OnRemoveCallback != null) {
					try {
						it.OnRemoveCallback (key, it.Value, reason);
					} catch {
						//TODO: anything to be done here?
					}
				}
				return it.Value;
			} else
				return null;
		}

		// Used when shutting down the application so that
		// session_end events are sent for all sessions.
		internal void InvokePrivateCallbacks ()
		{
			CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
			lock (cache) {
				foreach (string key in cache.Keys) {
					CacheItem item;
#if NET_2_0
					cache.TryGetValue (key, out item);
#else
					item = (CacheItem) cache [key];
#endif

					if (item != null && item.OnRemoveCallback != null) {
						try {
							item.OnRemoveCallback (key, item.Value, reason);
						} catch {
							//TODO: anything to be done here?
						}
					}
				}
			}
		}

		public IDictionaryEnumerator GetEnumerator ()
		{
			ArrayList list = new ArrayList ();
			lock (cache) {
#if NET_2_0
				foreach (CacheItem it in cache.Values)
					list.Add (it);
#else
				list.AddRange (cache.Values);
#endif
			}
			return new CacheItemEnumerator (list);
		}
		
		IEnumerator IEnumerable.GetEnumerator ()
		{
			return GetEnumerator ();
		}
		
		void OnDependencyChanged (object o, EventArgs a)
		{
			CheckDependencies ();
		}
		
		void ItemExpired(object cacheItem) {
			CacheItem ci = (CacheItem)cacheItem;
			long remaining = Math.Max (0, (long)(ci.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
			if (remaining > 4294967294L)
				remaining = 4294967294L;

			if (remaining <= 0) {
				ci.Timer.Dispose();
				ci.Timer = null;

				Remove (ci.Key, CacheItemRemovedReason.Expired, true);
			}

			ci.Timer.Change (remaining, Timeout.Infinite);
		}
		
		internal void CheckDependencies ()
		{
			ArrayList list;
			lock (cache) {
				list = new ArrayList ();
#if NET_2_0
				foreach (CacheItem it in cache.Values)
					list.Add (it);
#else
				list.AddRange (cache.Values);
#endif
			
				foreach (CacheItem it in list) {
					if (it.Dependency != null && it.Dependency.HasChanged)
						Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false);
				}
			}
		}
		
		internal DateTime GetKeyLastChange (string key)
		{
			lock (cache) {
				CacheItem it;
#if NET_2_0
				if (!cache.TryGetValue (key, out it))
					return DateTime.MaxValue;
#else
				it = (CacheItem) cache [key];
#endif
				if (it == null)
					return DateTime.MaxValue;
				
				return it.LastChange;
			}
		}

		internal Cache DependencyCache {
			get {
				if (dependencyCache == null)
					return this;

				return dependencyCache;
			}
			set { dependencyCache = value; }
		}
	}

	sealed class CacheItem
	{
		public object Value;
		public string Key;
		public CacheDependency Dependency;
		public DateTime AbsoluteExpiration;
		public TimeSpan SlidingExpiration;
		public CacheItemPriority Priority;
		public CacheItemRemovedCallback OnRemoveCallback;
		public DateTime LastChange;
		public Timer Timer;
	}
		
	sealed class CacheItemEnumerator: IDictionaryEnumerator
	{
		ArrayList list;
		int pos = -1;
		
		public CacheItemEnumerator (ArrayList list)
		{
			this.list = list;
		}
		
		CacheItem Item {
			get {
				if (pos < 0 || pos >= list.Count)
					throw new InvalidOperationException ();
				return (CacheItem) list [pos];
			}
		}
		
		public DictionaryEntry Entry {
			get { return new DictionaryEntry (Item.Key, Item.Value); }
		}
		
		public object Key {
			get { return Item.Key; }
		}
		
		public object Value {
			get { return Item.Value; }
		}
		
		public object Current {
			get { return Entry; }
		}
		
		public bool MoveNext ()
		{
			return (++pos < list.Count);
		}
		
		public void Reset ()
		{
			pos = -1;
		}
	}
}