public void BadAddKV() { var dict = new ThreadSafeDictionary <int, int>(); dict.Add(1, 1); dict.Add(new KeyValuePair <int, int>(1, 2)); }
/// <summary> /// 根据配置路径和段落名称获取配置对象 /// </summary> /// <typeparam name="TConfig"></typeparam> /// <param name="configurationPath"></param> /// <param name="type">区分平台和插件</param> /// <param name="sectionName"></param> /// <returns></returns> private TConfig Get <TConfig>(string configurationPath, ConfigurationType type, string sectionName) where TConfig : class { string key = configurationPath.ToLower(); TConfig tconfig; ConfigurationItem ci; if (configurationItemCache.ContainsKey(key)) { ci = configurationItemCache[key]; } else { ci = new ConfigurationItem() { ConfigurationFilePath = configurationPath, Type = type.ToDescription() }; configurationItemCache.Add(key, ci); } if (sectionName != "") { tconfig = ci.Configuration.GetSection(sectionName) as TConfig; if (tconfig == null) { throw new ConfigurationErrorsException("The configuration file {0} Lack of configuration section {1}".FormatString(ci.ConfigurationFilePath, sectionName)); } } else { tconfig = ci.Configuration as TConfig; } return(tconfig); }
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); }
public void BadAdd() { var dict = new ThreadSafeDictionary <int, int>(); dict.Add(1, 1); dict.Add(1, 2); }
internal object GetInstance(Type type, Scoped scope) { Func <Scoped, object?>?func = _getInstanceCache.GetOrDefault(type); if (func == null) { func = DependencyGraph.Resolve(type)?.Factory ?? (s => null !); _getInstanceCache.Add(type, func); } return(func(scope) !); }
public void CopyTo_should_copy() { var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>()); dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue")); dict.Add(new KeyValuePair <string, string>("AnyKey1", "AnyValue1")); dict.Add(new KeyValuePair <string, string>("AnyKey2", "AnyValue2")); var items = new KeyValuePair <string, string> [3]; dict.CopyTo(items, 0); Assert.That(items.Length, Is.EqualTo(3)); }
public void Dictionary_should_enumerate_correctly() { var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>()); dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue")); dict.Add(new KeyValuePair <string, string>("AnyKey1", "AnyValue1")); dict.Add(new KeyValuePair <string, string>("AnyKey2", "AnyValue2")); foreach (KeyValuePair <string, string> keyValue in dict) { Assert.That(keyValue.Key.StartsWith("AnyKey"), Is.True); Assert.That(keyValue.Value.StartsWith("AnyValue"), Is.True); } }
private static void RegisterType(Type type, string lifeCycle) { var exportAttributes = type.GetCustomAttributes(typeof(ExportAttribute), false); if (exportAttributes == null || exportAttributes.Length == 0) { return; } ExportAttribute exportAttribute = exportAttributes[0] as ExportAttribute; //string[] filterArray = new string[] { "IEnumerable" }; //Type[] objectInterfaces = interfaces.Where(pre => !filterArray.Contains(pre.Name) && !(pre.IsGenericType)).ToArray(); //反射类型中包含的所有非系统的方法,判断方法中是否带有特性,如果参数中不包含特性,则不处理 var allMethods = exportAttribute.InterfaceType.GetMethods(System.Reflection.BindingFlags.Public); if (methodMappingContainer.ContainsKey(type)) { IList <ValidatorMethodMapping> methodMappings = methodMappingContainer[type]; //添加当前方法对应的映射元数据信息 foreach (var method in allMethods) { ValidatorMethodMapping methodMapping = new ValidatorMethodMapping(method); if (methodMapping.MethodParameters != null && methodMapping.MethodParameters.Length > 0) { methodMappings.Add(methodMapping); } } } else { IList <ValidatorMethodMapping> methodMappings = new List <ValidatorMethodMapping>(); foreach (var method in allMethods) { ValidatorMethodMapping methodMapping = new ValidatorMethodMapping(method); if (methodMapping.MethodParameters != null && methodMapping.MethodParameters.Length > 0) { methodMappings.Add(methodMapping); } } methodMappingContainer.Add(type, methodMappings); } }
/// <summary> /// Registers the attached set of derived types by the indicated base type /// </summary> /// <param name="baseType">base type that will be encountered by the binder where an alternate value should be used</param> /// <param name="derivedTypes">an enumerable set of types to be considered for binding</param> public static bool RegisterDerivedTypes(Type baseType, IEnumerable <Type> derivedTypes) { try { // register the types based on the base type _typeCache.Add(baseType, derivedTypes); } catch (ArgumentException) { return(false); } foreach (var item in derivedTypes) { // this step is needed to make sure the closure behaves properly var currentItem = item; var encryptedName = EncryptStringToBase64(currentItem.FullName); _hashToTypeDictionary.AddOrUpdate(encryptedName, name => currentItem, (name, itemValue) => currentItem); _typeToHashDictionary.AddOrUpdate(currentItem, type => encryptedName, (type, name) => encryptedName); } // register the base type with the derived type modelbinder for binding purposes ModelBinders.Binders.Add(baseType, new DerivedTypeModelBinder()); return(true); }
private bool GetGlyphIndex(char c, out GlyphInfo gli) { GlyphInfo info; if (CharMap.TryGetValue(c, out info)) { if (info.ListID > 0 && info.Width > 0) { gli = info; return(true); } else { gli = GlyphInfo.Empty; return(false); } } else if (OnDemand) { lock (SyncObject) { uint glyphindex = Font.GetCharIndex(c); info = CompileCharacter(Font, glyphindex, c); CharMap.Add(c, info); gli = info; } return(true); } gli = GlyphInfo.Empty; return(false); }
public static void get_dataset(string sopInstanceUID, Action <DicomDS, string, string, string> datasetFile, int numRetries, int retryInterval) { AsyncHelper.Execute(() => { if (Module.Service != null) { try { if (_Callbacks.ContainsKey(sopInstanceUID)) { _Callbacks[sopInstanceUID] = datasetFile; } else { _Callbacks.Add(sopInstanceUID, datasetFile); } Module.Service.SendMessage(GetReferencedFile, sopInstanceUID, numRetries, retryInterval); } catch (Exception e) { Logger.Global.SystemException(string.Empty, e); } } }); }
static bool MonitorUpdateDurationInternal(IEnumerator tickable, string threadInfo) { TaskInfo info; bool result; if (taskInfos.TryGetValue(tickable.ToString(), out info) == false) { info = new TaskInfo(tickable); info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds); info.AddThreadInfo(threadInfo); taskInfos.Add(tickable.ToString(), info); } else { info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds); info.AddThreadInfo(threadInfo); } _stopwatch.Reset(); _stopwatch.Start(); result = tickable.MoveNext(); _stopwatch.Stop(); return(result); }
public void LoadScripts() { _Delegates.Clear(); Logger.Global.SystemMessage(LogType.Information, "Loading scripts", string.Empty); if (!string.IsNullOrEmpty(_RuleDirectory)) { foreach (string file in Directory.GetFiles(_RuleDirectory, "*.rule", SearchOption.AllDirectories)) { try { ServerRule rule = RuleEditorPresenter.LoadRule <ServerRule>(file); if (rule.Script.Length > 0) { if (!_Delegates.ContainsKey(rule.ServerEvent)) { _Delegates.Add(rule.ServerEvent, new ThreadSafeDictionary <ServerRule, ScriptObject>()); } _Delegates[rule.ServerEvent].Add(rule, null); } } catch (Exception e) { Logger.Global.SystemException(string.Empty, e); } } } }
public static bool MonitorUpdateDuration(IEnumerator tickable, string runnerName) { var key = tickable.ToString().FastConcat(runnerName); #if ENABLE_PIX_EVENTS PixWrapper.PIXBeginEventEx(0x11000000, key); #endif _stopwatch.Start(); var result = tickable.MoveNext(); _stopwatch.Stop(); #if ENABLE_PIX_EVENTS PixWrapper.PIXEndEventEx(); #endif lock (LOCK_OBJECT) { TaskInfo info; if (taskInfos.TryGetValue(key, out info) == false) { info = new TaskInfo(tickable); info.AddThreadInfo(runnerName.FastConcat(": ")); taskInfos.Add(key, ref info); } else { info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds); taskInfos.Update(key, ref info); } } _stopwatch.Reset(); return(result); }
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")); }
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 MultiplayerSessionReservation ReservePlayerContext( NitroxConnection connection, PlayerSettings playerSettings, AuthenticationContext authenticationContext, string correlationId) { // TODO: ServerPassword in NitroxClient if (!string.IsNullOrEmpty(serverConfig.ServerPassword) && (!authenticationContext.ServerPassword.HasValue || authenticationContext.ServerPassword.Value != serverConfig.ServerPassword)) { MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.AUTHENTICATION_FAILED; return(new MultiplayerSessionReservation(correlationId, rejectedState)); } if (reservedPlayerNames.Count >= serverConfig.MaxConnections) { MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.SERVER_PLAYER_CAPACITY_REACHED; return(new MultiplayerSessionReservation(correlationId, rejectedState)); } string playerName = authenticationContext.Username; Player player; allPlayersByName.TryGetValue(playerName, out player); if ((player?.IsPermaDeath == true) && serverConfig.IsHardcore) { MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.HARDCORE_PLAYER_DEAD; return(new MultiplayerSessionReservation(correlationId, rejectedState)); } if (reservedPlayerNames.Contains(playerName)) { MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.UNIQUE_PLAYER_NAME_CONSTRAINT_VIOLATED; return(new MultiplayerSessionReservation(correlationId, rejectedState)); } ConnectionAssets assetPackage; assetsByConnection.TryGetValue(connection, out assetPackage); if (assetPackage == null) { assetPackage = new ConnectionAssets(); assetsByConnection.Add(connection, assetPackage); reservedPlayerNames.Add(playerName); } bool hasSeenPlayerBefore = player != null; ushort playerId = hasSeenPlayerBefore ? player.Id : ++currentPlayerId; PlayerContext playerContext = new PlayerContext(playerName, playerId, !hasSeenPlayerBefore, playerSettings); string reservationKey = Guid.NewGuid().ToString(); reservations.Add(reservationKey, playerContext); assetPackage.ReservationKey = reservationKey; return(new MultiplayerSessionReservation(correlationId, playerId, reservationKey)); }
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")); }
public void ContainsKey_should_return_true_if_it_exists() { var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>()); dict.Add("1", "Any Item 1"); Assert.That(dict.ContainsKey("1"), Is.True); Assert.That(dict.ContainsKey("2"), Is.False); }
public void RegisterPlayer(NebulaConnection nebulaConnection, ushort playerId) { Requestors.Add(playerId, nebulaConnection); if (!IsStatisticsNeeded) { ClearCapturedData(); IsStatisticsNeeded = true; } }
public void Clear_should_get_rid_of_all_items() { var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>()); dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue")); dict.Clear(); Assert.That(dict.Count, Is.EqualTo(0)); }
internal object GetInstance(Type type, Scoped scope) { Func <Scoped, object> func = _getInstanceCache.Get(type); if (func == null) { func = _dependencyGraph.GetResolvedFactory(type) !; _getInstanceCache.Add(type, func); } return(func(scope)); }
public static void test(User user, string newName) { //string newName = "[FR-Mayor] " + user.Name; string previousName = user.Name; typeof(User).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.Name.ContainsCaseInsensitive("Name")).First().SetValue(user, newName); ThreadSafeDictionary <string, User> users = (typeof(UserManager).GetFields(BindingFlags.NonPublic | BindingFlags.Static).Where(x => x.Name.ContainsCaseInsensitive("UsersByDisplayName")).First().GetValue(UserManager.Obj) as ThreadSafeDictionary <string, User>); users.Remove(previousName); users.Add(newName, user); }
public void Remove_should_get_rid_of_key_value_pair() { var dict = new ThreadSafeDictionary <string, string>(new Dictionary <string, string>()); dict.Add(new KeyValuePair <string, string>("AnyKey", "AnyValue")); Assert.That(dict.Count, Is.EqualTo(1)); dict.Remove(new KeyValuePair <string, string>("AnyKey", "AnyValue")); Assert.That(dict.Count, Is.EqualTo(0)); }
internal void LateInject(object instance, Scoped scope) { Type type = instance.GetType(); Action <Scoped, object>?action = _injectionCache.GetOrDefault(type); if (action == null) { action = GenerateLateInjector(type); _injectionCache.Add(type, action); } action(scope, instance); }
public void Serialisation() { //Note that the behaviour of the BinaryFormatter will fix some of the strings //used in many of these tests, as not being valid Unicode. This is desirable behaviour //in real code, but would give false negatives to this test. var dict = new ThreadSafeDictionary <string, string>(); for (int i = 0; i != 10000; ++i) { dict.Add(i.ToString(), (i * 2).ToString()); } dict.Add(null, "check null keys work"); dict.Add("check null values work", null); using (MemoryStream ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, dict); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); Assert.IsTrue(EqualDicts(dict, (ThreadSafeDictionary <string, string>) new BinaryFormatter().Deserialize(ms))); } }
public static bool MonitorUpdateDuration <T #if ENABLE_PLATFORM_PROFILER , PP #endif >(T sveltoTask, string runnerName #if ENABLE_PLATFORM_PROFILER , PP profiler #endif ) where T : ISveltoTask #if ENABLE_PLATFORM_PROFILER where PP : IPlatformProfiler #endif { var key = sveltoTask.ToString().FastConcat(runnerName); bool result; #if ENABLE_PLATFORM_PROFILER using (profiler.Sample(sveltoTask.ToString())) #endif { _stopwatch.Start(); #if ENABLE_PIX_EVENTS PixWrapper.PIXBeginEventEx(0x11000000, key); #endif result = sveltoTask.MoveNext(); #if ENABLE_PIX_EVENTS PixWrapper.PIXEndEventEx(); #endif _stopwatch.Stop(); } lock (LOCK_OBJECT) { if (taskInfos.TryGetValue(key, out var info) == false) { info = new TaskInfo(sveltoTask.ToString()); info.AddThreadInfo(runnerName.FastConcat(": ")); taskInfos.Add(key, ref info); } else { info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds); taskInfos.Update(key, ref info); } } _stopwatch.Reset(); return(result); }
/// <summary> /// error handler for validation messages /// </summary> /// <param name="ex"></param> /// <param name="businessException"></param> /// <returns></returns> public bool ErrorHandler(Exception ex = null, ExceptionsML businessException = null) { var noError = true; if (businessException != null) { if (businessException.Type == typeof(LoginRequiredException).ToString()) { throw LoginRequiredException.Create((LoginRequiredReason)Enum.Parse(typeof(LoginRequiredReason), businessException.Data)); } else { if (ValidationMessages.ContainsKey("Exception")) { ValidationMessages["Exception"] = businessException; } else { ValidationMessages.Add("Exception", businessException); } } noError = false; } if (ex != null) { if (ValidationMessages.ContainsKey("Exception")) { ValidationMessages["Exception"] = ExceptionsML.GetExceptionML(ex); } else { ValidationMessages.Add("Exception", ExceptionsML.GetExceptionML(ex)); } noError = false; } return(noError); }
/// <summary> /// Registers the attached set of derived types by the indicated base type /// </summary> /// <param name="baseType">base type that will be encountered by the binder where an alternate value should be used</param> /// <param name="derivedTypes">an enumerable set of types to be considered for binding</param> public static bool RegisterDerivedTypes(Type baseType, IEnumerable <Type> derivedTypes) { try { typeCache.Add(baseType, derivedTypes); return(true); } catch (ArgumentException) { return(false); } }
public Player PlayerConnected(NebulaConnection conn) { //Generate new data for the player ushort playerId = GetNextAvailablePlayerId(); Float3 randomColor = new Float3(Random.value, Random.value, Random.value); PlayerData playerData = new PlayerData(playerId, -1, randomColor); Player newPlayer = new Player(conn, playerData); pendingPlayers.Add(conn, newPlayer); return(newPlayer); }
/// <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; }