internal static FieldDefinition GetRequiredPrimaryKeyValue <T>(this Dictionary <string, object> updateFields, out object idValue)
        {
            var pkField = typeof(T).GetModelDefinition().PrimaryKey;

            if (pkField == null)
            {
                throw new NotSupportedException($"'{typeof(T).Name}' does not have a primary key");
            }

            idValue = updateFields.TryRemove(pkField.Name, out var nameValue)
                ? nameValue
                : pkField.Alias != null && updateFields.TryRemove(pkField.Alias, out var aliasValue)
                    ? aliasValue
                    : null;

            if (idValue == null)
            {
                var caseInsensitiveMap =
                    new Dictionary <string, object>(updateFields, StringComparer.InvariantCultureIgnoreCase);
                idValue = caseInsensitiveMap.TryRemove(pkField.Name, out nameValue)
                    ? nameValue
                    : pkField.Alias != null && caseInsensitiveMap.TryRemove(pkField.Alias, out aliasValue)
                        ? aliasValue
                        : new NotSupportedException(
                    $"UpdateOnly<{typeof(T).Name}> requires a '{pkField.Name}' Primary Key Value");
            }

            return(pkField);
        }
Esempio n. 2
0
        /// <summary>
        /// Finishes profiling for 'command', recording durations.
        /// </summary>
        /// <param name="profiledDbCommand">The <see cref="IDbCommand"/> that finished.</param>
        /// <param name="executeType">The execution type of the <paramref name="profiledDbCommand"/>.</param>
        /// <param name="reader">(Optional) the reader piece of the <paramref name="profiledDbCommand"/>, if it exists.</param>
        void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
        {
            if (_inProgress == null)
            {
                return;
            }

            var          id = Tuple.Create((object)profiledDbCommand, executeType);
            CustomTiming current;

            lock (_inProgress)
            {
                if (!_inProgress.TryRemove(id, out current))
                {
                    return;
                }
            }

            if (reader != null)
            {
                lock (_dbLocker)
                {
                    _inProgressReaders = _inProgressReaders ?? new Dictionary <IDataReader, CustomTiming>();
                }
                lock (_inProgressReaders)
                {
                    _inProgressReaders[reader] = current;
                }
                current.FirstFetchCompleted();
            }
            else
            {
                current.Stop();
            }
        }
Esempio n. 3
0
        public void TestTryDictionaryRemove()
        {
            var map = new Dictionary <string, string>()
            {
                { "k1", "v1" },
                { "k2", "v2" },
                { "k3", "v3" },
            };

            Assert.True(map.TryRemove("k2", out string val) && val == "v2");
            Assert.False(map.TryRemove("booyah", out string _));
        }
        public void Dispose()
        {
            using (var token = @lock.ForReadingUpgradeable())
            {
                if (cache == null)
                {
                    return;
                }
                token.Upgrade();
                cache.Dispose();
                cache = null;

                if (parentScope != null)
                {
                    SetCurrentScope(parentScope);
                }
                else
                {
                    CallContext.FreeNamedDataSlot(keyInCallContext);
                }
            }
#if DOTNET35
            lock (cacheLocker)
            {
                appDomainLocalInstanceCache.Remove(contextId);
            }
#else
            CallContextLifetimeScope @this;
            appDomainLocalInstanceCache.TryRemove(contextId, out @this);
#endif
        }
Esempio n. 5
0
        internal static void removeFor(IntPtr db)
        {
            info i;

#if NO_CONCURRENTDICTIONARY
            lock (_hooks_by_db)
            {
                if (_hooks_by_db.TryGetValue(db, out i))
                {
                    _hooks_by_db.Remove(db);
                }
                else
                {
                    i = null;
                }
            }
            if (i != null)
            {
                i.free();
            }
#else
            if (_hooks_by_db.TryRemove(db, out i))
            {
                i.free();
            }
#endif
        }
Esempio n. 6
0
 /// <summary>
 /// Safe remove
 /// </summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="dict"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static bool SafeRemove <TKey, TValue>(this Dictionary <TKey, TValue> dict, TKey key) where TKey : class
 {
     if (key == null)
     {
         return(false);
     }
     return(dict.TryRemove(key));
 }
        public void RemoveClient(string clientName)
        {
            string key = ValidateAndParseRegistryKey(clientName);

            if (!_clients.TryRemove(key, out ICallistoClient _))
            {
                throw new CallistoException($"The application was unable to remove the client '{clientName}' from the registry.");
            }
        }
Esempio n. 8
0
        public void TryRemoveTest3()
        {
            var target = new Dictionary <string, Dictionary <object, string> >();
            var val1   = new object();
            var key1   = "Key1";
            var key2   = "Key2";

            target.TryAdd(key1, val1);
            target.TryAdd(key2, val1);
            Assert.AreEqual(2, target.Count);
            var innerDict = target[key1];

            Assert.AreEqual(1, innerDict.Count);
            target.TryRemove(key1, val1);
            Assert.AreEqual(1, target.Count);
            target.TryRemove(key2, val1);
            Assert.AreEqual(0, target.Count);
        }
Esempio n. 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public bool Remove(TKey key, out IEnumerable <TValue> values)
        {
            Exception      any;
            IList <TValue> list;
            bool           result = Dictionary.TryRemove(key, out list, out any);

            values = list;
            return(result);
        }
Esempio n. 10
0
        public void TryRemove_NotFound()
        {
            var dict = new Dictionary <string, string> {
                { "foo", "bar" }
            };

            string value;

            Assert.IsFalse(dict.TryRemove("foo2", out value));
        }
Esempio n. 11
0
        public bool Remove(TKey key)
        {
            if (_dic.TryRemove(key, out var oldValue))
            {
                _collection.Remove(oldValue);
                return(true);
            }

            return(false);
        }
Esempio n. 12
0
        public string RegisterClient()
        {
            var context   = OperationContext.Current;
            var sessionId = context.SessionId;

            try
            {
                var callback = context.GetCallbackChannel <IExternalControlServerCallback>();

                clients.TryRemove(context.SessionId);
                clients.Add(sessionId, callback);

                return(sessionId);
            }
            catch (Exception)
            {
                clients.TryRemove(sessionId);
                return(string.Empty);
            }
        }
Esempio n. 13
0
        public void TryRemove_Found()
        {
            var dict = new Dictionary <string, string> {
                { "foo", "bar" }
            };

            string value;

            Assert.IsTrue(dict.TryRemove("foo", out value));
            Assert.AreEqual("bar", value);
        }
Esempio n. 14
0
        public void Add(K key, V value)
        {
            var mruNode = MostRecentlyUsed.Add(value);

            mruNode.OnRemoval = () =>
            {
                MruNode <V> node;
                Dictionary.TryRemove(key, out node);
            };
            Dictionary.TryAdd(key, mruNode);
        }
Esempio n. 15
0
        public bool Remove(K key)
        {
            MruNode <V> handle;
            var         success = Dictionary.TryRemove(key, out handle);

            if (success)
            {
                handle.Delete();
            }
            return(success);
        }
Esempio n. 16
0
        public void TryRemove()
        {
            var dictionary = new Dictionary <string, string>
            {
                { "three", "bar" }
            };

            dictionary.TryRemove("four").Should().BeFalse();
            dictionary.TryRemove("three").Should().BeTrue();
            dictionary.Count.Should().Be(0);

            Action action = () => dictionary.TryRemove(key: null);

            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("key");

            dictionary = null;
            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("source");
        }
Esempio n. 17
0
        /// <summary>
        /// Implement IReliableDictionary methods
        /// </summary>
        #region IReliableDictionary
        public async Task AddAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
        {
            await LockManager.AcquireLock(BeginTransaction(tx).TransactionId, key, LockMode.Update, timeout, cancellationToken);

            if (!Dictionary.TryAdd(key, value))
            {
                throw new ArgumentException("A value with the same key already exists.", nameof(value));
            }

            AddAbortAction(tx, () => { Dictionary.TryRemove(key, out _); return(true); });
            AddCommitAction(tx, () => { InternalDictionaryChanged?.Invoke(this, new DictionaryChangedEvent <TKey, TValue>(tx, ChangeType.Added, key, added: value)); return(true); });
        }
Esempio n. 18
0
 public WebSocketUrlBuilder SetCompression(bool compressed)
 {
     if (compressed)
     {
         arguments.AddOrUpdate("compress", "zlib-stream");
     }
     else
     {
         arguments.TryRemove("compress");
     }
     return(this);
 }
Esempio n. 19
0
        public void TryRemoveOverloadOne()
        {
            var dictionary = new Dictionary <string, string>
            {
                { "one", "foo" },
                { "two", "foo" },
                { "three", "bar" }
            };

            dictionary.TryRemove(keys: new string[] { "zing" }).Should().BeFalse();
            dictionary.TryRemove(new string[] { "one", "three" }).Should().BeTrue();
            dictionary.Count.Should().Be(1);

            Action action = () => dictionary.TryRemove(keys: null);

            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("keys");

            dictionary = null;
            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("source");
        }
 public void Remove(TKey key)
 {
     try
     {
         SlimLock.EnterWriteLock();
         TValue value;
         Dictionary.TryRemove(key, out value);
     }
     finally
     {
         SlimLock.ExitWriteLock();
     }
 }
Esempio n. 21
0
        void FinishLoadingTask(int loadingTaskId, IReadOnlyList <AssetBundleRecord> necessaryAssetBundleRecords)
        {
            foreach (AssetBundleRecord assetBundleRecord in necessaryAssetBundleRecords)
            {
                string assetBundleName = assetBundleRecord.AssetBundleName;

                HashSet <int> taskIds = loadingTaskIdSets.GetValue(assetBundleName);
                if (taskIds == null)
                {
                    errorReceiver.OnError(AssetBundleErrorCode.MissingTaskIdSetInTermination, $"cannot get task id set: {assetBundleName}");
                    return;
                }

                if (!taskIds.TryRemove(loadingTaskId))
                {
                    errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveTaskId, $"cannot remove task id: {assetBundleName}");
                    return;
                }

                if (taskIds.IsEmpty())
                {
                    if (!loadingTaskIdSets.TryRemove(assetBundleName))
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadingTaskIdSet, $"cannot remove loading task id set: {assetBundleName}");
                        return;
                    }
                    HashSetPool <int> .Pool.Put(ref taskIds);

                    AssetBundle unusingAssetBundle = loadedAssetBundles.GetValue(assetBundleName);
                    if (unusingAssetBundle == null)
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.MissingLoadedAssetBundle, $"cannot get loaded asset bundle: {assetBundleName}");
                        return;
                    }

                    unusingAssetBundle.Unload(false);

                    if (!loadedAssetBundles.TryRemove(assetBundleName))
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadedAssetBundle, $"cannot remove loaded asset bundle: {assetBundleName}");
                        return;
                    }
                }
            }

            if (!loadingTasks.TryRemove(loadingTaskId))
            {
                errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadingTask, "cannot remove loading task");
                return;
            }
        }
Esempio n. 22
0
        internal static string GetUpdateOnlyWhereExpression <T>(this IOrmLiteDialectProvider dialectProvider,
                                                                Dictionary <string, object> updateFields, out object[] args)
        {
            var modelDef = typeof(T).GetModelDefinition();
            var pkField  = modelDef.PrimaryKey;

            if (pkField == null)
            {
                throw new NotSupportedException($"'{typeof(T).Name}' does not have a primary key");
            }

            var idValue = updateFields.TryRemove(pkField.Name, out var nameValue)
                ? nameValue
                : pkField.Alias != null && updateFields.TryRemove(pkField.Alias, out var aliasValue)
                    ? aliasValue
                    : null;

            if (idValue == null)
            {
                var caseInsensitiveMap =
                    new Dictionary <string, object>(updateFields, StringComparer.InvariantCultureIgnoreCase);
                idValue = caseInsensitiveMap.TryRemove(pkField.Name, out nameValue)
                    ? nameValue
                    : pkField.Alias != null && caseInsensitiveMap.TryRemove(pkField.Alias, out aliasValue)
                        ? aliasValue
                        : new NotSupportedException(
                    $"UpdateOnly<{typeof(T).Name}> requires a '{pkField.Name}' Primary Key Value");
            }

            if (modelDef.RowVersion == null || !updateFields.TryGetValue(ModelDefinition.RowVersionName, out var rowVersion))
            {
                args = new[] { idValue };
                return("(" + dialectProvider.GetQuotedColumnName(pkField.FieldName) + " = {0})");
            }

            args = new[] { idValue, rowVersion };
            return("(" + dialectProvider.GetQuotedColumnName(pkField.FieldName) + " = {0} AND " + dialectProvider.GetRowVersionColumn(modelDef.RowVersion) + " = {1})");
        }
Esempio n. 23
0
        public void TryRemoveTest1()
        {
            var target = new Dictionary <string, Dictionary <object, string> >();
            var val    = new object();
            var key    = "Key1";

            target.TryAdd(key, val);
            Assert.AreEqual(1, target.Count);
            var innerDict = target[key];

            Assert.AreEqual(1, innerDict.Count);
            target.TryRemove(key, val);
            Assert.AreEqual(0, target.Count);
        }
Esempio n. 24
0
        public void TryRemoveOverloadTwo()
        {
            var dictionary = new Dictionary <string, string>
            {
                { "three", "bar" }
            };

            string removed;

            dictionary.TryRemove("four", out removed).Should().BeFalse();
            removed.Should().BeNull();
            dictionary.TryRemove("three", out removed).Should().BeTrue();
            removed.Should().Be("bar");
            dictionary.Count.Should().Be(0);

            Action action = () => dictionary.TryRemove(key: null, value: out removed);

            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("key");

            dictionary = null;
            action.ShouldThrow <ArgumentNullException>()
            .And.ParamName.Should().Be("source");
        }
        private static void RemoveStream(IntPtr handle)
        {
#if NET20 || NET35
            lock (DicStreams)
            {
                if (DicStreams.ContainsKey(handle))
                {
                    DicStreams.Remove(handle);
                }
            }
#else
            StreamData result;
            DicStreams.TryRemove(handle, out result);
#endif
        }
Esempio n. 26
0
        public void Pop()
        {
            if (_contextStack.Count != 0)
            {
                IBaseView curView = _contextStack.Peek();
                _contextStack.Pop();
                _UIDict.TryRemove(curView.ViewType.panelId);
                curView.OnExit();
            }

            if (_contextStack.Count != 0)
            {
                IBaseView curView = _contextStack.Peek();
                curView.OnResume();
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Called when 'reader' finishes its iterations and is closed.
        /// </summary>
        /// <param name="reader">The <see cref="IDataReader"/> that finished.</param>
        void IDbProfiler.ReaderFinish(IDataReader reader)
        {
            if (_inProgressReaders == null)
            {
                return;
            }

            CustomTiming timing;

            lock (_inProgressReaders)
            {
                _inProgressReaders.TryRemove(reader, out timing);
            }

            // This reader may have been disposed/closed by reader code, not by our using()
            timing?.Stop();
        }
Esempio n. 28
0
        public void Remove(LuaState luaState)
        {
#if WINDOWS_PHONE || NET_3_5
            lock (translators)
            {
                if (!translators.ContainsKey(luaState))
                {
                    return;
                }

                translators.Remove(luaState);
            }
#else
            ObjectTranslator translator;
            translators.TryRemove(luaState, out translator);
#endif
        }
Esempio n. 29
0
        public async Task <bool> TryAddAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
        {
            var acquireResult = await LockManager.AcquireLock(BeginTransaction(tx).TransactionId, key, LockMode.Update, timeout, cancellationToken);

            var result = Dictionary.TryAdd(key, value);

            if (result)
            {
                AddAbortAction(tx, () => { Dictionary.TryRemove(key, out _); return(true); });
                AddCommitAction(tx, () => { InternalDictionaryChanged?.Invoke(this, new DictionaryChangedEvent <TKey, TValue>(tx, ChangeType.Added, key, added: value)); return(true); });
            }
            else if (acquireResult == AcquireResult.Acquired)
            {
                LockManager.ReleaseLock(tx.TransactionId, key);
            }

            return(result);
        }
Esempio n. 30
0
        public async Task <ConditionalValue <TValue> > TryRemoveAsync(ITransaction tx, TKey key, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
        {
            var acquireResult = await LockManager.AcquireLock(BeginTransaction(tx).TransactionId, key, LockMode.Update, timeout, cancellationToken);

            TValue value;
            bool   hasValue = Dictionary.TryRemove(key, out value);

            if (hasValue)
            {
                AddAbortAction(tx, () => { Dictionary.TryAdd(key, value); return(true); });
                AddCommitAction(tx, () => { OnDictionaryChanged(new DictionaryChange(tx, ChangeType.Removed, key, removed: value)); return(true); });
            }
            else if (acquireResult == AcquireResult.Acquired)
            {
                LockManager.ReleaseLock(tx.TransactionId, key);
            }

            return(new ConditionalValue <TValue>(hasValue, value));
        }
Esempio n. 31
0
        public void TryRemove_Found()
        {
            var dict = new Dictionary<string, string> { { "foo", "bar" } };

            string value;
            Assert.IsTrue (dict.TryRemove ("foo", out value));
            Assert.AreEqual ("bar", value);
        }
Esempio n. 32
0
        public void TryRemove_NotFound()
        {
            var dict = new Dictionary<string, string> { { "foo", "bar" } };

            string value;
            Assert.IsFalse (dict.TryRemove ("foo2", out value));
        }
Esempio n. 33
0
        public void TryRemove()
        {
            var dictionary = new Dictionary<string, string>
            {
                { "three", "bar" }
            };

            dictionary.TryRemove("four").Should().BeFalse();
            dictionary.TryRemove("three").Should().BeTrue();
            dictionary.Count.Should().Be(0);

            Action action = () => dictionary.TryRemove(key: null);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");

            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");
        }
Esempio n. 34
0
        public void TryRemoveOverloadOne()
        {
            var dictionary = new Dictionary<string, string>
            {
                { "one", "foo" },
                { "two", "foo" },
                { "three", "bar" }
            };

            dictionary.TryRemove(keys: new string[] { "zing" }).Should().BeFalse();
            dictionary.TryRemove(new string[] { "one", "three" }).Should().BeTrue();
            dictionary.Count.Should().Be(1);

            Action action = () => dictionary.TryRemove(keys: null);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("keys");

            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");
        }
Esempio n. 35
0
        public void TryRemoveOverloadTwo()
        {
            var dictionary = new Dictionary<string, string>
            {
                { "three", "bar" }
            };

            string removed;
            dictionary.TryRemove("four", out removed).Should().BeFalse();
            removed.Should().BeNull();
            dictionary.TryRemove("three", out removed).Should().BeTrue();
            removed.Should().Be("bar");
            dictionary.Count.Should().Be(0);

            Action action = () => dictionary.TryRemove(key: null, value: out removed);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");

            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");
        }