Esempio n. 1
0
        public void DictionaryCopyConstructorProperlyCopiesEntriesAndSetsGottenTracking()
        {
            var other = new Dictionary <string, string>();

            other.Add("key1", "otherValue1");
            other.Add("key2", "otherValue2");

            // trackAccessed = false, trackGotten = true
            var sd = new SynchronizedDictionary <string, string>(other, false, true);

            Assert.IsTrue(sd.ContainsKey("key1"));
            Assert.IsTrue(sd.ContainsKey("key2"));

            Assert.AreEqual(sd["key1"], "otherValue1");
            Assert.AreEqual(sd["key2"], "otherValue2");

            // Accessed Tracking is disabled
            Assert.IsFalse(sd.TrackAccessed);
            Assert.IsNull(sd.Accessed);

            // Accessed Tracking is enabled
            Assert.IsTrue(sd.TrackGotten);
            Assert.IsNotNull(sd.Gotten);
            Assert.AreEqual(sd.Gotten.Count, 2);
        }
        public IDictionary <long, IList <WorkSchedule> > GetAll(short pastMonths, short newMonths)
        {
            SynchronizedDictionary <long, IList <WorkSchedule> > result = new SynchronizedDictionary <long, IList <WorkSchedule> >();
            List <Task> tasks    = new List <Task>();
            DateTime    firstDay = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
            DateTime    lastDay  = firstDay.AddMonths(1).AddMilliseconds(-1);

            foreach (ProjectInfoS item in ProjectInfoS.FetchList(Database.Default,
                                                                 p => p.OriginateTime <= lastDay && (p.ClosedDate == null || p.ClosedDate >= firstDay)))
            {
                //项目经理
                long projectManager = item.ProjectManager;
                if (!result.ContainsKey(projectManager))
                {
                    result.Add(projectManager, null);
                    tasks.Add(Task.Run(async() =>
                    {
                        result[projectManager] = await ClusterClient.Default.GetGrain <IWorkScheduleGrain>(projectManager).FetchWorkSchedules(pastMonths, newMonths);
                    }));
                }
                //开发经理
                long developManager = item.DevelopManager;
                if (!result.ContainsKey(developManager))
                {
                    result.Add(developManager, null);
                    tasks.Add(Task.Run(async() =>
                    {
                        result[developManager] = await ClusterClient.Default.GetGrain <IWorkScheduleGrain>(developManager).FetchWorkSchedules(pastMonths, newMonths);
                    }));
                }
            }

            Task.WaitAll(tasks.ToArray());
            return(result);
        }
Esempio n. 3
0
        public void TrackAllFalseDisablesAccessedAndGottenCollections()
        {
            var sd = new SynchronizedDictionary <string, string>();

            Assert.IsNull(sd.Accessed);
            Assert.IsNull(sd.Gotten);

            // Default is tracking disabled
            Assert.IsFalse(sd.TrackAccessed);
            Assert.IsFalse(sd.TrackGotten);

            sd.TrackAll = true;

            // First ensure that tracking is enabled
            Assert.IsTrue(sd.TrackAccessed && sd.TrackGotten);
            Assert.IsNotNull(sd.Accessed);
            Assert.IsNotNull(sd.Gotten);

            sd.TrackAll = false;

            // Now ensure that tracking has been disabled
            Assert.IsFalse(sd.TrackAccessed);
            Assert.IsFalse(sd.TrackGotten);
            Assert.IsNull(sd.Accessed);
            Assert.IsNull(sd.Gotten);
        }
        public void TestAddRemoveByKey()
        {
            SynchronizedDictionary <int, string> test = new SynchronizedDictionary <int, string>(new IgnoreLocking());

            for (int i = 0; i < 10; i++)
            {
                test.Add(i, i.ToString());
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.IsTrue(test.ContainsKey(i));
            }

            string cmp;

            for (int i = 0; i < 10; i++)
            {
                Assert.IsTrue(test.TryGetValue(i, out cmp) && cmp == i.ToString());
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.IsTrue(test.Remove(i));
            }
        }
        public void TestTryRoutines()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            Assert.IsTrue(data.TryAdd(1, "a"));
            Assert.IsFalse(data.TryAdd(1, "a"));

            Assert.IsTrue(data.TryUpdate(1, "a"));
            Assert.IsTrue(data.TryUpdate(1, "c"));
            Assert.IsTrue(data.TryUpdate(1, "d", "c"));
            Assert.IsFalse(data.TryUpdate(1, "f", "c"));
            Assert.AreEqual("d", data[1]);
            Assert.IsTrue(data.TryUpdate(1, "a", data[1]));
            Assert.AreEqual("a", data[1]);
            Assert.IsFalse(data.TryUpdate(2, "b"));

            string val;

            Assert.IsTrue(data.TryRemove(1, out val) && val == "a");
            Assert.IsFalse(data.TryRemove(2, out val));
            Assert.AreNotEqual(val, "a");

            Assert.IsFalse(data.TryUpdate(1, (k, x) => x.ToUpper()));
            data[1] = "a";
            data[1] = "b";
            Assert.IsTrue(data.TryUpdate(1, (k, x) => x.ToUpper()));
            Assert.AreEqual("B", data[1]);
        }
Esempio n. 6
0
 public static string GetOldestPoisonEntryValueName(SynchronizedDictionary <string, CrashProperties> poisonEntryDictionary)
 {
     ArgumentValidator.ThrowIfNull("poisonEntryDictionary", poisonEntryDictionary);
     return((from keyValuePair in poisonEntryDictionary
             orderby keyValuePair.Value.LastCrashTime
             select keyValuePair.Key).FirstOrDefault <string>());
 }
Esempio n. 7
0
        public void GottenTrackingBeginsWhenItIsEnabled()
        {
            var sd = new SynchronizedDictionary <string, string>();

            sd.Add("key1", "value1");
            sd.Add("key2", "value2");

            // Turn on gotten tracking
            sd.TrackGotten = true;
            Assert.IsTrue(sd.TrackGotten);
            Assert.IsNotNull(sd.Gotten);

            var v1 = sd["key1"];

            Assert.AreEqual(v1, "value1");
            Assert.AreEqual(sd.Gotten.Count, 1);

            var v2 = sd["key2"];

            Assert.AreEqual(v2, "value2");
            Assert.AreEqual(sd.Gotten.Count, 2);

            // A second 'get' does not affect count
            v1 = sd["key1"];
            Assert.AreEqual(sd.Gotten.Count, 2);
        }
Esempio n. 8
0
        private IDictionary <Jid, UserRosterItemDic> LoadRosterItems()
        {
            var items = new SynchronizedDictionary <Jid, UserRosterItemDic>();

            ExecuteList(new SqlQuery("jabber_roster").Select("jid", "item_jid", "name", "subscription", "ask", "groups"))
            .ForEach(r =>
            {
                var item = new UserRosterItem(new Jid((string)r[1]))
                {
                    Name         = r[2] as string,
                    Subscribtion = (SubscriptionType)Convert.ToInt32(r[3]),
                    Ask          = (AskType)Convert.ToInt32(r[4]),
                };
                if (r[5] != null)
                {
                    item.Groups.AddRange(((string)r[5]).Split(new[] { GroupSeparator }, StringSplitOptions.RemoveEmptyEntries));
                }

                var jid = new Jid((string)r[0]);
                if (!items.ContainsKey(jid))
                {
                    items[jid] = new UserRosterItemDic();
                }
                items[jid][item.Jid] = item;
            });

            return(items);
        }
Esempio n. 9
0
        protected bool Start()
        {
            _auctionedItems = new SynchronizedDictionary <uint, ItemRecord>(10000);

            if (AllowInterFactionAuctions)
            {
                NeutralAuctions  = new AuctionHouse();
                AllianceAuctions = NeutralAuctions;
                HordeAuctions    = NeutralAuctions;
            }
            else
            {
                AllianceAuctions = new AuctionHouse();
                HordeAuctions    = new AuctionHouse();
                NeutralAuctions  = new AuctionHouse();
            }

#if DEBUG
            try
            {
#endif
            FetchAuctions();
#if DEBUG
        }
        catch (Exception e)
        {
            RealmDBMgr.OnDBError(e);
            FetchAuctions();
        }
#endif
            return(true);
        }
        public void TestDisposed()
        {
            SynchronizedDictionary <int, string> test = new SynchronizedDictionary <int, string>(new SimpleReadWriteLocking());

            test.Dispose();
            test.Add(1, "");
        }
Esempio n. 11
0
        public ReadyHandler()
        {
            PendingGuilds = new SynchronizedDictionary <ShardId, ISynchronizedDictionary <Snowflake, bool> >();
            InitialReadys = new SynchronizedDictionary <ShardId, Tcs>();

            _delays = new SynchronizedDictionary <ShardId, DelayToken>();
        }
        public void TestSpeed()
        {
            //Note: speed is not so good fro now
            const double coef = 1.8;
            const int count = 1000000;
            var dict1 = new Dictionary<string, string>(count);
            var dict2 = new SynchronizedDictionary<string, string>(count);
            
            var bench1 = InsertInto(dict1, count);
            var bench2 = InsertInto(dict2, count);
            Assert.LessOrEqual(bench2,bench1*coef);

            bench1 = ReadFrom(dict1, count);
            bench2 = ReadFrom(dict2, count);
            Assert.LessOrEqual(bench2, bench1 * coef);

            bench1 = DeleteFrom(dict1, count);
            bench2 = DeleteFrom(dict2, count);
            

            Assert.LessOrEqual(bench2, bench1 * coef);

            Assert.AreEqual(dict1.Count, 0);
            Assert.AreEqual(dict2.Count, 0);
        }
        /// <summary>
        /// Parses the XML of the configuration section.
        /// </summary>
        /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param>
        /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.</param>
        /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param>
        /// <returns>A configuration object.</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            if (section == null)
            {
                throw new ConfigurationErrorsException("The sourceForge/objectFactory section has not been defined.");
            }

            objectDefinitions = new SynchronizedDictionary<string, ObjectDefinition>();

            if (section.HasChildNodes)
            {
                // Register each object's configuration, without the constructor or property information
                foreach (XmlElement element in section.SelectNodes("object"))
                {
                    // In the event of a reference property or constructor argument already being processed, don't process the definition again
                    if (objectDefinitions.ContainsKey(element.GetAttribute("id")) == false)
                    {
                        ObjectDefinition objectDefinition = GetObjectDefinition(section as XmlElement, element, element.GetAttribute("id"));
                        objectDefinitions.Add(objectDefinition.Id, objectDefinition);
                    }
                }
            }

            return this;
        }
        public void TestAtomicInterfaces()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            data[1] = "a";

            AddUpdateValue update = new AddUpdateValue();

            Assert.IsFalse(data.AddOrUpdate(1, ref update));
            Assert.AreEqual("a", update.OldValue);
            Assert.IsFalse(data.AddOrUpdate(2, ref update));
            Assert.IsNull(update.OldValue);
            Assert.IsFalse(data.TryRemove(1, ref update));
            Assert.AreEqual("a", update.OldValue);

            Assert.AreEqual(1, data.Count);
            Assert.AreEqual("a", data[1]);

            update.Value = "b";
            Assert.IsTrue(data.AddOrUpdate(1, ref update));
            Assert.AreEqual("a", update.OldValue);
            Assert.IsTrue(data.AddOrUpdate(2, ref update));
            Assert.IsNull(update.OldValue);

            Assert.AreEqual(2, data.Count);
            Assert.AreEqual("b", data[1]);
            Assert.AreEqual("b", data[2]);

            Assert.IsTrue(data.TryRemove(1, ref update));
            Assert.AreEqual("b", update.OldValue);
            Assert.IsTrue(data.TryRemove(2, ref update));
            Assert.AreEqual("b", update.OldValue);
            Assert.AreEqual(0, data.Count);
        }
Esempio n. 15
0
        public void AddExistsIdNameElementTest_HasArgumentOutOfRangeException()
        {
            var dic = new SynchronizedDictionary<int, string, string>();

            dic.Add(1, "Иванов", "value_1");
            dic.Add(1, "Иванов", "value_2");
        }
        public void TestAtomicAddOrUpdate()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            int[] counter = new int[] { -1 };

            for (int i = 0; i < 100; i++)
            {
                data.AddOrUpdate(i, (k) => (++counter[0]).ToString(), (k, v) => { throw new InvalidOperationException(); });
            }

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual((i & 1) == 1, data.TryRemove(i, (k, v) => (int.Parse(v) & 1) == 1));
            }

            for (int i = 0; i < 100; i++)
            {
                data.AddOrUpdate(i, (k) => (++counter[0]).ToString(), (k, v) => (++counter[0]).ToString());
            }

            Assert.AreEqual(100, data.Count);
            Assert.AreEqual(200, counter[0] + 1);

            for (int i = 0; i < 100; i++)
            {
                Assert.IsTrue(data.TryRemove(i, (k, v) => int.Parse(v) - 100 == i));
            }

            Assert.AreEqual(0, data.Count);
        }
Esempio n. 17
0
        private static int ChangeSubscribers(SynchronizedDictionary <Security, int> subscribers, Security subscriber, int delta)
        {
            if (subscribers == null)
            {
                throw new ArgumentNullException("subscribers");
            }

            lock (subscribers.SyncRoot)
            {
                var value = subscribers.TryGetValue2(subscriber) ?? 0;

                value += delta;

                if (value > 0)
                {
                    subscribers[subscriber] = value;
                }
                else
                {
                    subscribers.Remove(subscriber);
                }

                return(value);
            }
        }
Esempio n. 18
0
        public void TestSpeed()
        {
            //Note: speed is not so good fro now
            const double coef  = 1.8;
            const int    count = 1000000;
            var          dict1 = new Dictionary <string, string>(count);
            var          dict2 = new SynchronizedDictionary <string, string>(count);

            var bench1 = InsertInto(dict1, count);
            var bench2 = InsertInto(dict2, count);

            Assert.IsTrue(bench2 <= bench1 * coef);

            bench1 = ReadFrom(dict1, count);
            bench2 = ReadFrom(dict2, count);
            Assert.IsTrue(bench2 <= bench1 * coef);

            bench1 = DeleteFrom(dict1, count);
            bench2 = DeleteFrom(dict2, count);


            Assert.IsTrue(bench2 <= bench1 * coef);

            Assert.AreEqual(dict1.Count, 0);
            Assert.AreEqual(dict2.Count, 0);
        }
 /// <summary>
 /// Initializes a new <see cref="SynchronizedKeyedCollection{TKey,TValue}"/> with a new lock, but specifies
 /// the equality comparer.
 /// </summary>
 /// <param name="comparer">An equality comparer.</param>
 protected SynchronizedKeyedCollection(IEqualityComparer <TKey> comparer)
 {
     if (comparer == null)
     {
         throw new ArgumentNullException("comparer");
     }
     this.dictionary = new SynchronizedDictionary(this, comparer, new ReaderWriterLockWrapper(this));
 }
Esempio n. 20
0
 public void TestLiveFiltering()
 {
     var dict = new SynchronizedDictionary <int, string>
     {
         { 1, "1" },
         { 2, "2" }
     };
 }
Esempio n. 21
0
 /// <summary>
 /// Creates a new WebRequestFactory instance.
 /// </summary>
 /// <param name="cacheResponses">Shall responses and redirects be cached?</param>
 public WebRequestFactory(bool cacheResponses = false)
 {
     if (cacheResponses)
     {
         Responses = new SynchronizedDictionary <string, string, AVLHashMap <string, string> >();
         Redirects = new SynchronizedDictionary <string, string, AVLHashMap <string, string> >();
     }
 }
        public void LockedWrite()
        {
            var values     = Enumerable.Range(1, 10);
            var dictionary = new SynchronizedDictionary <int, int>(values.ToDictionary(a => a * 2));

            Assert.Equal(15, dictionary.Lock.Write(d => d[15] = 15));
            Assert.Equal(15, dictionary.Lock.Read(d => d.GetValueOrDefault(15)));
        }
        public void LockedWrite()
        {
            var values = Enumerable.Range(1, 10);
            var dictionary = new SynchronizedDictionary<int, int>(values.ToDictionary(a => a * 2));

            Assert.Equal(15, dictionary.Lock.Write(d => d[15] = 15));
            Assert.Equal(15, dictionary.Lock.Read(d => d.GetValueOrDefault(15)));
        }
        public void Add()
        {
            var dictionary = new SynchronizedDictionary <string, string>();

            dictionary.Add("1", "11");

            Assert.Contains("11", dictionary["1"]);
        }
        public void Add()
        {
            var dictionary = new SynchronizedDictionary<string, string>();

            dictionary.Add("1", "11");

            Assert.Contains("11", dictionary["1"]);
        }
        /// <summary>
        /// Initializes a new <see cref="SynchronizedKeyedCollection{TKey,TValue}"/> and specifies an existing lock
        /// and the default equality comparer.
        /// </summary>
        /// <param name="lock">An existing lock.</param>
        protected SynchronizedKeyedCollection(ReaderWriterLockWrapper @lock)
        {
            if (@lock == null)
            {
                throw new ArgumentNullException("lock");
            }

            this.dictionary = new SynchronizedDictionary(this, @lock);
        }
        public void TestValues()
        {
            SynchronizedDictionary <string, string> test = new SynchronizedDictionary <string, string>(new Dictionary <string, string>());

            test["a"] = "b";
            string all = String.Join("", new List <string>(test.Values).ToArray());

            Assert.AreEqual("b", all);
        }
Esempio n. 28
0
        public static SynchronizedDictionary <Security, decimal> GetSecuritiesPositions(this IConnector connector, Portfolio portfolio,
                                                                                        List <Security> securities)
        {
            SynchronizedDictionary <Security, decimal> result = new SynchronizedDictionary <Security, decimal>();

            securities.ForEach(s => { result.Add(s, GetSecurityPosition(connector, portfolio, s)); });

            return(result);
        }
        public void TestKeys()
        {
            SynchronizedDictionary <string, string> test = new SynchronizedDictionary <string, string>(new Dictionary <string, string>(), new IgnoreLocking());

            test["a"] = "b";
            string all = String.Join("", new List <string>(test.Keys).ToArray());

            Assert.AreEqual("a", all);
        }
        public void TestReplaceDictionary()
        {
            SynchronizedDictionary <string, string> test = new SynchronizedDictionary <string, string>(StringComparer.Ordinal, new IgnoreLocking());

            test["a"] = "b";
            Assert.AreEqual(1, test.Count);
            test.ReplaceStorage(new Dictionary <string, string>());
            Assert.AreEqual(0, test.Count);
        }
        public void Reset(ShardId shardId = default)
        {
            lock (this)
            {
                if (shardId.Count <= 1)
                {
                    _caches.Clear();
                    foreach (var type in _supportedTypes)
                    {
                        var cacheType = typeof(SynchronizedDictionary <,>).MakeGenericType(typeof(Snowflake), type);
                        var cache     = Activator.CreateInstance(cacheType);
                        _caches.Add(type, cache);
                    }

                    _nestedCaches.Clear();
                    foreach (var type in _supportedNestedTypes)
                    {
                        var cache = new SynchronizedDictionary <Snowflake, object>();
                        _nestedCaches.Add(type, cache);
                    }
                }
                else
                {
                    if (_caches.GetValueOrDefault(typeof(CachedGuild)) is ISynchronizedDictionary <Snowflake, CachedGuild> guildsCache)
                    {
                        lock (guildsCache)
                        {
                            foreach (var guildId in guildsCache.Keys.Where(x => ShardId.ForGuildId(x, shardId.Count) == shardId))
                            {
                                guildsCache.Remove(guildId);

                                if (this.TryGetChannels(guildId, out var channelCache))
                                {
                                    channelCache.Clear();
                                }

                                if (this.TryGetMembers(guildId, out var memberCache))
                                {
                                    memberCache.Clear();
                                }

                                if (this.TryGetRoles(guildId, out var roleCache))
                                {
                                    roleCache.Clear();
                                }

                                if (this.TryGetVoiceStates(guildId, out var voiceStates))
                                {
                                    voiceStates.Clear();
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 32
0
 static ValueSupport()
 {
     support = new SynchronizedDictionary <Type, IValueSupport>(
         new Dictionary <Type, IValueSupport>()
     {
         { typeof(Int32), new Int32Support() },
         { typeof(Byte), new ByteSupport() }
     }
         );
 }
Esempio n. 33
0
        public void Register(Type type, string key, Func<Container, Type, string, object> builder)
        {
            Requires.NotNull("builder", builder);

            SynchronizedDictionary<string, Func<Container, Type, string, object>> builders;
            if (!_typeBuilders.TryGetValue(type, out builders))
            {
                _typeBuilders.Add(type, builders = new SynchronizedDictionary<string, Func<Container, Type, string, object>>(StringComparer.OrdinalIgnoreCase));
            }
            builders[key ?? string.Empty] = builder;
        }
Esempio n. 34
0
        public void AddCurrentElements_Success()
        {
            var dic = new SynchronizedDictionary<int, string, string>();

            dic.Add(1, "Иванов", "value_1");
            dic.Add(2, "Иванов", "value_2");
            dic.Add(5, "Иванов", "value_3");
            dic.Add(5, "Петров", "value_4");

            Assert.AreEqual(4, dic.Count);
        }
        public void CreateNewDhstrategy(decimal futuresPosition, SynchronizedDictionary <Security, decimal> optionsPositions)
        {
            StrategyForTest = new DeltaHedgerStrategy(futuresPosition, optionsPositions);

            List <Security> securitiesToReg = new List <Security>();

            securitiesToReg.AddRange(optionsPositions.Keys);
            securitiesToReg.Add(StSecurity);

            StrategyForTest.SetStrategyEntitiesForWork(StConnector, StSecurity, StPortfolio);
        }
        public void TestGetOrAdd()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            Assert.AreEqual("a", data.GetOrAdd(1, "a"));
            Assert.AreEqual("a", data.GetOrAdd(1, "b"));

            Assert.AreEqual("b", data.GetOrAdd(2, k => "b"));
            Assert.AreEqual("b", data.GetOrAdd(2, k => "c"));
        }
        public void TestComparer()
        {
            SynchronizedDictionary <string, string> test = new SynchronizedDictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            test["a"] = "b";
            Assert.IsTrue(test.ContainsKey("A"));

            test      = new SynchronizedDictionary <string, string>(StringComparer.OrdinalIgnoreCase, new IgnoreLocking());
            test["a"] = "b";
            Assert.IsTrue(test.ContainsKey("A"));
        }
Esempio n. 38
0
 /// <summary>
 /// Static constructor used to configure the ObjectFactory singleton.
 /// </summary>
 static ObjectFactory()
 {
     ObjectFactorySectionHandler objectFactorySectionHandler = (ObjectFactorySectionHandler) ConfigurationManager.GetSection("sharpCore/objectFactory");
     if (objectFactorySectionHandler == null)
     {
         throw new TypeInitializationException(typeof(ObjectFactory).FullName, new ConfigurationErrorsException("The sharpCore/objectFactory configuration section has not been defined."));
     }
     else
     {
         objectDefinitions = objectFactorySectionHandler.ObjectDefinitions;
     }
 }
 public void TestIndex()
 {
     var dictionary = new SynchronizedDictionary<string, string>();
     dictionary["1"] = "1";
     Assert.AreEqual(dictionary["1"],"1");
     Assert.AreEqual(dictionary["2"], null);
     string val1;
     dictionary.TryGetValue("3", out val1);
     Assert.AreEqual(val1,null);
     dictionary.TryGetValue("1", out val1);
     Assert.AreEqual(val1, "1");
 }
Esempio n. 40
0
 /// <summary>
 /// Initializes the static members of the Cache class.
 /// </summary>
 static Cache()
 {
     CachingSectionHandler sectionHandler = (CachingSectionHandler) ConfigurationManager.GetSection("sharpCore/caching");
     if (sectionHandler == null)
     {
         throw new TypeInitializationException(typeof(Cache).FullName, new ConfigurationErrorsException("The sharpCore/caching configuration section has not been defined."));
     }
     else
     {
         caches = sectionHandler.Caches;
     }
 }
Esempio n. 41
0
        public void GetByIdElements_Success()
        {
            var dic = new SynchronizedDictionary<int, string, string>();

            dic.Add(1, "Иванов", "value_1");
            dic.Add(2, "Иванов", "value_2");
            dic.Add(5, "Иванов", "value_3");
            dic.Add(5, "Петров", "value_4");

            var elementsById = dic.GetById(5);

            Assert.AreEqual(2, elementsById.Count);
        }
Esempio n. 42
0
		private void Init(Schema schema, string tableName)
		{
			if (schema == null)
				throw new ArgumentNullException(nameof(schema));

			DdeSettings = new DdeSettings();

			Schema = schema;
			TableName = tableName;

			EntitySerializer = new BinarySerializer<int>().GetSerializer(schema.EntityType);
			CollectionSerializer = new BinarySerializer<int>().GetSerializer(typeof(IEnumerable<>).Make(schema.EntityType));

			if (Schema.Identity != null)
				Cache = new SynchronizedDictionary<object, object>();
		}
        public void RemoveKeys()
        {
            var dictionary = new SynchronizedDictionary<string, string>();

            var collection = new[] {
                new KeyValuePair<string, string>("22", "33"),
                new KeyValuePair<string, string>("44", "55"),
                new KeyValuePair<string, string>("66", "77"),
            };

            dictionary.AddRange(collection);

            Assert.Equal(dictionary.Count, collection.Count());

            dictionary.RemoveKeys(collection.Select(t => t.Key));

            Assert.Equal(0, dictionary.Count());
        }
Esempio n. 44
0
        public void SynchronizedDictionaryUnitTest()
        {
            SynchronizedDictionary<int, string> dictionary = new SynchronizedDictionary<int, string>();

            dictionary.Add(1, "one");
            dictionary.Add(2, "two");
            Assert.IsTrue(dictionary.Count == 2);

            foreach (KeyValuePair<int, string> keyValuePair in dictionary)
            {
                Assert.IsTrue(dictionary.ContainsKey(keyValuePair.Key));
                Assert.IsTrue(dictionary.ContainsValue(keyValuePair.Value));
            }

            dictionary.Remove(1);
            Assert.IsTrue(dictionary.Count == 1);

            dictionary.Clear();
            Assert.IsTrue(dictionary.Count == 0);
        }
        public void LockedReadWrite()
        {
            var values = Enumerable.Range(1, 10);
            var dictionary = new SynchronizedDictionary<int, int>(values.ToDictionary(a => a * 2));

            int readValue = -1;
            dictionary.Lock.Write(
                d => (readValue = d.GetValueOrDefault(15, -1)) != -1,
                d => readValue = d[15] = 15
            );

            Assert.Equal(15, readValue);

            readValue = -1;
            dictionary.Lock.Write(
                d => (readValue = d.GetValueOrDefault(15, -1)) != -1,
                d => d[15] = 16
            );

            Assert.Equal(15, readValue);
        }
 public void TestThreadedSynchronized()
 {
     var dictionary = new SynchronizedDictionary<string, string>();
     RunThreadTest(dictionary);
 }
 /// <summary>
 /// Initializes a new instance of the CachingSectionHandler class.
 /// </summary>
 public CachingSectionHandler()
 {
     caches = new SynchronizedDictionary<string, CacheBase>();
 }
Esempio n. 48
0
		static BattlegroundMgr()
		{
			Instances = new SynchronizedDictionary<uint, Battleground>[(int)BattlegroundId.End];

			for (var id = BattlegroundId.None + 1; id < BattlegroundId.End; id++)
			{
				Instances[(uint)id] = new SynchronizedDictionary<uint, Battleground>();
			}
		}
Esempio n. 49
0
		private static int ChangeSubscribers(SynchronizedDictionary<Security, int> subscribers, Security subscriber, int delta)
		{
			if (subscribers == null)
				throw new ArgumentNullException("subscribers");

			lock (subscribers.SyncRoot)
			{
				var value = subscribers.TryGetValue2(subscriber) ?? 0;

				value += delta;

				if (value > 0)
					subscribers[subscriber] = value;
				else
					subscribers.Remove(subscriber);

				return value;
			}
		}
Esempio n. 50
0
		public AuctionHouse()
		{
			auctions = new SynchronizedDictionary<uint, Auction>(10000);
			items = new SynchronizedList<uint>(10000);
		}
Esempio n. 51
0
 private static void AddToCache(Guid userId, Size size, string fileName, bool replace)
 {
     if (!Photofiles.ContainsKey(userId)) Photofiles[userId] = new SynchronizedDictionary<Size, string>();
     if (replace)
     {
         Photofiles[userId][size]= fileName;
     }
     else
     {
         if (!Photofiles[userId].ContainsKey(size))
             Photofiles[userId].Add(size, fileName);
     }
 }
Esempio n. 52
0
		private static bool TryUnSubscribe(SynchronizedDictionary<Security, int> subscribers, Security subscriber)
		{
			return ChangeSubscribers(subscribers, subscriber, -1) == 0;
		}
        public void Serialization()
        {
            var dictionary = new SynchronizedDictionary<string, string>();

            var collection = new[] {
                new KeyValuePair<string, string>("22", "33"),
                new KeyValuePair<string, string>("44", "55"),
                new KeyValuePair<string, string>("66", "77"),
            };

            dictionary.AddRange(collection);

            var serialized = dictionary.Serialization().Binary();

            Assert.True(dictionary.ToList().Equality().Equal(serialized));
        }
Esempio n. 54
0
        private IDictionary<Jid, UserRosterItemDic> LoadRosterItems()
        {
            var items = new SynchronizedDictionary<Jid, UserRosterItemDic>();

            ExecuteList(new SqlQuery("jabber_roster").Select("jid", "item_jid", "name", "subscription", "ask", "groups"))
                .ForEach(r =>
                {
                    var item = new UserRosterItem(new Jid((string)r[1]))
                    {
                        Name = r[2] as string,
                        Subscribtion = (SubscriptionType)Convert.ToInt32(r[3]),
                        Ask = (AskType)Convert.ToInt32(r[4]),
                    };
                    if (r[5] != null) item.Groups.AddRange(((string)r[5]).Split(new[] { GroupSeparator }, StringSplitOptions.RemoveEmptyEntries));

                    var jid = new Jid((string)r[0]);
                    if (!items.ContainsKey(jid)) items[jid] = new UserRosterItemDic();
                    items[jid][item.Jid] = item;
                });

            return items;
        }
Esempio n. 55
0
 public DictionaryCache()
 {
     _dictionary = new SynchronizedDictionary<string, object>();
 }