File: ExecutionPropertyManager.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (666 lines) | stat: -rw-r--r-- 23,846 bytes parent folder | download | duplicates (7)
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.Activities.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime;
    using System.Runtime.Serialization;

    [DataContract]
    class ExecutionPropertyManager
    {
        ActivityInstance owningInstance;

        Dictionary<string, ExecutionProperty> properties;

        // Since the ExecutionProperty objects in this list
        // could exist in several places we need to make sure
        // that we clean up any booleans before more work items run
        List<ExecutionProperty> threadProperties;
        bool ownsThreadPropertiesList;

        string lastPropertyName;
        object lastProperty;
        IdSpace lastPropertyVisibility;

        // used by the root activity instance to chain parents correctly
        ExecutionPropertyManager rootPropertyManager;

        int exclusiveHandleCount;

        public ExecutionPropertyManager(ActivityInstance owningInstance)
        {
            Fx.Assert(owningInstance != null, "null instance should be using the internal host-based ctor");
            this.owningInstance = owningInstance;

            // This object is only constructed if we know we have properties to add to it
            this.properties = new Dictionary<string, ExecutionProperty>();

            if (owningInstance.HasChildren)
            {
                ActivityInstance previousOwner = owningInstance.PropertyManager != null ? owningInstance.PropertyManager.owningInstance : null;

                // we're setting a handle property. Walk the children and associate the new property manager
                // then walk our instance list, fixup parent references, and perform basic validation
                ActivityUtilities.ProcessActivityInstanceTree(owningInstance, null, (instance, executor) => AttachPropertyManager(instance, previousOwner));
            }
            else
            {
                owningInstance.PropertyManager = this;
            }
        }

        public ExecutionPropertyManager(ActivityInstance owningInstance, ExecutionPropertyManager parentPropertyManager)
            : this(owningInstance)
        {
            Fx.Assert(parentPropertyManager != null, "caller must verify");
            this.threadProperties = parentPropertyManager.threadProperties;

            // if our parent is null, capture any root properties
            if (owningInstance.Parent == null)
            {
                this.rootPropertyManager = parentPropertyManager.rootPropertyManager;
            }
        }

        internal ExecutionPropertyManager(ActivityInstance owningInstance, Dictionary<string, ExecutionProperty> properties)
        {
            Fx.Assert(properties != null, "properties should never be null");
            this.owningInstance = owningInstance;
            this.properties = properties;

            // owningInstance can be null (for host-provided root properties)
            if (owningInstance == null)
            {
                this.rootPropertyManager = this;
            }
        }

        [DataMember(EmitDefaultValue = false, Name = "properties")]
        internal Dictionary<string, ExecutionProperty> SerializedProperties
        {
            get { return this.properties; }
            set { this.properties = value; }
        }

        [DataMember(EmitDefaultValue = false, Name = "exclusiveHandleCount")]
        internal int SerializedExclusiveHandleCount
        {
            get { return this.exclusiveHandleCount; }
            set { this.exclusiveHandleCount = value; }
        }

        internal Dictionary<string, ExecutionProperty> Properties
        {
            get
            {
                return this.properties;
            }
        }

        internal bool HasExclusiveHandlesInScope
        {
            get
            {
                return this.exclusiveHandleCount > 0;
            }
        }

        bool AttachPropertyManager(ActivityInstance instance, ActivityInstance previousOwner)
        {
            if (instance.PropertyManager == null || instance.PropertyManager.owningInstance == previousOwner)
            {
                instance.PropertyManager = this;
                return true;
            }
            else
            {
                return false;
            }
        }

        public object GetProperty(string name, IdSpace currentIdSpace)
        {
            Fx.Assert(!string.IsNullOrEmpty(name), "The name should be validated by the caller.");

            if (lastPropertyName == name && (this.lastPropertyVisibility == null || this.lastPropertyVisibility == currentIdSpace))
            {
                return lastProperty;
            }

            ExecutionPropertyManager currentManager = this;

            while (currentManager != null)
            {
                ExecutionProperty property;
                if (currentManager.properties.TryGetValue(name, out property))
                {
                    if (!property.IsRemoved && (!property.HasRestrictedVisibility || property.Visibility == currentIdSpace))
                    {
                        this.lastPropertyName = name;
                        this.lastProperty = property.Property;
                        this.lastPropertyVisibility = property.Visibility;

                        return this.lastProperty;
                    }
                }

                currentManager = GetParent(currentManager);
            }

            return null;
        }

        void AddProperties(IDictionary<string, ExecutionProperty> properties, IDictionary<string, object> flattenedProperties, IdSpace currentIdSpace)
        {
            foreach (KeyValuePair<string, ExecutionProperty> item in properties)
            {
                if (!item.Value.IsRemoved && !flattenedProperties.ContainsKey(item.Key) && (!item.Value.HasRestrictedVisibility || item.Value.Visibility == currentIdSpace))
                {
                    flattenedProperties.Add(item.Key, item.Value.Property);
                }
            }
        }

        public IEnumerable<KeyValuePair<string, object>> GetFlattenedProperties(IdSpace currentIdSpace)
        {
            ExecutionPropertyManager currentManager = this;
            Dictionary<string, object> flattenedProperties = new Dictionary<string, object>();
            while (currentManager != null)
            {
                AddProperties(currentManager.Properties, flattenedProperties, currentIdSpace);
                currentManager = GetParent(currentManager);
            }
            return flattenedProperties;
        }

        //Currently this is only used for the exclusive scope processing
        internal List<T> FindAll<T>() where T : class
        {
            ExecutionPropertyManager currentManager = this;
            List<T> list = null;

            while (currentManager != null)
            {
                foreach (ExecutionProperty property in currentManager.Properties.Values)
                {
                    if (property.Property is T)
                    {
                        if (list == null)
                        {
                            list = new List<T>();
                        }
                        list.Add((T)property.Property);
                    }
                }

                currentManager = GetParent(currentManager);
            }

            return list;
        }

        static ExecutionPropertyManager GetParent(ExecutionPropertyManager currentManager)
        {
            if (currentManager.owningInstance != null)
            {
                if (currentManager.owningInstance.Parent != null)
                {
                    return currentManager.owningInstance.Parent.PropertyManager;
                }
                else
                {
                    return currentManager.rootPropertyManager;
                }
            }
            else
            {
                return null;
            }
        }

        public void Add(string name, object property, IdSpace visibility)
        {
            Fx.Assert(!string.IsNullOrEmpty(name), "The name should be validated before calling this collection.");
            Fx.Assert(property != null, "The property should be validated before caling this collection.");

            ExecutionProperty executionProperty = new ExecutionProperty(name, property, visibility);
            this.properties.Add(name, executionProperty);

            if (this.lastPropertyName == name)
            {
                this.lastProperty = property;
            }

            if (property is ExclusiveHandle)
            {
                this.exclusiveHandleCount++;

                UpdateChildExclusiveHandleCounts(1);
            }

            if (property is IExecutionProperty)
            {
                AddIExecutionProperty(executionProperty, false);
            }
        }

        void UpdateChildExclusiveHandleCounts(int amountToUpdate)
        {
            Queue<HybridCollection<ActivityInstance>> toProcess = null;

            HybridCollection<ActivityInstance> children = this.owningInstance.GetRawChildren();

            if (children != null && children.Count > 0)
            {
                ProcessChildrenForExclusiveHandles(children, amountToUpdate, ref toProcess);

                if (toProcess != null)
                {
                    while (toProcess.Count > 0)
                    {
                        children = toProcess.Dequeue();
                        ProcessChildrenForExclusiveHandles(children, amountToUpdate, ref toProcess);
                    }
                }
            }
        }

        void ProcessChildrenForExclusiveHandles(HybridCollection<ActivityInstance> children, int amountToUpdate, ref Queue<HybridCollection<ActivityInstance>> toProcess)
        {
            for (int i = 0; i < children.Count; i++)
            {
                ActivityInstance child = children[i];

                ExecutionPropertyManager childManager = child.PropertyManager;

                if (childManager.IsOwner(child))
                {
                    childManager.exclusiveHandleCount += amountToUpdate;
                }

                HybridCollection<ActivityInstance> tempChildren = child.GetRawChildren();

                if (tempChildren != null && tempChildren.Count > 0)
                {
                    if (toProcess == null)
                    {
                        toProcess = new Queue<HybridCollection<ActivityInstance>>();
                    }

                    toProcess.Enqueue(tempChildren);
                }
            }
        }

        void AddIExecutionProperty(ExecutionProperty property, bool isDeserializationFixup)
        {
            bool willCleanupBeCalled = !isDeserializationFixup;

            if (this.threadProperties == null)
            {
                this.threadProperties = new List<ExecutionProperty>(1);
                this.ownsThreadPropertiesList = true;
            }
            else if (!this.ownsThreadPropertiesList)
            {
                List<ExecutionProperty> updatedProperties = new List<ExecutionProperty>(this.threadProperties.Count);

                // We need to copy all properties to our new list and we
                // need to mark hidden properties as "to be removed" (or just
                // not copy them on the deserialization path)
                for (int i = 0; i < this.threadProperties.Count; i++)
                {
                    ExecutionProperty currentProperty = this.threadProperties[i];

                    if (currentProperty.Name == property.Name)
                    {
                        if (willCleanupBeCalled)
                        {
                            currentProperty.ShouldBeRemovedAfterCleanup = true;
                            updatedProperties.Add(currentProperty);
                        }

                        // If cleanup won't be called then we are on the
                        // deserialization path and shouldn't copy this
                        // property over to our new list
                    }
                    else
                    {
                        updatedProperties.Add(currentProperty);
                    }
                }

                this.threadProperties = updatedProperties;
                this.ownsThreadPropertiesList = true;
            }
            else
            {
                for (int i = this.threadProperties.Count - 1; i >= 0; i--)
                {
                    ExecutionProperty currentProperty = this.threadProperties[i];

                    if (currentProperty.Name == property.Name)
                    {
                        if (willCleanupBeCalled)
                        {
                            currentProperty.ShouldBeRemovedAfterCleanup = true;
                        }
                        else
                        {
                            this.threadProperties.RemoveAt(i);
                        }

                        // There will only be at most one property in this list that
                        // matches the name
                        break;
                    }
                }
            }

            property.ShouldSkipNextCleanup = willCleanupBeCalled;
            this.threadProperties.Add(property);
        }

        public void Remove(string name)
        {
            Fx.Assert(!string.IsNullOrEmpty(name), "This should have been validated by the caller.");

            ExecutionProperty executionProperty = this.properties[name];

            Fx.Assert(executionProperty != null, "This should only be called if we know the property exists");

            if (executionProperty.Property is IExecutionProperty)
            {
                Fx.Assert(this.ownsThreadPropertiesList && this.threadProperties != null, "We should definitely be the list owner if we have an IExecutionProperty");

                if (!this.threadProperties.Remove(executionProperty))
                {
                    Fx.Assert("We should have had this property in the list.");
                }
            }

            this.properties.Remove(name);

            if (executionProperty.Property is ExclusiveHandle)
            {
                this.exclusiveHandleCount--;

                UpdateChildExclusiveHandleCounts(-1);
            }

            if (this.lastPropertyName == name)
            {
                this.lastPropertyName = null;
                this.lastProperty = null;
            }
        }

        public object GetPropertyAtCurrentScope(string name)
        {
            Fx.Assert(!string.IsNullOrEmpty(name), "This should be validated elsewhere");

            ExecutionProperty property;
            if (this.properties.TryGetValue(name, out property))
            {
                return property.Property;
            }

            return null;
        }

        public bool IsOwner(ActivityInstance instance)
        {
            return this.owningInstance == instance;
        }

        [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode, Justification = "Called from Serialization")]
        internal bool ShouldSerialize(ActivityInstance instance)
        {
            return IsOwner(instance) && this.properties.Count > 0;
        }

        public void SetupWorkflowThread()
        {
            if (this.threadProperties != null)
            {
                for (int i = 0; i < this.threadProperties.Count; i++)
                {
                    ExecutionProperty executionProperty = this.threadProperties[i];
                    executionProperty.ShouldSkipNextCleanup = false;
                    IExecutionProperty property = (IExecutionProperty)executionProperty.Property;

                    property.SetupWorkflowThread();
                }
            }
        }

        // This method only throws fatal exceptions
        public void CleanupWorkflowThread(ref Exception abortException)
        {
            if (this.threadProperties != null)
            {
                for (int i = this.threadProperties.Count - 1; i >= 0; i--)
                {
                    ExecutionProperty current = this.threadProperties[i];

                    if (current.ShouldSkipNextCleanup)
                    {
                        current.ShouldSkipNextCleanup = false;
                    }
                    else
                    {
                        IExecutionProperty property = (IExecutionProperty)current.Property;

                        try
                        {
                            property.CleanupWorkflowThread();
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e))
                            {
                                throw;
                            }

                            abortException = e;
                        }
                    }

                    if (current.ShouldBeRemovedAfterCleanup)
                    {
                        this.threadProperties.RemoveAt(i);
                        current.ShouldBeRemovedAfterCleanup = false;
                    }
                }
            }
        }

        public void UnregisterProperties(ActivityInstance completedInstance, IdSpace currentIdSpace)
        {
            UnregisterProperties(completedInstance, currentIdSpace, false);
        }

        public void UnregisterProperties(ActivityInstance completedInstance, IdSpace currentIdSpace, bool ignoreExceptions)
        {
            if (IsOwner(completedInstance))
            {
                RegistrationContext registrationContext = new RegistrationContext(this, currentIdSpace);

                foreach (ExecutionProperty property in this.properties.Values)
                {
                    // We do a soft removal because we're about to throw away this dictionary
                    // and we don't want to mess up our enumerator
                    property.IsRemoved = true;

                    IPropertyRegistrationCallback registrationCallback = property.Property as IPropertyRegistrationCallback;

                    if (registrationCallback != null)
                    {
                        try
                        {
                            registrationCallback.Unregister(registrationContext);
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e) || !ignoreExceptions)
                            {
                                throw;
                            }
                        }
                    }
                }

                Fx.Assert(completedInstance == null || completedInstance.GetRawChildren() == null || completedInstance.GetRawChildren().Count == 0, "There must not be any children at this point otherwise our exclusive handle count would be incorrect.");

                // We still need to clear this list in case any non-serializable
                // properties were being used in a no persist zone
                this.properties.Clear();
            }
        }

        public void ThrowIfAlreadyDefined(string name, ActivityInstance executingInstance)
        {
            if (executingInstance == this.owningInstance)
            {
                if (this.properties.ContainsKey(name))
                {
                    throw FxTrace.Exception.Argument("name", SR.ExecutionPropertyAlreadyDefined(name));
                }
            }
        }

        public void OnDeserialized(ActivityInstance owner, ActivityInstance parent, IdSpace visibility, ActivityExecutor executor)
        {
            this.owningInstance = owner;

            if (parent != null)
            {
                if (parent.PropertyManager != null)
                {
                    this.threadProperties = parent.PropertyManager.threadProperties;
                }
            }
            else
            {
                this.rootPropertyManager = executor.RootPropertyManager;
            }

            foreach (ExecutionProperty property in this.properties.Values)
            {
                if (property.Property is IExecutionProperty)
                {
                    AddIExecutionProperty(property, true);
                }

                if (property.HasRestrictedVisibility)
                {
                    property.Visibility = visibility;
                }
            }
        }

        [DataContract]
        internal class ExecutionProperty
        {
            string name;
            object property;
            bool hasRestrictedVisibility;

            public ExecutionProperty(string name, object property, IdSpace visibility)
            {
                this.Name = name;
                this.Property = property;

                if (visibility != null)
                {
                    this.Visibility = visibility;
                    this.HasRestrictedVisibility = true;
                }
            }
            
            public string Name 
            {
                get
                {
                    return this.name;
                }
                private set
                {
                    this.name = value;
                }
            }
            
            public object Property
            {
                get
                {
                    return this.property;
                }
                private set
                {
                    this.property = value;
                }
            }
           
            public bool HasRestrictedVisibility
            {
                get
                {
                    return this.hasRestrictedVisibility;
                }
                private set
                {
                    this.hasRestrictedVisibility = value;
                }
            }

            // This property is fixed up at deserialization time
            public IdSpace Visibility
            {
                get;
                set;
            }

            // This is always false at persistence because
            // a removed property belongs to an activity which
            // has completed and is therefore not part of the 
            // instance map anymore
            public bool IsRemoved { get; set; }

            // These don't need to be serialized because they are only
            // ever false at persistence time.  We potentially set
            // them to true when a property is added but we always
            // reset them to false after cleaning up the thread
            public bool ShouldBeRemovedAfterCleanup { get; set; }
            public bool ShouldSkipNextCleanup { get; set; }

            [DataMember(Name = "Name")]
            internal string SerializedName
            {
                get { return this.Name; }
                set { this.Name = value; }
            }

            [DataMember(Name = "Property")]
            internal object SerializedProperty
            {
                get { return this.Property; }
                set { this.Property = value; }
            }

            [DataMember(EmitDefaultValue = false, Name = "HasRestrictedVisibility")]
            internal bool SerializedHasRestrictedVisibility
            {
                get { return this.HasRestrictedVisibility; }
                set { this.HasRestrictedVisibility = value; }
            }
        }
    }
}