Ejemplo n.º 1
0
        static void Service_Message(object sender, MessageEventArgs e)
        {
            if (e.Message.Message == GetReferencedFile)
            {
                try
                {
                    string sopInstanceUID = e.Message.Data[0].ToString();

                    if (_Callbacks.ContainsKey(sopInstanceUID))
                    {
                        DicomServer server = ServiceLocator.Retrieve <DicomServer>();

                        if (e.Message.Data.Count == 2)
                        {
                            try
                            {
                                string referencedFile = e.Message.Data[1].ToString();

                                if (referencedFile != null && referencedFile.Length > 0)
                                {
                                    DicomDataSet ds = new DicomDataSet(server.TemporaryDirectory);

                                    ds.Load(referencedFile, DicomDataSetLoadFlags.None);
                                    _Callbacks[sopInstanceUID](new DicomDS(ds), referencedFile, sopInstanceUID, string.Empty);
                                }
                                else
                                {
                                    Logger.Global.SystemMessage(LogType.Information, "Referenced file for (" + sopInstanceUID + ") not found", string.Empty);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Global.SystemException(string.Empty, ex);
                                _Callbacks[sopInstanceUID](null, string.Empty, sopInstanceUID, "Invalid message response for GetReferenceFile");
                            }
                        }
                        else
                        {
                            _Callbacks[sopInstanceUID](null, string.Empty, sopInstanceUID, "Invalid message response for GetReferenceFile");
                        }
                        _Callbacks.Remove(sopInstanceUID);
                    }
                }
                catch (Exception exception)
                {
                    Logger.Global.SystemException(string.Empty, exception);
                }
            }
        }
Ejemplo n.º 2
0
            public void TryAdd()
            {
                var dict = new ThreadSafeDictionary <int, int>();

                dict[0] = 0;
                Assert.IsTrue(dict.TryAdd(1, 2));
                Assert.IsFalse(dict.TryAdd(1, 9));
                Assert.IsTrue(dict.TryAdd(new KeyValuePair <int, int>(2, 4)));
                Assert.IsFalse(dict.TryAdd(new KeyValuePair <int, int>(2, 9)));
                Assert.IsFalse(dict.TryAdd(2, 20));
                Assert.IsTrue(dict.TryAdd(3, x => x * 2));
                Assert.IsFalse(dict.TryAdd(3, x => x * 4));
                int monitor = 99;

                Assert.IsTrue(dict.TryAdd(4, x => {
                    return(monitor = 8);
                }));
                Assert.AreEqual(8, monitor);
                Assert.IsFalse(dict.TryAdd(4, x => {
                    return(monitor = 9);
                }));
                Assert.AreEqual(8, monitor);
                Assert.IsTrue(dict.TryAdd(5, 10, out monitor));
                Assert.AreEqual(0, monitor);
                Assert.IsFalse(dict.TryAdd(5, 9, out monitor));
                Assert.AreEqual(10, monitor);
                Assert.IsTrue(dict.TryAdd(6, x => 12, out monitor));
                Assert.AreEqual(0, monitor);
                Assert.IsFalse(dict.TryAdd(6, x => 9, out monitor));
                Assert.AreEqual(12, monitor);
                foreach (var kvp in dict)
                {
                    Assert.AreEqual(kvp.Value, kvp.Key * 2);
                }
            }
Ejemplo n.º 3
0
            public void BadAddKV()
            {
                var dict = new ThreadSafeDictionary <int, int>();

                dict.Add(1, 1);
                dict.Add(new KeyValuePair <int, int>(1, 2));
            }
 private TypeReflector()
 {
     this._nonAttachableMemberCache            = new ThreadSafeDictionary <string, XamlMember>();
     this._nonAttachableMemberCache.IsComplete = true;
     this._attachableMemberCache            = new ThreadSafeDictionary <string, XamlMember>();
     this._attachableMemberCache.IsComplete = true;
     this._baseType.Value                      = XamlLanguage.Object;
     this._boolTypeBits                        = -57015;
     this._collectionKind                      = XamlCollectionKind.None;
     this._addMethod.Value                     = null;
     this._contentProperty.Value               = null;
     this._deferringLoader.Value               = null;
     this._dictionaryKeyProperty.Value         = null;
     this._getEnumeratorMethod.Value           = null;
     this._isReadOnlyMethod.Value              = null;
     this._runtimeNameProperty.Value           = null;
     this._typeConverter.Value                 = null;
     this._uidProperty.Value                   = null;
     this._valueSerializer.Value               = null;
     this._xamlSetMarkupExtensionHandler.Value = null;
     this._xamlSetTypeConverterHandler.Value   = null;
     this._xmlLangProperty.Value               = null;
     base.CustomAttributeProvider              = null;
     this.Invoker = XamlTypeInvoker.UnknownInvoker;
 }
 /// <summary>
 /// Initializes a new instance of the ContainerControllerFactory class that will initialize
 /// controllers through StructureMap containers
 /// </summary>
 /// <param name="resolver">
 ///     Dependency container resolver from which to pull dependency instances
 /// </param>
 /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="resolver"/> is null</exception>
 public ContainerControllerFactory(IContainerResolver resolver)
 {
     Ensure.Argument.NotNull(resolver, "resolver");
     this.ContainerResolver = resolver;
     this.typeCache = new ThreadSafeDictionary<IContainer, IDictionary<string, Type>>();
     ContainerControllerFactory._sessionStateCache = new ConcurrentDictionary<Type, SessionStateBehavior>();
 }
 public void GetEnumerator_CastToIEnumerble_ReturnsEnumerator()
 {
     var dictionary = new ThreadSafeDictionary<string, string>();
     var enumerator = ((IEnumerable)dictionary).GetEnumerator();
     
     Assert.IsNotNull(enumerator);
 }
Ejemplo n.º 7
0
        public ControllerTypeResolver(
            IEnumerable <string> areaNamespacesToIgnore,
            RouteCollection routes,
            IControllerBuilder controllerBuilder,
            IBuildManager buildManager
            )
        {
            if (areaNamespacesToIgnore == null)
            {
                throw new ArgumentNullException("areaNamespacesToIgnore");
            }
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            if (controllerBuilder == null)
            {
                throw new ArgumentNullException("controllerBuilder");
            }
            if (buildManager == null)
            {
                throw new ArgumentNullException("buildManager");
            }

            this.areaNamespacesToIgnore = areaNamespacesToIgnore;
            this.routes            = routes;
            this.controllerBuilder = controllerBuilder;
            this.buildManager      = buildManager;

            Cache = new ThreadSafeDictionary <string, Type>();
        }
 /// <summary>
 /// Initializes a new instance of the ContainerControllerFactory class that will initialize
 /// controllers through StructureMap containers
 /// </summary>
 /// <param name="resolver">
 ///     Dependency container resolver from which to pull dependency instances
 /// </param>
 /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="resolver"/> is null</exception>
 public ContainerControllerFactory(IContainerResolver resolver)
 {
     Ensure.Argument.NotNull(resolver, "resolver");
     this.ContainerResolver = resolver;
     this.typeCache         = new ThreadSafeDictionary <IContainer, IDictionary <string, Type> >();
     ContainerControllerFactory._sessionStateCache = new ConcurrentDictionary <Type, SessionStateBehavior>();
 }
Ejemplo n.º 9
0
        // Used for UnknownReflector only
        private TypeReflector()
        {
            _nonAttachableMemberCache            = new ThreadSafeDictionary <string, XamlMember>();
            _nonAttachableMemberCache.IsComplete = true;
            _attachableMemberCache            = new ThreadSafeDictionary <string, XamlMember>();
            _attachableMemberCache.IsComplete = true;

            _baseType.Value = XamlLanguage.Object;
            _boolTypeBits   = (int)BoolTypeBits.Default | (int)BoolTypeBits.Unknown | (int)BoolTypeBits.WhitespaceSignificantCollection | (int)BoolTypeBits.AllValid;
            _collectionKind = XamlCollectionKind.None;

            // Set all the nullable references explicitly so that IsSet will be equal to true
            _addMethod.Value                     = null;
            _contentProperty.Value               = null;
            _deferringLoader.Value               = null;
            _dictionaryKeyProperty.Value         = null;
            _getEnumeratorMethod.Value           = null;
            _isReadOnlyMethod.Value              = null;
            _runtimeNameProperty.Value           = null;
            _typeConverter.Value                 = null;
            _uidProperty.Value                   = null;
            _valueSerializer.Value               = null;
            _xamlSetMarkupExtensionHandler.Value = null;
            _xamlSetTypeConverterHandler.Value   = null;
            _xmlLangProperty.Value               = null;
            CustomAttributeProvider              = null;

            Invoker = XamlTypeInvoker.UnknownInvoker;
        }
Ejemplo n.º 10
0
        public static IEnumerable <AtomPropertyInfo> GetEntityProperties(this Type type, bool keyOnly = false)
        {
            ThreadSafeDictionary <Type, IEnumerable <AtomPropertyInfo> > cache = keyOnly ? _keyList : _allList;


            return(cache.GetOrAdd(type, t =>
            {
                List <AtomPropertyInfo> list = new List <AtomPropertyInfo>();

                foreach (PropertyInfo p in type.GetCachedProperties())
                {
                    KeyAttribute a = p.GetCustomAttribute <KeyAttribute>();
                    if (a == null)
                    {
                        continue;
                    }
                    NotMappedAttribute notMapped = p.GetCustomAttribute <NotMappedAttribute>();
                    if (notMapped != null)
                    {
                        continue;
                    }
                    if (keyOnly)
                    {
                        list.Add(new AtomPropertyInfo(type, p, true));
                    }
                    else
                    {
                        list.Add(new AtomPropertyInfo(type, p, false));
                    }
                }

                return list;
            }));
        }
Ejemplo n.º 11
0
                public void RacingWrite()
                {
                    var dict = new ThreadSafeDictionary <int, int>();

                    for (int i = 0; i != _threads.Length; ++i)
                    {
                        _threads[i] = new Thread((object obj) =>
                        {
                            int offset = (int)obj;
                            for (int j = 0; j != 21000; ++j)
                            {
                                dict[j] = j % 3;
                            }
                            for (int j = 0; j != 20000; ++j)
                            {
                                dict[j] = offset + j % 10;
                            }
                        });
                        _params[i] = i * 10;
                    }
                    StartThreads();
                    EndThreads();
                    for (int i = 0; i != 20000; ++i)
                    {
                        Assert.AreEqual(i % 10, dict[i] % 10);
                    }
                    for (int i = 20000; i != 21000; ++i)
                    {
                        Assert.AreEqual(i % 3, dict[i] % 3);
                    }
                }
Ejemplo n.º 12
0
            public void BadAdd()
            {
                var dict = new ThreadSafeDictionary <int, int>();

                dict.Add(1, 1);
                dict.Add(1, 2);
            }
Ejemplo n.º 13
0
        /// <summary>
        /// Engines root contextualize your engines and entities. You don't need to limit yourself to one EngineRoot
        /// as multiple engines root could promote separation of scopes. The EntitySubmissionScheduler checks
        /// periodically if new entity must be submitted to the database and the engines. It's an external
        /// dependencies to be independent by the running platform as the user can define it.
        /// The EntitySubmissionScheduler cannot hold an EnginesRoot reference, that's why
        /// it must receive a weak reference of the EnginesRoot callback.
        /// </summary>
        public EnginesRoot(IEntitiesSubmissionScheduler entitiesComponentScheduler)
        {
            _entitiesOperations        = new ThreadSafeDictionary <ulong, EntitySubmitOperation>();
            serializationDescriptorMap = new SerializationDescriptorMap();
            _reactiveEnginesAddRemove  = new FasterDictionary <RefWrapper <Type>, FasterList <IEngine> >();
            _reactiveEnginesSwap       = new FasterDictionary <RefWrapper <Type>, FasterList <IEngine> >();
            _enginesSet                  = new FasterList <IEngine>();
            _enginesTypeSet              = new HashSet <Type>();
            _disposableEngines           = new FasterList <IDisposable>();
            _transientEntitiesOperations = new FasterList <EntitySubmitOperation>();

            _groupEntityComponentsDB =
                new FasterDictionary <uint, FasterDictionary <RefWrapper <Type>, ITypeSafeDictionary> >();
            _groupsPerEntity    = new FasterDictionary <RefWrapper <Type>, FasterDictionary <uint, ITypeSafeDictionary> >();
            _groupedEntityToAdd = new DoubleBufferedEntitiesToAdd();
            _entityLocatorMap   = new FasterList <EntityLocatorMapElement>();
            _egidToLocatorMap   = new FasterDictionary <uint, FasterDictionary <uint, EntityLocator> >();

            _entityStreams = EntitiesStreams.Create();
            _groupFilters  = new FasterDictionary <RefWrapper <Type>, FasterDictionary <ExclusiveGroupStruct, GroupFilters> >();
            _entitiesDB    = new EntitiesDB(this);

            scheduler        = entitiesComponentScheduler;
            scheduler.onTick = new EntitiesSubmitter(this);
#if UNITY_BURST
            AllocateNativeOperations();
#endif
        }
Ejemplo n.º 14
0
 public Entity()
 {
     unchecked {
         ID = Interlocked.Increment(ref NextID);
     }
     components = new ThreadSafeDictionary <Type, IComponent>();
 }
Ejemplo n.º 15
0
 public void Dispose()
 {
     try
     {
         if (this.timer_0 != null)
         {
             this.timer_0.Enabled = false;
             this.timer_0.Close();
             this.timer_0.Dispose();
             this.timer_0 = null;
         }
         if (this.threadSafeDictionary_0 != null)
         {
             this.threadSafeDictionary_0.Clear();
             this.threadSafeDictionary_0.Dispose();
         }
         this.threadSafeDictionary_0 = null;
         this.VAT_PHAM = null;
         this.VAT_PHAM_QUYEN_UU_TIEN = null;
         this.object_0 = null;
         this.object_1 = null;
     }
     catch (Exception exception)
     {
     }
 }
        public void ConcurrentGetOrAdd_ThreadSafeDictionary_Simplified()
        {
            // Without all the counters and boolean to validate the behaviour
            // The code is really simple
            var threadSafeDictionary = new ThreadSafeDictionary <long, string>();

            string Factory(long id)
            {
                switch (id)
                {
                case 1:
                    return("One");

                case 6:
                    return("Six");

                default:
                    throw new Exception("Not found");
                }
            };

            Parallel.For(
                0,
                50,
                i =>
            {
                var name = threadSafeDictionary.GetOrCreateValue(
                    6,
                    Factory);

                Assert.That(name, Does.StartWith("Six"));
            });
        }
Ejemplo n.º 17
0
            public void EqualityComparer()
            {
                var dict = new ThreadSafeDictionary <string, int>(StringComparer.InvariantCultureIgnoreCase);

                dict.Add("Weißbier", 93);
                Assert.AreEqual(dict["WEISSBIER"], 93);
                dict["weissbier"] = 777;
                Assert.AreEqual(dict["Weißbier"], 777);
                dict.Add(new KeyValuePair <string, int>("Δίος", 21));
                Assert.AreEqual(2, dict.Count);
                Assert.IsTrue(dict.ContainsKey("ΔΊΟΣ"));
                Assert.IsTrue(dict.Contains(new KeyValuePair <string, int>("δίος", 21)));
                Assert.IsFalse(dict.Contains(new KeyValuePair <string, int>("δίος", 3)));
                Assert.IsTrue(dict.Keys.Contains("δίος"));
                Assert.IsFalse(dict.Keys.Contains("δίοςδίος"));
                Assert.IsTrue(dict.Values.Contains(770, new RoundedEquality()));
                Assert.IsFalse(dict.Values.Contains(770));
                int result;

                Assert.IsTrue(dict.TryGetValue("ΔΊΟΣ", out result) && result == 21);
                Assert.IsFalse(dict.TryGetValue("Eggplant", out result));
                Assert.IsFalse(dict.Remove("aubergine"));
                Assert.IsTrue(dict.Remove("Δίος"));
                Assert.IsFalse(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 93)));
                Assert.IsTrue(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 777)));
                Assert.IsFalse(dict.ContainsKey("WEISSBIER"));
                Assert.IsFalse(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 777)));
                Assert.AreEqual(dict.Count, 0);
                dict.Add("Palmer", 1111);
                Assert.IsFalse(dict.Remove("Palmer", 1110, out result));
                Assert.AreEqual(dict.Count, 1);
                Assert.IsTrue(dict.Remove("Palmer", 1110, new RoundedEquality(), out result));
                Assert.AreEqual(result, 1111);
                Assert.AreEqual(dict.Count, 0);
            }
Ejemplo n.º 18
0
            public void ConstantReturns()
            {
                var dict = new ThreadSafeDictionary <int, int>();

                Assert.IsFalse(((ICollection <KeyValuePair <int, int> >)dict).IsReadOnly);
                Assert.IsTrue(((ICollection <int>)dict.Keys).IsReadOnly && ((ICollection <int>)dict.Values).IsReadOnly);
            }
Ejemplo n.º 19
0
 public EntityManager(World world)
 {
     World = world;
     //entities = new HashSet<Entity>();
     entities     = new ThreadSafeDictionary <int, Entity>();
     EntityFinder = new EntityFinder(entities);
 }
        public void ConcurrentGetOrAdd_ThreadSafeDictionary()
        {
            // Some have even go further and have totally rewrite an alternative to ConcurrentDictionary
            // That takes all into account, to have something performant hen reading (no locks)
            // And without the flows of the ConcurrentDictionary
            // The code is really complex (see all what have been put in the Pfz folder),
            // but as you can see in that example the ThreadSafeDictionary seems to effectively do what we need,
            // and without having to wrap our factory into a Lazy wrapper
            // sources:
            // https://www.codeproject.com/Articles/548406/Dictionary-plus-Locking-versus-ConcurrentDictionar
            var threadSafeDictionary = new ThreadSafeDictionary <long, string>();

            var factoryCount   = 0;
            var exceptionCount = 0;

            Parallel.For(
                0,
                50,
                i =>
            {
                var added = false;

                string name;
                try
                {
                    name = threadSafeDictionary.GetOrCreateValue(
                        6,
                        n =>
                    {
                        added = true;
                        Interlocked.Increment(ref factoryCount);
                        Thread.Sleep(10);
                        if (factoryCount == 1)
                        {
                            throw new Exception("Issue while accessing a resource (network, file system, ...)");
                        }
                        return("Six" + "-from-" + i);
                    });
                }
                catch (Exception)
                {
                    Interlocked.Increment(ref exceptionCount);
                    return;
                }

                Assert.That(name, Does.StartWith("Six"));
                if (added)
                {
                    Assert.That(name, Does.EndWith("-from-" + i));
                }
                else
                {
                    Assert.That(name, Does.Not.EndWith("-from-" + i));
                }
            });

            Assert.That(factoryCount, Is.EqualTo(2));
            Assert.That(exceptionCount, Is.EqualTo(1));
        }
Ejemplo n.º 21
0
 public ExtensionHandlerBase(IBundleContext bundleContext, string extensionPoint)
 {
     BundleContext  = bundleContext;
     ExtensionPoint = extensionPoint;
     ExtensionDatas = new ThreadSafeDictionary <Extension, List <T> >();
     HandleExtensions();
     BundleContext.ExtensionChanged += new EventHandler <ExtensionEventArgs>(BundleContextExtensionChanged);
 }
        public void Indexer_should_always_return_correct_values()
        {
            var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>());

            dict["1"] = "Any Item 1";

            Assert.That(dict["1"], Is.Not.EqualTo(default(string)));
        }
        public void Contains_should_eval_to_true_if_exists()
        {
            var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>());

            dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue"));

            Assert.That(dict.Contains(new KeyValuePair <string, string>("AnyKey", "AnyValue")), Is.True);
        }
        public void Add_should_always_add_the_key_und_value()
        {
            var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>());

            dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue"));

            Assert.That(dict["AnyKey"], Is.EqualTo("AnyValue"));
        }
Ejemplo n.º 25
0
 public PlayerManager()
 {
     pendingPlayers     = new ThreadSafeDictionary <NebulaConnection, Player>();
     syncingPlayers     = new ThreadSafeDictionary <NebulaConnection, Player>();
     connectedPlayers   = new ThreadSafeDictionary <NebulaConnection, Player>();
     savedPlayerData    = new ThreadSafeDictionary <string, PlayerData>();
     availablePlayerIds = new ThreadSafeQueue <ushort>();
 }
Ejemplo n.º 26
0
 public StatisticsManager()
 {
     Requestors           = new ThreadSafeDictionary <ushort, NebulaConnection>();
     StatisticalSnapShots = new List <StatisticalSnapShot>();
     IsStatisticsNeeded   = false;
     instance             = this;
     ClearCapturedData();
 }
Ejemplo n.º 27
0
        public PlayerManager(List <Player> players, ServerConfig serverConfig)
        {
            allPlayersByName   = new ThreadSafeDictionary <string, Player>(players.ToDictionary(x => x.Name), false);
            currentPlayerId    = players.Count == 0 ? (ushort)0 : players.Max(x => x.Id);
            defaultPlayerStats = serverConfig.DefaultPlayerStats;

            this.serverConfig = serverConfig;
        }
Ejemplo n.º 28
0
 public Transact()
 {
     WriteLog            = new ThreadSafeDictionary <IResource, object>();
     ReadLog             = new ThreadSafeDictionary <IResource, object>();
     ParentTransaction   = _currentTransaction;
     _currentTransaction = this;
     _thread             = Thread.CurrentThread;
 }
Ejemplo n.º 29
0
            public void PathologicalHashAlgorithm()
            {
                var dict = new ThreadSafeDictionary <int, int>(Enumerable.Range(0, 1000).Zip(Enumerable.Range(0, 1000), (k, v) => new KeyValuePair <int, int>(k, v * 2)));

                for (int i = 999; i != -1; --i)
                {
                    Assert.AreEqual(dict[i], i * 2);
                }
            }
        public void Keys_should_return_all_keys_in_Dictionary()
        {
            var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>());

            dict.Add("1", "Any Item 1");

            Assert.That(dict.Keys.Count, Is.EqualTo(1));
            Assert.That(dict.Keys.First(), Is.EqualTo("1"));
        }
Ejemplo n.º 31
0
 private GroupBuilder(IEnumerable <TSource> source, IEqualityComparer <TKey> comparer, Func <TSource, TKey> keySelector, Func <TSource, TElement> resultSelector)
 {
     _enumerator              = source.GetEnumerator();
     _results                 = new ThreadSafeQueue <Grouping <TKey, TElement> >();
     _proxies                 = new ThreadSafeDictionary <TKey, ProxyObservable <TElement> >(comparer);
     _keySelector             = keySelector;
     _resultSelector          = resultSelector;
     _cancellationTokenSource = new CancellationTokenSource();
 }
Ejemplo n.º 32
0
 public ImageList(IGUIContext context, string name, Size imageSize, bool shouldDisposeImages)
 {
     Context             = context;
     m_Images            = new ThreadSafeDictionary <string, TextureImage>();
     Name                = name;
     ImageSize           = imageSize;
     ShouldDisposeImages = shouldDisposeImages;
     LoadMissingImage();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ActionMethodParameterResolver"/> class.
        /// </summary>
        public ActionMethodParameterResolver(
            IControllerDescriptorFactory controllerDescriptorFactory
            )
        {
            if (controllerDescriptorFactory == null)
                throw new ArgumentNullException("controllerDescriptorFactory");

            this.controllerDescriptorFactory = controllerDescriptorFactory;

            Cache = new ThreadSafeDictionary<string, IEnumerable<string>>();
        }
 private static Action Add(ThreadSafeDictionary<string, string> dictionary)
 {
     return () =>
         {
             Thread.Sleep(50);
             for (int i = 0; i < 50; i++)
             {
                 dictionary.TryAdd("Key", "Value");
             }
             
         };
 }
        private static Action Remove(ThreadSafeDictionary<string, string> dictionary)
        {
            return () =>
            {
                Thread.Sleep(50);
                for (int i = 0; i < 50; i++)
                {
                    string value;
                    dictionary.TryRemove("Key", out value);
                }

            };
        }
Ejemplo n.º 36
0
        public Data()
        {
            labels = new ThreadSafeDictionary<string, List<Label>>();

            conversations = new ThreadSafeCollection<Conversation>();
            messages = new ThreadSafeCollection<Message>();
            documents = new ThreadSafeCollection<Document>();
            versions = new ThreadSafeCollection<DocumentVersion>();
            persons = new ThreadSafeCollection<Person>();
            profiles = new ThreadSafeCollection<Profile>();
            statusUpdates = new ThreadSafeCollection<UserStatus>();
            statusUpdateAttachments = new ThreadSafeCollection<UserStatusAttachment>();

            keyedMessages = new Dictionary<long, Message>();
            keyedDocuments = new Dictionary<long, Document>();
            keyedPersons = new Dictionary<long, Person>();
            keyedConversations = new Dictionary<string, Conversation>();
            keyedStatusUpdates = new Dictionary<string, UserStatus>();
            keyedProfiles = new Dictionary<string, Profile>();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// IP Details From IP Address
        /// </summary>
        /// <param name="ip">
        /// The ip.
        /// </param>
        /// <param name="format">
        /// The format.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <param name="culture">
        /// The culture.
        /// </param>
        /// <param name="browser">
        /// The browser.
        /// </param>
        /// <param name="os">
        /// The os.
        /// </param>
        /// <returns>
        /// IPLocator Class
        /// </returns>
        public ThreadSafeDictionary<string, string> GetData([CanBeNull] string ip, [CanBeNull] string format, bool callback, string culture, string browser, string os)
        {
            CodeContracts.ArgumentNotNull(ip, "ip");

            ThreadSafeDictionary<string, string> res = new ThreadSafeDictionary<string, string>();

            if (YafContext.Current.Get<YafBoardSettings>().IPLocatorResultsMapping.IsNotSet() ||
                YafContext.Current.Get<YafBoardSettings>().IPLocatorUrlPath.IsNotSet())
            {
                return res;
            }

            if (YafContext.Current.Get<YafBoardSettings>().EnableIPInfoService)
            {
                try
                {
                    string path = YafContext.Current.Get<YafBoardSettings>().IPLocatorUrlPath.FormatWith(Utils.Helpers.IPHelper.GetIp4Address(ip));
                    var client = new WebClient();
                    string[] eResult = client.DownloadString(path).Split(';');
                    string[] sray = YafContext.Current.Get<YafBoardSettings>().IPLocatorResultsMapping.Trim().Split(',');
                    if (eResult.Length > 0 && eResult.Length == sray.Length)
                    {
                        int i = 0;
                        foreach (string str in eResult)
                        {
                            res.Add(sray[i].Trim(), str);
                            i++;
                        }
                    }
                }
                catch
                {
                    return res;
                }
            }

            return res;
        }
        public ControllerTypeResolver(
			IEnumerable<string> areaNamespacesToIgnore,
			RouteCollection routes,
			IControllerBuilder controllerBuilder,
			IBuildManager buildManager            
			)
        {
            if (areaNamespacesToIgnore == null)
                throw new ArgumentNullException("areaNamespacesToIgnore");
            if (routes == null)
                throw new ArgumentNullException("routes");
            if (controllerBuilder == null)
                throw new ArgumentNullException("controllerBuilder");
            if (buildManager == null)
                throw new ArgumentNullException("buildManager");

            this.areaNamespacesToIgnore = areaNamespacesToIgnore;
            this.routes = routes;
            this.controllerBuilder = controllerBuilder;
            this.buildManager = buildManager;

            Cache = new ThreadSafeDictionary<string, Type>();
        }
Ejemplo n.º 39
0
 private ServiceState()
 {
     AllLogs = new ThreadSafeList<RotatedLog>();
     LastKnownLogHashes = new ThreadSafeDictionary<string, string>();
     HashesOfPendingLogs = new ThreadSafeQueue<string>();
 }
Ejemplo n.º 40
0
		public AjaxWebsocket()
		{
			sessions = new ThreadSafeDictionary<int, Session>();
			timer = new MultiTimer<int>(KeepConnectionTimer, 1024, 20000);
		}
Ejemplo n.º 41
0
        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (!this.IsPostBack)
              {
            this.CreateUserWizard1.MembershipProvider = Config.MembershipProvider;

            this.PageLinks.AddLink(this.Get<YafBoardSettings>().Name, YafBuildLink.GetLink(ForumPages.forum));
            this.PageLinks.AddLink(this.GetText("TITLE"));

            // handle the CreateUser Step localization
            this.SetupCreateUserStep();

            // handle other steps localization
            ((Button)this.CreateUserWizard1.FindWizardControlRecursive("ProfileNextButton")).Text = this.GetText("SAVE");
            ((Button)this.CreateUserWizard1.FindWizardControlRecursive("ContinueButton")).Text = this.GetText("CONTINUE");

            // get the time zone data source
            var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones");
            timeZones.DataSource = StaticDataHelper.TimeZones();

            // get the country data source
            var country = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("Country");
            country.DataSource = StaticDataHelper.Country();

            if (this.Get<YafBoardSettings>().EnableIPInfoService && this._UserIpLocator == null)
            {
              // vzrus: we should always get not null class here
            this._UserIpLocator = new IPDetails().GetData(
                this.Get<HttpRequestBase>().UserHostAddress,
                "text",
                false,
                this.PageContext().CurrentForumPage.Localization.Culture.Name,
                string.Empty,
                string.Empty);
            }

            if (!this.Get<YafBoardSettings>().EmailVerification)
            {
              // automatically log in created users
              this.CreateUserWizard1.LoginCreatedUser = true;
              this.CreateUserWizard1.DisableCreatedUser = false;

              // success notification localization
              ((Literal)this.CreateUserWizard1.FindWizardControlRecursive("AccountCreated")).Text =
            this.Get<IBBCode>().MakeHtml(this.GetText("ACCOUNT_CREATED"), true, false);
            }
            else
            {
              this.CreateUserWizard1.LoginCreatedUser = false;
              this.CreateUserWizard1.DisableCreatedUser = true;

              // success notification localization
              ((Literal)this.CreateUserWizard1.FindWizardControlRecursive("AccountCreated")).Text =
            this.Get<IBBCode>().MakeHtml(this.GetText("ACCOUNT_CREATED_VERIFICATION"), true, false);
            }

            this.CreateUserWizard1.FinishDestinationPageUrl = YafForumInfo.ForumURL;

            this.DataBind();

            decimal hours = 0;

            // fill location field
            // Trying to consume data about user IP whereabouts
            if (this.Get<YafBoardSettings>().EnableIPInfoService && this._UserIpLocator["StatusCode"] != "OK")
            {
            LegacyDb.eventlog_create(null, this.GetType().ToString(), "Geolocation Service reports: " + this._UserIpLocator["StatusMessage"], EventLogTypes.Information);
            }

            if (this.Get<YafBoardSettings>().EnableIPInfoService && this._UserIpLocator.Count > 0 && this._UserIpLocator["StatusCode"] == "OK")
            {
            var location = new StringBuilder();

            if (this._UserIpLocator["CountryName"].IsSet())
            {
                country.Items.FindByValue(this.Get<ILocalization>().Culture.Name.Substring(2, 2)).Selected = true;
            }

            if (this._UserIpLocator["RegionName"].IsSet())
            {
                location.AppendFormat(", {0}", this._UserIpLocator["RegionName"]);
            }

            if (this._UserIpLocator["CityName"].IsSet())
            {
                location.AppendFormat(", {0}", this._UserIpLocator["CityName"]);
            }

            this.CreateUserWizard1.FindControlRecursiveAs<TextBox>("Location").Text = location.ToString();

            if (this._UserIpLocator["TimeZone"].IsSet())
            {
                try
                {
                    hours = this._UserIpLocator["TimeZone"].ToType<decimal>() * 60;
                }
                catch (FormatException)
                {
                    hours = 0;
                }
            }
            }

            timeZones.Items.FindByValue(hours.ToString()).Selected = true;
            this.CreateUserWizard1.FindWizardControlRecursive("UserName").Focus();
              }

              // password requirement parameters...
              var requirementText = (LocalizedLabel)this.CreateUserStepContainer.FindControl("LocalizedLabelRequirementsText");
              requirementText.Param0 = this.Get<MembershipProvider>().MinRequiredPasswordLength.ToString();
              requirementText.Param1 = this.Get<MembershipProvider>().MinRequiredNonAlphanumericCharacters.ToString();

              // max user name length
              var usernamelehgthText =
            (LocalizedLabel)this.CreateUserStepContainer.FindControl("LocalizedLabelLohgUserNameWarnText");
              usernamelehgthText.Param0 = this.Get<YafBoardSettings>().UserNameMaxLength.ToString();

              if (this.Get<YafBoardSettings>().CaptchaTypeRegister == 2)
              {
            this.SetupRecaptchaControl();
              }
        }
 /// <summary>
 /// Initializes a new instance of the ContainerControllerFactory class that will initialize
 /// controllers through StructureMap containers
 /// </summary>
 /// <param name="resolver">
 ///     Dependency container resolver from which to pull dependency instances
 /// </param>
 /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="resolver"/> is null</exception>
 public ContainerControllerFactory(IContainerResolver resolver)
 {
     Ensure.Argument.NotNull(resolver, "resolver");
     this.ContainerResolver = resolver;
     this.typeCache = new ThreadSafeDictionary<IContainer, IDictionary<string, Type>>();
 }
 public void TryAdd_CanHandleMultipleThreads()
 {
     var dictionary = new ThreadSafeDictionary<string, string>();            
     ParallelInvoker.Invoke(50, Add(dictionary), Remove(dictionary));                         
 }
 private RepeatedPackageNotifyManager()
 {
     m_Packages = new ThreadSafeDictionary<String, RepeatedPackage>(); 
     ReadConfig();
     InitSavePackagesThread();    
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultActionMethodParameterResolver"/> class.
 /// </summary>
 public DefaultActionMethodParameterResolver()
 {
     Cache = new ThreadSafeDictionary<string, IEnumerable<string>>();
 }
        private void CycleGeneration(List<INode> population, List<INode> mergePopulation = null)
        {
            NodeContext zeroContext = new NodeContext();
            zeroContext.AvailableCollections = fitnessFunction.GetCollections();
            zeroContext.AvailableInputs = fitnessFunction.GetInputs();

            // Create a new set of tests
            fitnessFunction.Initialise();

            // Get the fitness measure for each individual
            var fitnesses = new ThreadSafeDictionary<int, double>();
            for (int i = 0; i < population.Count; ++i)
            {
                fitnesses[i] = this.fitnessFunction.CalculateFitness(population[i]);
                fitnesses[i] = Math.Abs(fitnesses[i]);
            }

            this.selector.Initialise(population, fitnesses);

            var bestIndividuals = from k in fitnesses.Keys orderby fitnesses[k] ascending select population[k];

            INode best = bestIndividuals.FirstOrDefault();
            this.BestIndividual = best;

            // Update the best fitness
            this.BestFitness = fitnesses.Values.Min();

            List<INode> newPopulation = new List<INode>();

            if (mergePopulation == null)
            {
                // Always keep the best 10%
                newPopulation.AddRange(bestIndividuals.Take(this.populationSize / 10));

                while (newPopulation.Count < this.populationSize)
                {
                    INode parentA = this.selector.SelectNode();
                    INode parentB = this.selector.SelectNode();
                    INode child = this.reproductionFunction.Reproduce(parentA, parentB);
                    //INode child = (INode) this.selector.SelectNode().Clone();
                    this.mutator.Mutate(ref child, zeroContext);
                    newPopulation.Add(child);

                }

                // Replace the old population;
                population.Clear();
                population.AddRange(newPopulation);
            }
            else
            {
                mergePopulation.AddRange(bestIndividuals.Take(this.populationSize / 10));

                // Reinitialise the population
                this.IntialisePopulation(population);
            }
        }
 public EntityPropertyRules(Type type)
 {
     TypeName = type.Name;
     Type = type;
     Rules = new ThreadSafeDictionary<string, SerializeMode>();
 }
		public void MultiThreadAccess()
		{
			MultiThreadRunner<IDictionary<int, int>>.ExecuteAction[] actions =
				new MultiThreadRunner<IDictionary<int, int>>.ExecuteAction[]
					{
						delegate(IDictionary<int, int> d)
							{
								try
								{
									log.DebugFormat("T{0} Add", Thread.CurrentThread.Name);
									write++;
									d.Add(rnd.Next(), rnd.Next());
								}
								catch (ArgumentException)
								{
									// duplicated key
								}
							}, 
						delegate(IDictionary<int, int> d)
						 	{
								log.DebugFormat("T{0} ContainsKey", Thread.CurrentThread.Name);
					   		read++;
					   		d.ContainsKey(rnd.Next());
					   	}, 
						delegate(IDictionary<int, int> d)
			   	   	{
								log.DebugFormat("T{0} Remove", Thread.CurrentThread.Name);
			   	   		write++;
			   	   		d.Remove(rnd.Next());
			   	   	}, 
						delegate(IDictionary<int, int> d)
	   	   	   	{
								log.DebugFormat("T{0} TryGetValue", Thread.CurrentThread.Name);
	   	   	   		read++;
	   	   	   		int val;
	   	   	   		d.TryGetValue(rnd.Next(), out val);
	   	   	   	}, 
						delegate(IDictionary<int, int> d)
 	   	   	   	{
 	   	   	   		try
 	   	   	   		{
									log.DebugFormat("T{0} get_this[]", Thread.CurrentThread.Name);
 	   	   	   			read++;
 	   	   	   			int val = d[rnd.Next()];
 	   	   	   		}
 	   	   	   		catch (KeyNotFoundException)
 	   	   	   		{
 	   	   	   			// not foud key
 	   	   	   		}
 	   	   	   	}, 
						delegate(IDictionary<int, int> d)
 	   	   	   	{
								log.DebugFormat("T{0} set_this[]", Thread.CurrentThread.Name);
 	   	   	   		write++;
 	   	   	   		d[rnd.Next()] = rnd.Next();
 	   	   	   	},
						delegate(IDictionary<int, int> d)
							{
								log.DebugFormat("T{0} Keys", Thread.CurrentThread.Name);
								read++;
								IEnumerable<int> e = d.Keys;
							},
						delegate(IDictionary<int, int> d)
					   	{
								log.DebugFormat("T{0} Values", Thread.CurrentThread.Name);
					   		read++;
					   		IEnumerable<int> e = d.Values;
					   	}, 
						delegate(IDictionary<int, int> d)
			   	   	{
								log.DebugFormat("T{0} GetEnumerator", Thread.CurrentThread.Name);
			   	   		read++;
			   	   		foreach (KeyValuePair<int, int> pair in d)
			   	   		{
			   	   			
			   	   		}
			   	   	},
					};
			MultiThreadRunner<IDictionary<int, int>> mtr = new MultiThreadRunner<IDictionary<int, int>>(20, actions);
			IDictionary<int, int> wrapper = new ThreadSafeDictionary<int, int>(new Dictionary<int, int>());
			mtr.EndTimeout = 2000;
			mtr.Run(wrapper);
			log.DebugFormat("{0} reads, {1} writes -- elements {2}", read, write, wrapper.Count);
		}
Ejemplo n.º 49
0
        /// <summary>
        /// Generate a new population based on the fitness of the previous population's
        /// individuals
        /// </summary>
        public void ProcessGeneration()
        {
            NodeContext zeroContext = new NodeContext();
            zeroContext.AvailableCollections = fitnessFunction.GetCollections();
            zeroContext.AvailableInputs = fitnessFunction.GetInputs();

            // Create a new set of tests
            fitnessFunction.Initialise();

            Console.WriteLine("Calculate");

            // Get the fitness measure for each individual
            var fitnesses = new ThreadSafeDictionary<int, double>();
            for (int i = 0; i < this.population.Count; ++i)
            {
                fitnesses[i] = this.fitnessFunction.CalculateFitness(this.population[i]);
                fitnesses[i] = Math.Abs(fitnesses[i]);
            }

            //var loopResult = Parallel.For(0, this.population.Count, delegate(int i)
            //{
            //    fitnesses[i] = Math.Abs(this.fitnessFunction.CalculateFitness(this.population[i]));
            //    //fitnesses[i] = Math.Abs(fitnesses[i]);
            //});

            //if (!loopResult.IsCompleted)
            //{
            //    Console.WriteLine("Loop failed");
            //}

            this.selector.Initialise(this.population, fitnesses);

            var bestIndividuals = from k in fitnesses.Keys orderby fitnesses[k] ascending select this.population[k];

            INode best = bestIndividuals.FirstOrDefault();
            this.BestIndividual = best;

            // Update the best fitness
            this.BestFitness = fitnesses.Values.Min();
            this.AverageFitness = fitnesses.Values.Sum(f => f < Double.MaxValue ? f : 0)/fitnesses.Values.Count(f => f < Double.MaxValue);

            Console.WriteLine("Best fitness: {0} {1}", fitnesses.Values.Min(), best);

            this.PrintAverageTreeSize();

            List<INode> newPopulation = new List<INode>();

            // Always keep the best 10%
            newPopulation.AddRange(bestIndividuals.Take(this.populationSize / 10));

            while (newPopulation.Count < this.populationSize)
            {
                INode parentA = this.selector.SelectNode();
                INode parentB = this.selector.SelectNode();
                INode child = this.reproductionFunction.Reproduce(parentA, parentB);
                //INode child = (INode) this.selector.SelectNode().Clone();
                this.mutator.Mutate(ref child, zeroContext);
                newPopulation.Add(child);

            }

            // Replace the old population);
            this.population = newPopulation;
        }