aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.BL/ObservablesContextInMemoryCache.cs
blob: 39e6d7d9a2ec6ba089808cc5c497dc9a58cb72a5 (plain)
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
using EFCache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.BL
{
    public class ObservablesContextInMemoryCache : ICache
    {
        private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>();
        private readonly Dictionary<string, HashSet<string>> _entitySetToKey = new Dictionary<string, HashSet<string>>();

        public TimeSpan Expiration { get; set; }
        public bool ResetAccessTimeOnAccess { get; set; }

        public bool GetItem(string key, out object value)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            value = null;

            lock (_cache)
            {
                var now = DateTimeOffset.Now;

                CacheEntry entry;
                if (_cache.TryGetValue(key, out entry))
                {
                    if (EntryExpired(entry, now))
                    {
                        InvalidateItem(key);
                    }
                    else
                    {
                        if (ResetAccessTimeOnAccess)
                        {
                            entry.LastAccess = now;
                        }
                        value = entry.Value;
                        return true;
                    }
                }
            }

            return false;
        }

        public void PutItem(string key, object value, IEnumerable<string> dependentEntitySets, TimeSpan slidingExpiration, DateTimeOffset absoluteExpiration)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (dependentEntitySets == null)
            {
                throw new ArgumentNullException("dependentEntitySets");
            }

            lock (_cache)
            {
                var entitySets = dependentEntitySets.ToArray();

                _cache[key] = new CacheEntry(value, entitySets, slidingExpiration, absoluteExpiration);

                foreach (var entitySet in entitySets)
                {
                    HashSet<string> keys;

                    if (!_entitySetToKey.TryGetValue(entitySet, out keys))
                    {
                        keys = new HashSet<string>();
                        _entitySetToKey[entitySet] = keys;
                    }

                    keys.Add(key);
                }
            }
        }

        public void InvalidateSets(IEnumerable<string> entitySets)
        {
            if (entitySets == null)
            {
                throw new ArgumentNullException("entitySets");
            }

            lock (_cache)
            {
                var itemsToInvalidate = new HashSet<string>();

                foreach (var entitySet in entitySets)
                {
                    HashSet<string> keys;

                    if (_entitySetToKey.TryGetValue(entitySet, out keys))
                    {
                        itemsToInvalidate.UnionWith(keys);

                        _entitySetToKey.Remove(entitySet);
                    }
                }

                foreach (var key in itemsToInvalidate)
                {
                    InvalidateItem(key);
                }
            }
        }

        public void InvalidateItem(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            lock (_cache)
            {
                CacheEntry entry;

                if (_cache.TryGetValue(key, out entry))
                {
                    _cache.Remove(key);

                    foreach (var set in entry.EntitySets)
                    {
                        HashSet<string> keys;
                        if (_entitySetToKey.TryGetValue(set, out keys))
                        {
                            keys.Remove(key);
                        }
                    }
                }
            }
        }

        public void Purge()
        {
            Purge(false);
        }

        public void Purge(bool removeUnexpiredItems)
        {
            lock (_cache)
            {
                var now = DateTimeOffset.Now;
                var itemsToRemove = new HashSet<string>();

                foreach (var item in _cache)
                {
                    if (removeUnexpiredItems || EntryExpired(item.Value, now))
                    {
                        itemsToRemove.Add(item.Key);
                    }
                }

                foreach (var key in itemsToRemove)
                {
                    InvalidateItem(key);
                }
            }
        }

        public int Count
        {
            get { return _cache.Count; }
        }

        private bool EntryExpired(CacheEntry entry, DateTimeOffset now)
        {
            return entry.AbsoluteExpiration < now || (now - entry.LastAccess) > Expiration;
        }

        private class CacheEntry
        {
            private readonly object _value;
            private readonly string[] _entitySets;
            private readonly TimeSpan _slidingExpiration;
            private readonly DateTimeOffset _absoluteExpiration;
            private readonly DateTime _created;

            public CacheEntry(object value, string[] entitySets, TimeSpan slidingExpiration,
                DateTimeOffset absoluteExpiration)
            {
                _value = value;
                _entitySets = entitySets;
                _slidingExpiration = slidingExpiration;
                _absoluteExpiration = absoluteExpiration;
                LastAccess = DateTimeOffset.Now;
            }

            public object Value
            {
                get { return _value; }
            }

            public string[] EntitySets
            {
                get { return _entitySets; }
            }

            public TimeSpan SlidingExpiration
            {
                get { return _slidingExpiration; }
            }

            public DateTimeOffset AbsoluteExpiration
            {
                get { return _absoluteExpiration; }
            }

            public DateTimeOffset LastAccess { get; set; }
        }
    }
}
n">LightMagentaOutput)); RaisePropertyChanged(nameof(YellowOutput)); RaisePropertyChanged(nameof(LightYellowOutput)); RaisePropertyChanged(nameof(BlackOutput)); } private double GetVolumeLiquidType(LiquidTypes liquidType) { if (JobBrushStop != null && JobBrushStop.Dispensers != null && JobBrushStop.Dispensers.Count > 0) { var lt = JobBrushStop.Dispensers.FirstOrDefault(x => x.DispenserLiquidType == (DispenserLiquidType)liquidType); if (lt != null) { return Math.Round(lt.Volume, 2); } } return 0; } #endregion #region Override Methods /// <summary> /// Called when the application has been started. /// </summary> public override void OnApplicationStarted() { MachineProvider.MachineOperator.PrintingStarted += MachineOperator_PrintingStarted; MachineProvider.MachineOperator.PrintingEnded += MachineOperator_PrintingEnded; } /// <summary> /// Called when the navigation system has navigated to this VM view. /// </summary> public override void OnNavigatedTo() { base.OnNavigatedTo(); IsDisplayJobOutline = false; if (_handler != null && !_handler.Status.IsFailed) { _stop_job_btn.Push(); } } #endregion #region Event Handlers private void _stop_job_btn_Pressed() { if (_handler != null) { _handler.Cancel(); IsDyeingProcess = false; } } /// <summary> /// Handles the PrintingStarted event of the MachineOperator. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="PrintingEventArgs"/> instance containing the event data.</param> private void MachineOperator_PrintingStarted(object sender, PrintingEventArgs e) { _handler = e.JobHandler; Job = e.Job; e.JobHandler.StatusChanged += JobHandler_StatusChanged; e.JobHandler.SpoolChangeRequired += JobHandler_SpoolChangeRequired; e.JobHandler.Stopped += JobHandler_Stopped; e.JobHandler.CanCancelChanged += JobHandler_CanCancelChanged; _stop_job_btn.Push(); _stop_job_btn.IsEnabled = true; } private void MachineOperator_PrintingEnded(object sender, PrintingEventArgs e) { LogManager.Log("Printing ended, popping job stop button..."); if (_stop_job_btn != null) { _stop_job_btn.Pop(); } else { LogManager.Log("Job stop button instance was null!", LogCategory.Warning); } } /// <summary> /// Handles the SpoolChangeRequired event of the JobHandler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="SpoolChangeRequiredEventArgs"/> instance containing the event data.</param> private void JobHandler_SpoolChangeRequired(object sender, SpoolChangeRequiredEventArgs e) { InvokeUI(async () => { if ((await NotificationProvider.ShowDialog(new SpoolChangeViewVM(e))).DialogResult) { e.Confirm(); } else { e.Abort(); } }); } /// <summary> /// Handles the Stopped event of the JobHandler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void JobHandler_Stopped(object sender, EventArgs e) { if (_handler != null) { _handler.StatusChanged -= JobHandler_StatusChanged; _handler.SpoolChangeRequired -= JobHandler_SpoolChangeRequired; _handler.Stopped -= JobHandler_Stopped; _handler.CanCancelChanged -= JobHandler_CanCancelChanged; IsDyeingProcess = false; } } /// <summary> /// Handles the JobHandler StatusChanged event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private void JobHandler_StatusChanged(object sender, RunningJobStatus e) { InvokeUI(() => { RunningJobStatus = e; IsDyeingProcess = (RunningJobStatus != null && RunningJobStatus.CurrentSegment != null); if (RunningJobStatus != null && RunningJobStatus.CurrentSegment != null) { if (_runningJobStatus.CurrentSegment.IsInterSegment) { CurrentBrushStop = _runningJobStatus.CurrentSegment.BrushStops.FirstOrDefault(); JobBrushStop = null; } else { var realsegmIndex = 1; if (Job.EnableInterSegment && Job.InterSegmentLength > 0) { int segmentIndex = _runningJobStatus.CurrentSegment.SegmentIndex - (Job.EffectiveSegments.Count * RunningJobStatus.CurrentUnit); if (RunningJobStatus.CurrentUnit > 0) { segmentIndex -= RunningJobStatus.CurrentUnit;// inter segment between units } realsegmIndex = (int)(segmentIndex / 2) + 1; } else { realsegmIndex = Math.Max(_runningJobStatus.CurrentSegment.SegmentIndex - (Job.Segments.Count * RunningJobStatus.CurrentUnit), 0); } var segment = Job.Segments.FirstOrDefault(x => x.SegmentIndex == realsegmIndex); if (segment != null) { if (_handler.JobTicket.Segments.Count > 0) { JobBrushStop = _handler.JobTicket.Segments[Job.OrderedSegments.IndexOf(segment)].BrushStops.First(); } } CurrentBrushStop = RunningJobStatus.CurrentSegment.FirstBrushStop; } } }); } /// <summary> /// Handles the CanCancelChanged event of the JobHandler control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void JobHandler_CanCancelChanged(object sender, EventArgs e) { _stop_job_btn.IsEnabled = _handler.CanCancel; } #endregion } }