SmartAPI
Open Source .NET RQL library for RedDot CMS / OpenText WSM Management Server
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Pages
CachedList.cs
Go to the documentation of this file.
1 ï»¿// SmartAPI - .Net programmatic access to RedDot servers
2 //
3 // Copyright (C) 2013 erminas GbR
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free Software Foundation,
7 // either version 3 of the License, or (at your option) any later version.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 // See the GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License along with this program.
14 // If not, see <http://www.gnu.org/licenses/>.
15 
16 using System;
17 using System.Collections;
18 using System.Collections.Generic;
19 
20 namespace erminas.SmartAPI.Utils.CachedCollections
21 {
22  public class CachedList<T> : ICachedList<T> where T : class
23  {
24  private bool _isCachingEnabled;
25 
26  public CachedList(Func<List<T>> retrieveFunc, Caching caching)
27  {
28  RetrieveFunc = retrieveFunc;
29  _isCachingEnabled = caching == Caching.Enabled;
30  }
31 
32  protected CachedList(Caching caching)
33  {
34  _isCachingEnabled = caching == Caching.Enabled;
35  }
36 
37  public int Count
38  {
39  get
40  {
41  EnsureListIsLoaded();
42  return List.Count;
43  }
44  }
45 
46  public T GetByPosition(int pos)
47  {
48  EnsureListIsLoaded();
49  return List[pos];
50  }
51 
52  public IEnumerator<T> GetEnumerator()
53  {
54  EnsureListIsLoaded();
55  return List.GetEnumerator();
56  }
57 
58  public virtual void InvalidateCache()
59  {
60  List = null;
61  }
62 
63  public virtual bool IsCachingEnabled
64  {
65  get { return _isCachingEnabled; }
66  set { _isCachingEnabled = value; }
67  }
68 
69  public void Refresh()
70  {
71  InvalidateCache();
72  if (IsCachingEnabled)
73  {
74  EnsureListIsLoaded();
75  }
76  }
77 
78  public ICachedList<T> Refreshed()
79  {
80  Refresh();
81  return this;
82  }
83 
84  public void WaitFor(Predicate<ICachedList<T>> predicate, TimeSpan wait, TimeSpan retryPeriod)
85  {
86  Wait.For(() => predicate(Refreshed()), wait, retryPeriod);
87  }
88 
89  protected void EnsureListIsLoaded()
90  {
91  if (IsCachingEnabled && List != null)
92  {
93  return;
94  }
95 
96  List = RetrieveFunc();
97  }
98 
99  protected virtual List<T> List { get; set; }
100  protected Func<List<T>> RetrieveFunc { private get; set; }
101 
102  IEnumerator IEnumerable.GetEnumerator()
103  {
104  EnsureListIsLoaded();
105  return List.GetEnumerator();
106  }
107  }
108 
109  public enum Caching
110  {
111  Enabled,
112  Disabled
113  }
114 }