public void AddingToSameKeyTwiceAlwaysThrows()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o);
            dict.Add("foo1", o);
        }
Example #2
0
        public void TestAddSameKeyThrowsException()
        {
            WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5);
            KeyObject key = new KeyObject(10);
            weakDict.Add(key, 10);

            Action testAction = () => { weakDict.Add(key, 10); };
            testAction.ShouldThrow<ArgumentException>();
        }
Example #3
0
        //[ExpectedException(typeof(ArgumentException))]
        public void AddingToSameKeyTwiceAlwaysThrows()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o);
            //dict.Add("foo1", o);
            Assert.That(() => dict.Add("foo1", o),
                        Throws.TypeOf <ArgumentException>());
        }
Example #4
0
        public void CanAddItemAfterPreviousItemIsCollected()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", new object());

            GC.Collect();

            dict.Add("foo", new object());
        }
Example #5
0
        public void CanAddSameObjectTwiceWithDifferentKeys()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o);
            dict.Add("foo2", o);

            Assert.AreSame(dict["foo1"], dict["foo2"]);
        }
Example #6
0
        public void RemovingAKeyOfOneObjectDoesNotAffectOtherKeysForSameObject()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o);
            dict.Add("foo2", o);
            dict.Remove("foo1");

            Assert.AreSame(o, dict["foo2"]);
        }
Example #7
0
        public void CanInformCountainedValue()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();
            object o = new object();

            dict.Add("foo1", "bar");
            dict.Add("foo2", o);

            Assert.IsTrue(dict.ContainsValue("bar"));
            Assert.IsTrue(dict.ContainsValue(o));
        }
Example #8
0
        public void RemovingAKeyDoesNotAffectOtherKeys()
        {
            object o1 = new object();
            object o2 = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o1);
            dict.Add("foo2", o2);
            dict.Remove("foo1");

            Assert.AreSame(o2, dict["foo2"]);
        }
Example #9
0
        public void CanRegisterTwoObjectsAndGetThemBoth()
        {
            object o1 = new object();
            object o2 = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o1);
            dict.Add("foo2", o2);

            Assert.AreSame(o1, dict["foo1"]);
            Assert.AreSame(o2, dict["foo2"]);
        }
        public void TestAddDiffTupleForSameObjectThrowsException()
        {
            WeakDictionary <object, int> weakDict = new WeakDictionary <object, int>(this.comparer, 5);
            var key = new Tuple <object, MemberInfo>(new KeyObject(10), this.memberInfo);

            weakDict.Add(key, 10);

            var    key2       = new Tuple <object, MemberInfo>(key.Item1, this.memberInfo);
            Action testAction = () => { weakDict.Add(key2, 10); };

            testAction.ShouldThrow <ArgumentException>();
        }
Example #11
0
        public void TestRemoveDeadItemWhenAddMoreThanCurrentRefreshIntervalItems()
        {
            WeakDictionary <KeyObject, int> weakDict = new WeakDictionary <KeyObject, int>(this.comparer, 5);

            for (int i = 0; i < 4; i++)
            {
                AddAnItem(weakDict, i);
            }

            // Force gc to collect dead items
            GC.Collect();
            if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
            {
                var key1 = new KeyObject(11);
                weakDict.Add(key1, 11);

                var key2 = new KeyObject(12);

                // Weak dictionary will remove dead items during this adding operation.
                // Then the currentRefreshInterval will be 1(still alive)+5=6.
                weakDict.Add(key2, 12);

                Assert.Equal(2, weakDict.Count);

                for (int i = 0; i < 3; i++)
                {
                    AddAnItem(weakDict, i);
                }

                // Force gc to collect dead items
                GC.Collect();
                if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
                {
                    // Add the six item to dictionary.
                    var key6 = new KeyObject(16);

                    // Weak dictionary will not clean dead entities.
                    weakDict.Add(key6, 16);
                    Assert.Equal(6, weakDict.Count);

                    var key14 = new KeyObject(114);

                    // Weak dictionary will remove dead items during this adding operation.
                    // Then the currentRefreshInterval will be 3(still alive)+5=8.
                    weakDict.Add(key14, 114);
                    Assert.Equal(4, weakDict.Count);
                }
            }
        }
Example #12
0
        public void CountReturnsNumberOfKeysWithLiveValues()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo1", o);
            dict.Add("foo2", o);

            Assert.AreEqual(2, dict.Count);

            o = null;
            GC.Collect();

            Assert.AreEqual(0, dict.Count);
        }
        /// <summary>
        /// Patches the events for a specific treeview.
        /// </summary>
        /// <param name="treeView">The TreeView.</param>
        private static void CorrectEventsForTreeView(TreeView treeView)
        {
            if (EventsPatched.ContainsKey(treeView))
            {
                throw new InvalidOperationException("Events for this TreeView has been previously patched: '" + treeView.Name + "'");
            }

            EventsPatched.Add(treeView, new Dictionary <string, List <Delegate> >());
            foreach (string eventName in EventsToCorrect.Keys)
            {
                EventInfo eventInfo = treeView.GetType().GetEvent(eventName);
                if (eventInfo == null)
                {
                    throw new InvalidOperationException("Event info for event '" + eventName + "' could not be found");
                }

                EventsPatched[treeView].Add(eventName, new List <Delegate>());
                Delegate[] eventDelegates = ContainerHelper.GetEventSubscribers(treeView, eventName);
                if (eventDelegates != null)
                {
                    foreach (Delegate del in eventDelegates)
                    {
                        EventsPatched[treeView][eventName].Add(del);
                        eventInfo.RemoveEventHandler(treeView, del);
                    }
                }
                eventInfo.AddEventHandler(treeView, EventsToCorrect[eventName]);
            }
        }
        /// <summary>
        ///   Creates an instance of the type with the specified constructor arguments.
        /// </summary>
        /// <param name = "type">The type.</param>
        /// <param name = "args">The constructor args.</param>
        /// <returns>The created instance.</returns>
        protected override object ActivateInstance(Type type, object[] args)
        {
            object result;

            if (_singletones.TryGetValue(type, out result))
            {
                return(result);
            }

            RegisterAsKind kind;

            lock (_syncObject)
            {
                if (!_types.TryGetValue(type, out kind))
                {
                    kind = GetKind(type);
                    _types.Add(type, kind);
                }
            }

            result = base.ActivateInstance(type, args);

            if (kind == RegisterAsKind.Singleton)
            {
                _singletones.Add(type, result);
            }

            return(result);
        }
Example #15
0
        public void NullIsAValidValue()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", null);
            Assert.IsNull(dict["foo"]);
        }
        public void TestRemoveDeadItemWhenAddMoreThanRefreshIntervalItems()
        {
            WeakDictionary <object, int> weakDict = new WeakDictionary <object, int>(this.comparer, 5);

            for (int i = 0; i < 2; i++)
            {
                AddKeyObject(weakDict, i);
            }

            for (int i = 0; i < 3; i++)
            {
                AddTupleObject(weakDict, i);
            }

            // Force gc to collect dead items
            GC.Collect();
            if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
            {
                var key = new KeyObject(6);
                weakDict.Add(key, 6);

                // The countLimit after the first clean is 6 now.
                Assert.Equal(1, weakDict.Count);
            }
        }
Example #17
0
        public virtual IRevertChangesSavepoint CreateSavepoint(Object source)
        {
            if (source == null)
            {
                return(null);
            }
            List <Object>  objList = new List <Object>();
            List <IObjRef> objRefs = new List <IObjRef>();

            FindAllObjectsToBackup(source, objList, objRefs, new IdentityHashSet <Object>());

            IDictionary <Object, RevertChangesSavepoint.IBackup> originalToValueBackup = new IdentityDictionary <Object, RevertChangesSavepoint.IBackup>();

            // Iterate manually through the list because the list itself should not be 'backuped'
            for (int a = objList.Count; a-- > 0;)
            {
                BackupObjects(objList[a], originalToValueBackup);
            }
            WeakDictionary <Object, RevertChangesSavepoint.IBackup> weakObjectsToBackup = new WeakDictionary <Object, RevertChangesSavepoint.IBackup>(new IdentityEqualityComparer <Object>());

            DictionaryExtension.Loop(originalToValueBackup, delegate(Object obj, RevertChangesSavepoint.IBackup backup)
            {
                if (backup != null)
                {
                    weakObjectsToBackup.Add(obj, backup);
                }
            });

            return(BeanContext.RegisterBean <RevertChangesSavepoint>().PropertyValue("Changes", weakObjectsToBackup).Finish());
        }
Example #18
0
        public void TestAddANullKeyThrowsException()
        {
            WeakDictionary <KeyObject, int> weakDict = new WeakDictionary <KeyObject, int>(this.comparer, 5);
            Action testAction = () => { weakDict.Add(null, 10); };

            testAction.ShouldThrow <ArgumentNullException>();
        }
Example #19
0
        /// <summary>
        /// Patches the events for a specific button.
        /// </summary>
        /// <param name="btn"></param>
        private static void CorretEventsForButton(Button btn)
        {
            Delegate[] EventDelegates = null;

            if (EventsPatched.ContainsKey(btn))
            {
                throw new InvalidOperationException("Events for this button has been previously patched: '" + btn.Name + "'");
            }

            EventsPatched.Add(btn, new Dictionary <string, List <Delegate> >());
            foreach (string eventName in EventsToCorrect.Keys)
            {
                EventInfo eInfo = btn.GetType().GetEvent(eventName);
                if (eInfo == null)
                {
                    throw new InvalidOperationException("Event info for event '" + eventName + "' could not be found");
                }

                EventsPatched[btn].Add(eventName, new List <Delegate>());
                EventDelegates = ContainerHelper.GetEventSubscribers(btn, eventName);
                if (EventDelegates != null)
                {
                    foreach (Delegate del in EventDelegates)
                    {
                        EventsPatched[btn][eventName].Add(del);
                        eInfo.RemoveEventHandler(btn, del);
                    }
                }
                eInfo.AddEventHandler(btn, EventsToCorrect[eventName]);
            }
        }
        private void AddTupleObject(WeakDictionary <object, int> dict, int id)
        {
            KeyObject key   = new KeyObject(id);
            var       tuple = new Tuple <object, MemberInfo>(key, this.memberInfo);

            dict.Add(tuple, rand.Next());
        }
Example #21
0
        public void KeyCanBeGarbageCollected()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add(new object(), "foo");
            GC.Collect();
            Assert.IsTrue(dict.Count == 0);
        }
        public void RegistrationDoesNotPreventGarbageCollection()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", new object());
            GC.Collect();
            object unused = dict["foo"];
        }
        private WeakDictionary <object, int> CreateDict(out List <object> keys)
        {
            WeakDictionary <object, int> weakDict = CreateDictWithoutItem();

            keys = new List <object>();
            for (int i = 0; i < 5; i++)
            {
                KeyObject key = new KeyObject(i);
                keys.Add(key);
                weakDict.Add(key, 2 * i);
                var tuple = new Tuple <object, MemberInfo>(key, this.memberInfo);
                keys.Add(tuple);
                weakDict.Add(tuple, 2 * i + 1);
            }

            return(weakDict);
        }
Example #24
0
        public void CanFindOutIfContainsAKey()
        {
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", null);
            Assert.IsTrue(dict.ContainsKey("foo"));
            Assert.IsFalse(dict.ContainsKey("foo2"));
        }
Example #25
0
        /// <summary>
        /// <b>Expert:</b> Adds a custom AttributeImpl instance with one or more Attribute interfaces.
        /// <p><font color="red"><b>Please note:</b> It is not guaranteed, that <c>att</c> is added to
        /// the <c>AttributeSource</c>, because the provided attributes may already exist.
        /// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding
        /// with this method and cast to your class.
        /// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/>
        /// </font></p>
        /// </summary>
        public void AddAttributeImpl(Attribute att)
        {
            Type clazz = att.GetType();

            if (attributeImpls.TryGetValue(clazz, out var impl))
            {
                return;
            }

            LinkedList <WeakReference> foundInterfaces;

            lock (knownImplClasses)
            {
                foundInterfaces = knownImplClasses[clazz];
                if (foundInterfaces == null)
                {
                    // we have a strong reference to the class instance holding all interfaces in the list (parameter "att"),
                    // so all WeakReferences are never evicted by GC
                    knownImplClasses.Add(clazz, foundInterfaces = new LinkedList <WeakReference>());
                    // find all interfaces that this attribute instance implements
                    // and that extend the Attribute interface
                    Type actClazz = clazz;
                    do
                    {
                        Type[] interfaces = actClazz.GetInterfaces();
                        for (int i = 0; i < interfaces.Length; i++)
                        {
                            Type curInterface = interfaces[i];
                            if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface))
                            {
                                foundInterfaces.AddLast(new WeakReference(curInterface));
                            }
                        }
                        actClazz = actClazz.BaseType;
                    }while (actClazz != null);
                }
            }

            // add all interfaces of this AttributeImpl to the maps
            foreach (var curInterfaceRef in foundInterfaces)
            {
                System.Type curInterface = (System.Type)curInterfaceRef.Target;
                System.Diagnostics.Debug.Assert(curInterface != null,
                                                "We have a strong reference on the class holding the interfaces, so they should never get evicted");

                // Attribute is a superclass of this interface
                if (!attributes.TryGetValue(curInterface, out var _))
                {
                    // invalidate state to force recomputation in captureState()
                    this.currentState[0]     = null;
                    attributes[curInterface] = new AttributeImplItem(curInterface, att);
                    if (!attributeImpls.TryGetValue(clazz, out _))
                    {
                        attributeImpls[clazz] = new AttributeImplItem(clazz, att);
                    }
                }
            }
        }
Example #26
0
        /// <summary>
        /// <b>Expert:</b> Adds a custom AttributeImpl instance with one or more Attribute interfaces.
        /// <p><font color="red"><b>Please note:</b> It is not guaranteed, that <c>attr</c> is added to
        /// the <c>AttributeSource</c>, because the provided attributes may already exist.
        /// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding
        /// with this method and cast to your class.
        /// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/>
        /// </font></p>
        /// </summary>
        public virtual void AddAttributeImpl(Attribute attr)
        {
            Type attrType = attr.GetType();

            if (attributeImpls.Contains(attrType))
            {
                return;
            }

            LinkedList <WeakReference> foundInterfaces;

            lock (knownImplClasses)
            {
                foundInterfaces = knownImplClasses[attrType];
                if (foundInterfaces == null)
                {
                    // we have a strong reference to the class instance holding all interfaces in the list (parameter "attr"),
                    // so all WeakReferences are never evicted by GC
                    knownImplClasses.Add(attrType, foundInterfaces = new LinkedList <WeakReference>());

                    // find all interfaces that this attribute instance implements
                    // and that extend the Attribute interface
                    var type = attrType;
                    do
                    {
                        var interfaces = type.GetInterfaces();
                        foreach (var curInterface in interfaces)
                        {
                            if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface))
                            {
                                foundInterfaces.AddLast(new WeakReference(curInterface));
                            }
                        }
                        type = type.BaseType;
                    }while (type != null);
                }
            }

            // add all interfaces of this AttributeImpl to the maps
            foreach (var curInterfaceRef in foundInterfaces)
            {
                Type curInterface = (Type)curInterfaceRef.Target;
                System.Diagnostics.Debug.Assert(curInterface != null,
                                                "We have a strong reference on the class holding the interfaces, so they should never get evicted");
                // Attribute is a superclass of this interface
                if (!attributes.ContainsKey(curInterface))
                {
                    // invalidate state to force recomputation in captureState()
                    this.currentState[0] = null;
                    attributes.Add(new AttributeImplItem(curInterface, attr));
                    if (!attributeImpls.ContainsKey(attrType))
                    {
                        attributeImpls.Add(new AttributeImplItem(attrType, attr));
                    }
                }
            }
        }
        public void CanRemoveAnObjectThatWasAlreadyAdded()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", o);
            dict.Remove("foo");
            object unused = dict["foo"];
        }
Example #28
0
        public void CanRegisterObjectAndFindItByID()
        {
            object o = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add("foo", o);
            Assert.IsNotNull(dict["foo"]);
            Assert.AreSame(o, dict["foo"]);
        }
Example #29
0
        /// <summary>
        /// Static - Gets the property MaskColor for the button.
        /// </summary>
        /// <param name="button">The button.</param>
        /// <returns>The current MaskColor for this button.</returns>
        public static Color GetMaskColorProperty(Button button)
        {
            if (!MaskColor.ContainsKey(button))
            {
                MaskColor.Add(button, Color.Silver);
            }

            return(MaskColor[button]);
        }
Example #30
0
        public void KeyCanBeOfArbitraryType()
        {
            object oKey = new object();
            object oVal = new object();
            WeakDictionary <object, object> dict = new WeakDictionary <object, object>();

            dict.Add(oKey, oVal);

            Assert.AreSame(oVal, dict[oKey]);
        }
        public void TestBasicOps()
        {
            WeakDictionary<string, string> wd = new WeakDictionary<string, string>();
            List<string> list = new List<string>();
            for (int i = 0; i < 100; i++)
            {
                list.Add(i.ToString());
            }

            foreach (string s in list)
            {
                wd.Add("k" + s, "v" + s);
            }
            foreach(string key in list)
            {
                Assert.AreEqual(wd["k"+key],"v"+key);
            }
            foreach (string key in list)
            {
                wd.Remove("k"+key);
            }
            Assert.AreEqual(0,wd.Count);


            foreach (string s in list)
            {
                wd.Add("k" + s, "v" + s);
            }
            foreach (string key in wd.Keys)
            {
                Assert.True(list.Contains(key.Substring(1)));
            }

            foreach(KeyValuePair<string,string> kv in wd)
            {
                Assert.True(list.Contains(kv.Key.Substring(1)));
                Assert.AreEqual(kv.Key.Substring(1), kv.Value.Substring(1));
            }
        }
 private WeakDictionary<object, int> CreateDict(out List<KeyObject> keys)
 {
     WeakDictionary<object, int> weakDict = new WeakDictionary<object, int>(this.comparer, refreshInterval: 5);
     keys = new List<KeyObject>();
     for (int i = 0; i < 10; i++)
     {
         KeyObject key = new KeyObject(i);
         keys.Add(key);
         weakDict.Add(key, i);
     }
     return weakDict;
 }
        public void TestAddSameKeyThrowsException()
        {
            WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5);
            KeyObject key = new KeyObject(10);
            weakDict.Add(key, 10);

            Action testAction = () => { weakDict.Add(key, 10); };
            testAction.ShouldThrow<ArgumentException>();
        }
 public void TestAddANullKeyThrowsException()
 {
     WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5);
     Action testAction = () => { weakDict.Add(null, 10); };
     testAction.ShouldThrow<ArgumentNullException>();
 }
 private void AddAnItem(WeakDictionary<KeyObject, int> dict, int id)
 {
     KeyObject key = new KeyObject(id);
     dict.Add(key, rand.Next());
 }
        public void TestRemoveDeadItemWhenAddMoreThanCurrentRefreshIntervalItems()
        {
            WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5);
            for (int i = 0; i < 4; i++)
            {
                AddAnItem(weakDict, i);
            }

            // Force gc to collect dead items
            GC.Collect();
            if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
            {
                var key1 = new KeyObject(11);
                weakDict.Add(key1, 11);

                var key2 = new KeyObject(12);

                // Weak dictionary will remove dead items during this adding operation.
                // Then the currentRefreshInterval will be 1(still alive)+5=6.
                weakDict.Add(key2, 12);

                Assert.AreEqual(2, weakDict.Count);

                for (int i = 0; i < 3; i++)
                {
                    AddAnItem(weakDict, i);
                }

                // Force gc to collect dead items
                GC.Collect();
                if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
                {
                    // Add the six item to dictionary.
                    var key6 = new KeyObject(16);

                    // Weak dictionary will not clean dead entities.
                    weakDict.Add(key6, 16);
                    Assert.AreEqual(6, weakDict.Count);

                    var key14 = new KeyObject(114);

                    // Weak dictionary will remove dead items during this adding operation.
                    // Then the currentRefreshInterval will be 3(still alive)+5=8.
                    weakDict.Add(key14, 114);
                    Assert.AreEqual(4, weakDict.Count);
                }
            }
        }
        public void TestRemoveDeadItemWhenAddMoreThanRefreshIntervalItems()
        {
            WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5);
            for (int i = 0; i < 5; i++)
            {
                AddAnItem(weakDict, i);
            }

            // Force gc to collect dead items
            GC.Collect();
            if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
            {
                var key = new KeyObject(6);
                weakDict.Add(key, 6);

                // The countLimit after the first clean is 6 now.
                Assert.AreEqual(1, weakDict.Count);
            }
        }
 private void AddTupleObject(WeakDictionary<object, int> dict, int id)
 {
     KeyObject key = new KeyObject(id);
     var tuple = new Tuple<object, MemberInfo>(key, this.memberInfo);
     dict.Add(tuple, rand.Next());
 }
        public void TestAddDiffTupleForSameObjectThrowsException()
        {
            WeakDictionary<object, int> weakDict = new WeakDictionary<object, int>(this.comparer, 5);
            var key = new Tuple<object, MemberInfo>(new KeyObject(10), this.memberInfo);
            weakDict.Add(key, 10);

            var key2 = new Tuple<object, MemberInfo>(key.Item1, this.memberInfo);
            Action testAction = () => { weakDict.Add(key2, 10); };
            testAction.ShouldThrow<ArgumentException>();
        }