System.Collections.Generic.Dictionary.Remove(string)

Here are the examples of the csharp api System.Collections.Generic.Dictionary.Remove(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4162 Examples 7

19 Source : BankIdSimulatedApiClient.cs
with MIT License
from ActiveLogin

public async Task<CollectResponse> CollectAsync(CollectRequest request)
        {
            await SimulateResponseDelay().ConfigureAwait(false);

            if (!_auths.ContainsKey(request.OrderRef))
            {
                throw new BankIdApiException(ErrorCode.NotFound, "OrderRef not found.");
            }

            var auth = _auths[request.OrderRef];
            var status = GetStatus(auth.CollectCalls);
            var hintCode = GetHintCode(auth.CollectCalls);

            if (status != CollectStatus.Complete)
            {
                auth.CollectCalls += 1;
                return new CollectResponse(auth.OrderRef, status.ToString(), hintCode.ToString());
            }

            if (_auths.ContainsKey(request.OrderRef))
            {
                _auths.Remove(request.OrderRef);
            }

            var completionData = GetCompletionData(auth.EndUserIp, status, auth.PersonalIdenreplacedyNumber);

            return new CollectResponse(auth.OrderRef, status.ToString(), hintCode.ToString(), completionData);
        }

19 Source : BankIdSimulatedApiClient.cs
with MIT License
from ActiveLogin

public async Task<CancelResponse> CancelAsync(CancelRequest request)
        {
            await SimulateResponseDelay().ConfigureAwait(false);

            if (_auths.ContainsKey(request.OrderRef))
            {
                _auths.Remove(request.OrderRef);
            }

            return new CancelResponse();
        }

19 Source : GrandIdSimulatedApiClient.cs
with MIT License
from ActiveLogin

public async Task<BankIdGetSessionResponse> BankIdGetSessionAsync(BankIdGetSessionRequest request)
        {
            await SimulateResponseDelay().ConfigureAwait(false);

            if (!_bankidFederatedLogins.ContainsKey(request.SessionId))
            {
                throw new GrandIdApiException(ErrorCode.Unknown, "SessionId not found.");
            }

            var auth = _bankidFederatedLogins[request.SessionId];
            _bankidFederatedLogins.Remove(request.SessionId);

            var personalIdenreplacedyNumber = auth.PersonalIdenreplacedyNumber;
            var userAttributes = GetUserAttributes(personalIdenreplacedyNumber);
            var response = new BankIdGetSessionResponse(auth.BankIdFederatedLoginResponse.SessionId,
                userAttributes.PersonalIdenreplacedyNumber,
                userAttributes
            );

            return response;
        }

19 Source : GrandIdSimulatedApiClient.cs
with MIT License
from ActiveLogin

public async Task<LogoutResponse> LogoutAsync(LogoutRequest request)
        {
            await SimulateResponseDelay().ConfigureAwait(false);

            var sessionId = request.SessionId;

            if (_bankidFederatedLogins.ContainsKey(sessionId))
            {
                _bankidFederatedLogins.Remove(sessionId);
            }

            return new LogoutResponse(true);
        }

19 Source : AdColony.cs
with Apache License 2.0
from AdColony

public void _OnClosed(string paramJson)
        {
            Hashtable values = (AdColonyJson.Decode(paramJson) as Hashtable);
            if (values == null)
            {
                Debug.LogError("Unable to parse parameters in _OnClosed, " + (paramJson ?? "null"));
                return;
            }

            IntersreplacedialAd ad = GetAdFromHashtable(values);
            if (ad == null)
            {
                Debug.LogError("Unable to create ad within _OnClosed, " + (paramJson ?? "null"));
                return;
            }

            if (Ads.OnClosed != null)
            {
                if (ad != null)
                {
                    Ads.OnClosed(ad);
                }
                else
                {
                    Debug.LogError(Constants.AdsMessageErrorUnableToRebuildAd);
                }
            }

            _ads.Remove(ad.Id);
        }

19 Source : AdColony.cs
with Apache License 2.0
from AdColony

public void _OnExpiring(string paramJson)
        {
            Hashtable values = (AdColonyJson.Decode(paramJson) as Hashtable);
            if (values == null)
            {
                Debug.LogError("Unable to parse parameters in _OnExpiring, " + (paramJson ?? "null"));
                return;
            }

            IntersreplacedialAd ad = GetAdFromHashtable(values);
            if (ad == null)
            {
                Debug.LogError("Unable to create ad within _OnExpiring, " + (paramJson ?? "null"));
                return;
            }

            if (Ads.OnExpiring != null)
            {
                if (ad != null)
                {
                    Ads.OnExpiring(ad);
                }
                else
                {
                    Debug.LogError(Constants.AdsMessageErrorUnableToRebuildAd);
                }
            }

            _ads.Remove(ad.Id);
        }

19 Source : ContentMap.cs
with MIT License
from Adoxio

private bool RemoveFromLookup(EnreplacedyReference reference)
		{
			IDictionary<EnreplacedyReference, EnreplacedyNode> lookup;

			if (TryGetValue(reference.LogicalName, out lookup))
			{
				var result = lookup.Remove(reference);

				if (result && !lookup.Any())
				{
					// cleanup the enreplacedy set

					Remove(reference.LogicalName);
				}

				return result;
			}

			return false;
		}

19 Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio

public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationCreateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions ||
				(result.PermissionsExist && result.PermissionGranted))
			{
				var enreplacedy = new Enreplacedy("annotation");

				if (note.Owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", note.Owner);
				}

				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("objectid", note.Regarding);
				enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);

				if (note.FileAttachment != null)
				{
					var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
					var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
					if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
							acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;

					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				// Create annotaion but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				if (result != null) result.Annotation = note;

				note.AnnotationId = enreplacedy.Id = id;
				note.Enreplacedy = enreplacedy;

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var container = GetBlobContainer(storageAccount, _containerName);

					var azureFile = (AzureAnnotationFile)note.FileAttachment;

					azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = azureFile.BlockBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					serviceContextForWrite.UpdateObject(enreplacedy);
					serviceContextForWrite.SaveChanges();

					// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
					// actual blob replication is handled here.
					var key = note.AnnotationId.ToString("N");
					if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
					{
						var replication =
							HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
						if (replication != null && replication.ContainsKey(key))
						{
							CopyBlob(note, replication[key]);
							replication.Remove(key);
						}
					}
				} 
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
			}

			return result;
		}

19 Source : FetchXmlResultsFilter.cs
with MIT License
from Adoxio

public string Aggregate(string fetchXml, string primaryKeyFieldName, params string[] fields)
		{
			var fetchXmlParsed = XDoreplacedent.Parse(fetchXml);
			var inputResults = fetchXmlParsed.Descendants("result").ToList();

			if (inputResults.Count == 0)
			{
				return fetchXml;
			}

			var aggregatedResults = new Dictionary<string, XElement>();
			var parsedResultSet = new FetchXmlResultSet(fetchXml);

			bool isFirstPage = this.lastResultOnPage == null;
			bool isLastPage = !parsedResultSet.MoreRecords;

			//// Check if last result of last page and first result of this page are the same article.
			//// If not, we need to add the aggregated result from last page during this round.
			//// If so, the past CAL/product ids should still be stored and we'll just add to 
			if (!isFirstPage)
			{
				var firstId = inputResults.First().Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				var previousPageLastId = this.lastResultOnPage.Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				if (firstId != previousPageLastId)
				{
					aggregatedResults[previousPageLastId] = this.lastResultOnPage;
				}
			}
			var lastId = inputResults.Descendants(primaryKeyFieldName).FirstOrDefault().Value;

			var collectionOfFields = fields.Select(fieldName => new RelatedField(fieldName)).ToList();

			//// Iterating through fetchXml retrieving multiple related fields
			foreach (var resultNode in inputResults)
			{
				var primaryKeyFieldNode = resultNode.Descendants(primaryKeyFieldName).FirstOrDefault();
				if (primaryKeyFieldNode == null) { return fetchXml; }

				////Retrieving fields
				collectionOfFields.ForEach(field => this.GetRelatedFields(resultNode, field, primaryKeyFieldNode.Value));
				////Removing duplicate nodes
				aggregatedResults[primaryKeyFieldNode.Value] = resultNode;
			}

			var node = inputResults.FirstOrDefault();
			if (node == null)
			{
				return fetchXml;
			}
			var parentNode = node.Parent;
			if (parentNode == null)
			{
				return fetchXml;
			}

			fetchXmlParsed.Descendants("result").Remove();

			//// Inserting retrieved above related fields and deduplicated results.
			collectionOfFields.ForEach(field => this.InsertRelatedFields(aggregatedResults, field));

			//// Remove and store the last aggregated result, as this might be the same article as the first result on the 
			//// next page.
			this.lastResultOnPage = aggregatedResults[lastId];
			if (!isLastPage)
			{
				aggregatedResults.Remove(lastId);
			}

			fetchXmlParsed.Element(parentNode.Name).Add(aggregatedResults.Values);
			return fetchXmlParsed.ToString();
		}

19 Source : NamedLock.cs
with MIT License
from Adoxio

public void Unlock(string name)
		{
			lock (_locks)
			{
				ReferenceCount obj;

				_locks.TryGetValue(name, out obj);

				if (obj != null)
				{
					Monitor.Exit(obj);

					if (0 == obj.Release())
					{
						_locks.Remove(name);
					}
				}
			}
		}

19 Source : NotifyIcon.cs
with GNU General Public License v3.0
from aduskin

public static void Unregister(string token, NotifyIcon notifyIcon)
        {
            if (string.IsNullOrEmpty(token) || notifyIcon == null) return;

            if (NotifyIconDic.ContainsKey(token))
            {
                if (ReferenceEquals(NotifyIconDic[token], notifyIcon))
                {
                    NotifyIconDic.Remove(token);
                }
            }
        }

19 Source : NotifyIcon.cs
with GNU General Public License v3.0
from aduskin

public static void Unregister(NotifyIcon notifyIcon)
        {
            if (notifyIcon == null) return;
            var first = NotifyIconDic.FirstOrDefault(item => ReferenceEquals(notifyIcon, item.Value));
            if (!string.IsNullOrEmpty(first.Key))
            {
                NotifyIconDic.Remove(first.Key);
            }
        }

19 Source : NotifyIcon.cs
with GNU General Public License v3.0
from aduskin

public static void Unregister(string token)
        {
            if (string.IsNullOrEmpty(token)) return;

            if (NotifyIconDic.ContainsKey(token))
            {
                NotifyIconDic.Remove(token);
            }
        }

19 Source : BlockSyncAttachBlockAbnormalPeerTestAElfModule.cs
with MIT License
from AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            _peers.Add("AbnormalPeerPubkey", new PeerInfo());
            
            context.Services.AddSingleton(o =>
            {
                var networkServiceMock = new Mock<INetworkService>();
                
                networkServiceMock.Setup(p => p.RemovePeerByPubkeyAsync(It.IsAny<string>(),It.IsAny<int>()))
                    .Returns<string, int>(
                        (peerPubkey, removalSeconds) =>
                        {
                            _peers.Remove(peerPubkey);
                            return Task.FromResult(true);
                        });

                networkServiceMock.Setup(p => p.GetPeerByPubkey(It.IsAny<string>()))
                    .Returns<string>((peerPubKey) => _peers.ContainsKey(peerPubKey) ? _peers[peerPubKey] : null);

                return networkServiceMock.Object;
            });

            context.Services.AddTransient<IBlockValidationService>(o =>
            {
                var blockValidationServiceMock = new Mock<IBlockValidationService>();

                blockValidationServiceMock.Setup(p => p.ValidateBlockBeforeAttachAsync(It.IsAny<Block>()))
                    .Returns<Block>(block =>
                    {
                        if (block.Header.PreviousBlockHash.Equals(HashHelper.ComputeFrom("BadBlock")))
                        {
                            return Task.FromResult(false);
                        }

                        return Task.FromResult(true);
                    });
                blockValidationServiceMock.Setup(s =>
                    s.ValidateBlockBeforeExecuteAsync(It.IsAny<IBlock>())).Returns(Task.FromResult(true));
                blockValidationServiceMock.Setup(s =>
                    s.ValidateBlockAfterExecuteAsync(It.IsAny<IBlock>())).Returns(Task.FromResult(true));

                return blockValidationServiceMock.Object;
            });
        }

19 Source : BlockSyncAbnormalPeerTestAElfModule.cs
with MIT License
from AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            _peers.Add("AbnormalPeerPubkey", new PeerInfo());
            _peers.Add("NotLinkedBlockPubkey", new PeerInfo());
            _peers.Add("WrongLIBPubkey", new PeerInfo
            {
                Pubkey = "WrongLIBPubkey",
                SyncState = SyncState.Finished,
                LastKnownLibHeight = 110
            });

            for (int i = 0; i < 15; i++)
            {
                var pubkey = "GoodPeerPubkey" + i;
                _peers.Add(pubkey, new PeerInfo
                {
                    Pubkey = pubkey,
                    SyncState = SyncState.Finished,
                    LastKnownLibHeight = 150 + i
                });
            }

            var osTestHelper = context.Services.GetServiceLazy<OSTestHelper>();
            
            context.Services.AddSingleton(o =>
            {
                var networkServiceMock = new Mock<INetworkService>();
                networkServiceMock
                    .Setup(p => p.GetBlockByHashAsync(It.IsAny<Hash>(), It.IsAny<string>()))
                    .Returns<Hash, string>((hash, peerPubkey) =>
                    {
                        BlockWithTransactions result = null;
                        if (peerPubkey == "AbnormalPeerPubkey")
                        {
                            result = osTestHelper.Value.GenerateBlockWithTransactions(HashHelper.ComputeFrom("BadBlock"),
                                1000);
                        }

                        return Task.FromResult(new Response<BlockWithTransactions>(result));
                    });

                networkServiceMock
                    .Setup(p => p.GetBlocksAsync(It.IsAny<Hash>(), It.IsAny<int>(),
                        It.IsAny<string>()))
                    .Returns<Hash, int, string>((previousBlockHash, count, peerPubKey) =>
                    {
                        var result = new List<BlockWithTransactions>();
                        var hash = previousBlockHash;
                        
                        if (peerPubKey == "NotLinkedBlockPubkey")
                        {
                            for (var i = 0; i < count-1; i++)
                            {
                                var block = osTestHelper.Value.GenerateBlockWithTransactions(hash, 100 + i);
                                hash = block.Header.PreviousBlockHash;

                                result.Add(block);
                            }

                            var notLinkedBlock =
                                osTestHelper.Value.GenerateBlockWithTransactions(HashHelper.ComputeFrom("NotLinkedBlock"),
                                    100);
                            result.Add(notLinkedBlock);
                        }

                        if (hash == HashHelper.ComputeFrom("GoodBlockHash"))
                        {
                            for (var i = 0; i < count; i++)
                            {
                                var block = osTestHelper.Value.GenerateBlockWithTransactions(hash, 100 + i);
                                hash = block.Header.PreviousBlockHash;

                                result.Add(block);
                            }
                        }

                        return Task.FromResult(new Response<List<BlockWithTransactions>>(result));
                    });

                networkServiceMock.Setup(p => p.RemovePeerByPubkeyAsync(It.IsAny<string>(), It.IsAny<int>()))
                    .Returns<string, int>(
                        (peerPubkey,removalSeconds) =>
                        {
                            _peers.Remove(peerPubkey);
                            return Task.FromResult(true);
                        });

                networkServiceMock.Setup(p => p.GetPeerByPubkey(It.IsAny<string>()))
                    .Returns<string>((peerPubKey) => _peers.ContainsKey(peerPubKey) ? _peers[peerPubKey] : null);

                networkServiceMock.Setup(p => p.GetPeers(It.IsAny<bool>())).Returns(_peers.Values.ToList());

                return networkServiceMock.Object;
            });
        }

19 Source : PixmapManager.cs
with GNU General Public License v2.0
from afrantzis

public void DereferencePixmap(string id)
	{
		--references[id];
		if (references[id] <= 0) {
			pixmaps[id].Dispose();
			pixmaps.Remove(id);
			references.Remove(id);
		}
	}

19 Source : PlatformLoader.cs
with GNU General Public License v3.0
from affederaffe

internal async Task<CustomPlatform?> LoadPlatformFromFileAsync(string fullPath)
        {
            if (!File.Exists(fullPath))
            {
                _siraLog.Error($"File could not be found:\n{fullPath}");
                return null;
            }

            if (_pathTaskPairs.TryGetValue(fullPath, out Task<CustomPlatform?> task)) return await task;
            task = LoadPlatformFromFileAsyncImpl(fullPath);
            _pathTaskPairs.Add(fullPath, task);
            CustomPlatform? platform = await task;
            _pathTaskPairs.Remove(fullPath);
            return platform;
        }

19 Source : CSRedisClientAsync.cs
with Mozilla Public License 2.0
from agebullhu

async public Task<T[]> CacheShellAsync<T>(string key, string[] fields, int timeoutSeconds, Func<string[], Task<(string, T)[]>> getDataAsync, Func<(T, long), string> serialize, Func<string, (T, long)> deserialize) {
			fields = fields?.Distinct().ToArray();
			if (fields == null || fields.Length == 0) return new T[0];
			if (timeoutSeconds <= 0) return (await getDataAsync(fields)).Select(a => a.Item2).ToArray();

			var ret = new T[fields.Length];
			var cacheValue = await HashMGetAsync(key, fields);
			var fieldsMGet = new Dictionary<string, int>();

			for (var a = 0; a < cacheValue.Length; a++) {
				if (cacheValue[a] != null) {
					try {
						var value = deserialize(cacheValue[a]);
						if (DateTime.Now.Subtract(dt1970.AddSeconds(value.Item2)).TotalSeconds <= timeoutSeconds) {
							ret[a] = value.Item1;
							continue;
						}
					} catch {
						await HashDeleteAsync(key, fields[a]);
						throw;
					}
				}
				fieldsMGet.Add(fields[a], a);
			}

			if (fieldsMGet.Any()) {
				var getDataIntput = fieldsMGet.Keys.ToArray();
				var data = await getDataAsync(getDataIntput);
				var mset = new object[fieldsMGet.Count * 2];
				var msetIndex = 0;
				foreach (var d in data) {
					if (fieldsMGet.ContainsKey(d.Item1) == false) throw new Exception($"使用 CacheShell 请确认 getData 返回值 (string, T)[] 中的 Item1 值: {d.Item1} 存在于 输入参数: {string.Join(",", getDataIntput)}");
					ret[fieldsMGet[d.Item1]] = d.Item2;
					mset[msetIndex++] = d.Item1;
					mset[msetIndex++] = serialize((d.Item2, (long)DateTime.Now.Subtract(dt1970).TotalSeconds));
					fieldsMGet.Remove(d.Item1);
				}
				foreach (var fieldNull in fieldsMGet.Keys) {
					ret[fieldsMGet[fieldNull]] = default(T);
					mset[msetIndex++] = fieldNull;
					mset[msetIndex++] = serialize((default(T), (long)DateTime.Now.Subtract(dt1970).TotalSeconds));
				}
				if (mset.Any()) await HashSetAsync(key, mset);
			}
			return ret.ToArray();
		}

19 Source : AttributeDictionary.cs
with Mozilla Public License 2.0
from agebullhu

public bool Set<T>(string name, T value)
        {
            if (Dictionary.TryGetValue(name, out object value1))
            {
                if (Equals(value, default(T)))
                {
                    Dictionary.Remove(name);
                    return true;
                }
                if (Equals(value1, value))
                {
                    return false;
                }
                Dictionary[name] = value;
                return true;
            }
            if (Equals(value, default( T )))
            {
                return false;
            }
            Dictionary.Add(name, value);
            return true;
        }

19 Source : ZeroAppConfig.cs
with Mozilla Public License 2.0
from agebullhu

internal void Remove(StationConfig station)
        {
            lock (_configs)
            {
                _configs.Remove(station.Name);
                _configMap.Remove(station.Name);
                _configMap.Remove(station.ShortName);
                if (station.StationAlias == null)
                    return;
                foreach (var ali in station.StationAlias)
                {
                    _configMap.Remove(ali);
                }
            }
        }

19 Source : FunctionDictionaryBase.cs
with Mozilla Public License 2.0
from agebullhu

public void AnnexDelegate<TAction>(TAction action, string name = null) where TAction : clreplaced
        {
            if (string.IsNullOrEmpty(name))
            {
                var type = typeof(TAction);
                if (_dependencyDictionary.ContainsKey(type))
                {
                    if (Equals(action, null))
                    {
                        _dependencyDictionary.Remove(type);
                    }
                    else
                    {
                        _dependencyDictionary[type] = action;
                    }
                }
                else if (!Equals(action, null))
                {
                    _dependencyDictionary.Add(type, action);
                }
            }
            else if (_nameDictionary.ContainsKey(name))
            {
                if (Equals(action, null))
                {
                    _nameDictionary.Remove(name);
                }
                else
                {
                    _nameDictionary[name] = action;
                }
            }
            else if (!Equals(action, null))
            {
                _nameDictionary.Add(name, action);
            }
        }

19 Source : OriginalRecordStatus.cs
with Mozilla Public License 2.0
from agebullhu

protected override void OnEndPropertyChangingInner(PropertyChangingEventArgsEx args)
        {
            if (Equals(this.OriginalValues[args.PropertyName], args.NewValue))
            {
                this.OriginalValues.Remove(args.PropertyName);
                this.SetUnModify(args.PropertyName);
            }
            else
            {
                this.SetModify(args.PropertyName);
            }
        }

19 Source : Sections.cs
with MIT License
from agens-no

public void RemoveEntry(string guid)
        {
            if (m_Entries.ContainsKey(guid))
                m_Entries.Remove(guid);
        }

19 Source : Utils.cs
with MIT License
from agens-no

public void Remove(string guid)
        {
            m_Dict.Remove(guid);
        }

19 Source : RouteChahe.cs
with Mozilla Public License 2.0
from agebullhu

internal static bool LoadCache(Uri uri, string bearer, out CacheOption setting, out string key,
            ref string resultMessage)
        {
            if (!CacheMap.TryGetValue(uri.LocalPath, out setting))
            {
                key = null;
                return false;
            }

            if (setting.Feature.HasFlag(CacheFeature.Bear) && bearer.Substring(0, setting.Bear.Length) != setting.Bear)
            {
                setting = null;
                key = null;
                return false;
            }

            CacheData cacheData;

            lock (setting)
            {
                key = setting.OnlyName ? uri.LocalPath : uri.PathAndQuery;
                if (!Cache.TryGetValue(key, out cacheData))
                    return false;
                if (cacheData.UpdateTime <= DateTime.Now)
                {
                    Cache.Remove(key);
                    return false;
                }
            }

            resultMessage = cacheData.Content;
            return true;
        }

19 Source : AssetCatalog.cs
with MIT License
from agens-no

public DeviceRequirement AddCustom(string key, string value)
        {
            if (values.ContainsKey(key))
                values.Remove(key);
            values.Add(key, value);
            return this;
        }

19 Source : PBXProjectData.cs
with MIT License
from agens-no

public void BuildFilesRemove(string targetGuid, string fileGuid)
        {
            var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid);
            if (buildFile != null)
            {
                m_FileGuidToBuildFileMap[targetGuid].Remove(buildFile.fileRef);
                buildFiles.RemoveEntry(buildFile.guid);
            }
        }

19 Source : PBXProjectData.cs
with MIT License
from agens-no

public void FileRefsRemove(string guid)
        {
            PBXFileReferenceData fileRef = fileRefs[guid];
            fileRefs.RemoveEntry(guid);
            m_ProjectPathToFileRefMap.Remove(m_FileRefGuidToProjectPathMap[guid]);
            m_FileRefGuidToProjectPathMap.Remove(guid);
            foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees())
                m_RealPathToFileRefMap[tree].Remove(fileRef.path);
            m_GuidToParentGroupMap.Remove(guid);
        }

19 Source : PBXProjectData.cs
with MIT License
from agens-no

public void FileRefsRemove(string guid)
        {
            PBXFileReferenceData fileRef = fileRefs[guid];
            fileRefs.RemoveEntry(guid);
            m_ProjectPathToFileRefMap.Remove(m_FileRefGuidToProjectPathMap[guid]);
            m_FileRefGuidToProjectPathMap.Remove(guid);
            foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees())
                m_RealPathToFileRefMap[tree].Remove(fileRef.path);
            m_GuidToParentGroupMap.Remove(guid);
        }

19 Source : PBXProjectData.cs
with MIT License
from agens-no

public void GroupsRemove(string guid)
        {
            m_ProjectPathToGroupMap.Remove(m_GroupGuidToProjectPathMap[guid]);
            m_GroupGuidToProjectPathMap.Remove(guid);
            m_GuidToParentGroupMap.Remove(guid);
            groups.RemoveEntry(guid);
        }

19 Source : PBXProjectData.cs
with MIT License
from agens-no

static bool RemoveObjectsFromSection<T>(KnownSectionBase<T> section,
                                                Dictionary<string, bool> allGuids,
                                                Func<T, bool> checker) where T : PBXObjectData, new()
        {
            List<string> guidsToRemove = null;
            foreach (var kv in section.GetEntries())
            {
                if (checker(kv.Value))
                {
                    if (guidsToRemove == null)
                        guidsToRemove = new List<string>();
                    guidsToRemove.Add(kv.Key);
                }
            }
            if (guidsToRemove != null)
            {
                foreach (var guid in guidsToRemove)
                {
                    section.RemoveEntry(guid);
                    allGuids.Remove(guid);
                }
                return true;
            }
            return false;
        }

19 Source : BaseViewModelWithAnnotationValidation.cs
with MIT License
from ahmed-abdelrazek

public bool ValidateProperty(string propertyName)
        {
            if (_Properties.TryGetValue(propertyName, out PropertyInfo propInfo))
            {
                var errors = new List<object>();
                foreach (var attribute in propInfo.GetCustomAttributes<ValidationAttribute>())
                {
                    if (!attribute.IsValid(propInfo.GetValue(this)))
                    {
                        errors.Add(attribute.FormatErrorMessage(propertyName));
                    }
                }

                if (errors.Any())
                {
                    _ValidationErrorsByProperty[propertyName] = errors;
                    ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
                    return false;
                }

                if (_ValidationErrorsByProperty.Remove(propertyName))
                {
                    ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
                }
            }
            return true;
        }

19 Source : Directory.cs
with GNU General Public License v3.0
from ahmed605

public void DeleteObject(FSObject obj)
        {
            _fsObjectsByName.Remove(obj.Name.ToLower());
            _fsObjects.Remove(obj);
        }

19 Source : ValidationPropertyChangedBase.cs
with MIT License
from ahmed-abdelrazek

protected void RemoveError(string propertyName, string error)
        {
            if (_errors.TryGetValue(propertyName, out List<string> propertyErrors))
            {
                if (propertyErrors.Contains(error))
                {
                    propertyErrors.Remove(error);
                    if (!propertyErrors.Any())
                    {
                        _errors.Remove(propertyName);
                    }
                    OnErrorsChanged(propertyName);
                }
            }
        }

19 Source : BlackBoard.cs
with MIT License
from aillieo

public bool Remove(string key)
        {
            return this.dict.Remove(key);
        }

19 Source : WebSocketClient.cs
with MIT License
from Aiko-IT-Systems

public bool RemoveDefaultHeader(string name)
            => this._defaultHeaders.Remove(name);

19 Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems

public void UnregisterCommands(params Command[] cmds)
        {
            if (cmds.Any(x => x.Parent != null))
                throw new InvalidOperationException("Cannot unregister nested commands.");

            var keys = this.RegisteredCommands.Where(x => cmds.Contains(x.Value)).Select(x => x.Key).ToList();
            foreach (var key in keys)
                this.TopLevelCommands.Remove(key);
        }

19 Source : EsiaSecureDataFormat.cs
with GNU General Public License v3.0
from AISGorod

public AuthenticationProperties Unprotect(string protectedText, string purpose)
        {
            if (!_dict.ContainsKey(protectedText))
                return null;
            var data = _dict[protectedText];
            _dict.Remove(protectedText);
            return data;
        }

19 Source : SubscriptionListener.cs
with Apache License 2.0
from ajuna-network

public void RegisterCallBackHandler<T>(string subscriptionId, Action<string, T> callback)
        {
            if (!_headerCallbacks.ContainsKey(subscriptionId))
            {
                Logger.Debug($"Register {callback} for subscription '{subscriptionId}'");
                _headerCallbacks.Add(subscriptionId, callback);
            }

            if (_pendingHeaders.ContainsKey(subscriptionId))
            {
                foreach (var h in _pendingHeaders[subscriptionId])
                    // we don't wait on the tasks to finish
                    callback(subscriptionId, (T) h);
                _pendingHeaders.Remove(subscriptionId);
            }
        }

19 Source : SubscriptionListener.cs
with Apache License 2.0
from ajuna-network

public void UnregisterHeaderHandler(string subscriptionId)
        {
            if (_headerCallbacks.ContainsKey(subscriptionId))
            {
                Logger.Debug($"Unregister subscription '{subscriptionId}'");
                _headerCallbacks.Remove(subscriptionId);
            }
        }

19 Source : JPropertyKeyedCollection.cs
with MIT License
from akaskela

private void RemoveKey(string key)
        {
            if (_dictionary != null)
            {
                _dictionary.Remove(key);
            }
        }

19 Source : WindowMemory.cs
with MIT License
from AkiniKites

public static void SaveAndForget(string name)
        {
            if (!Windows.TryGetValue(name, out TrackingWindow window))
                throw new WindowMemoryException($"Window name not found: {name}");

            var r = new Rectangle((int)window.Window.Left, (int)window.Window.Top,
                (int)window.Window.Width, (int)window.Window.Height);
            IoC.Settings.Windows[window.Name] = r;
            SettingsManager.Save();

            Windows.Remove(name);
        }

19 Source : NodeEditorPreferences.cs
with MIT License
from aksyr

public static void ResetPrefs() {
            if (EditorPrefs.HasKey(lastKey)) EditorPrefs.DeleteKey(lastKey);
            if (settings.ContainsKey(lastKey)) settings.Remove(lastKey);
            typeColors = new Dictionary<Type, Color>();
            VerifyLoaded();
            NodeEditorWindow.RepaintAll();
        }

19 Source : Node.cs
with MIT License
from aksyr

public void RemoveDynamicPort(NodePort port) {
            if (port == null) throw new ArgumentNullException("port");
            else if (port.IsStatic) throw new ArgumentException("cannot remove static port");
            port.ClearConnections();
            ports.Remove(port.fieldName);
        }

19 Source : NodeDataCache.cs
with MIT License
from aksyr

public static void UpdatePorts(Node node, Dictionary<string, NodePort> ports) {
            if (!Initialized) BuildCache();

            Dictionary<string, NodePort> staticPorts = new Dictionary<string, NodePort>();
            System.Type nodeType = node.GetType();

            List<NodePort> typePortCache;
            if (portDataCache.TryGetValue(nodeType, out typePortCache)) {
                for (int i = 0; i < typePortCache.Count; i++) {
                    staticPorts.Add(typePortCache[i].fieldName, portDataCache[nodeType][i]);
                }
            }

            // Cleanup port dict - Remove nonexisting static ports - update static port types
            // Loop through current node ports
            foreach (NodePort port in ports.Values.ToList()) {
                // If port still exists, check it it has been changed
                NodePort staticPort;
                if (staticPorts.TryGetValue(port.fieldName, out staticPort)) {
                    // If port exists but with wrong settings, remove it. Re-add it later.
                    if (port.connectionType != staticPort.connectionType || port.IsDynamic || port.direction != staticPort.direction || port.typeConstraint != staticPort.typeConstraint) ports.Remove(port.fieldName);
                    else port.ValueType = staticPort.ValueType;
                }
                // If port doesn't exist anymore, remove it
                else if (port.IsStatic) ports.Remove(port.fieldName);
            }
            // Add missing ports
            foreach (NodePort staticPort in staticPorts.Values) {
                if (!ports.ContainsKey(staticPort.fieldName)) {
                    ports.Add(staticPort.fieldName, new NodePort(staticPort, node));
                }
            }
        }

19 Source : VirtualInput.cs
with MIT License
from alanplotko

public void UnRegisterVirtualButton(string name)
        {
            // if we have a button with this name then remove it from our dictionary of registered buttons
            if (m_VirtualButtons.ContainsKey(name))
            {
                m_VirtualButtons.Remove(name);
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from AlaricGilbert

private void TaskCallback(int taskid)
        {
            this.Invoke(() =>
            {
                var replacedle = TaskList[taskid].BangumiInfo.replacedle;
                TaskList.RemoveAt(taskid);
                TaskPair.Remove(replacedle);
                TaskListBox.Items.Remove(replacedle);
                SaveCurrentTasks();
            });
        }

19 Source : MainWindow.xaml.cs
with MIT License
from AlaricGilbert

private void Remove(object sender, RoutedEventArgs e)
        {
            if (TaskListBox.SelectedItem == null)
                return;
            if (TaskListBox.Items.Count == 0)
                return;
            var replacedle = TaskListBox.SelectedItem as string;
            var tsk = TaskPair[replacedle];
            tsk.Dispose();
            TaskList.Remove(tsk);
            TaskPair.Remove(tsk.BangumiInfo.replacedle);
            TaskListBox.Items.Remove(tsk.BangumiInfo.replacedle);
            SaveCurrentTasks();
        }

19 Source : VirtualInput.cs
with MIT License
from alanplotko

public void UnRegisterVirtualAxis(string name)
        {
            // if we have an axis with that name then remove it from our dictionary of registered axes
            if (m_VirtualAxes.ContainsKey(name))
            {
                m_VirtualAxes.Remove(name);
            }
        }

19 Source : BaseNode.Init.cs
with MIT License
from alelievr

void LoadFieldAttributes()
		{
			//get input variables
			System.Reflection.FieldInfo[] fInfos = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

			List< string > actualFields = new List< string >();

			anchorFieldInfoMap.Clear();
				
			foreach (var field in fInfos)
			{
				// reading field informations.

				actualFields.Add(field.Name);
				anchorFieldInfoMap[field.Name] = field;

				if (!anchorFieldDictionary.ContainsKey(field.Name))
					anchorFieldDictionary[field.Name] = CreateAnchorField();
				
				AnchorField	anchorField = anchorFieldDictionary[field.Name];
				
				//detect multi-anchor by checking for PWArray<T> type
				if (field.FieldType.IsGenericType)
				{
					if (field.FieldType.GetGenericTypeDefinition() == typeof(PWArray<>))
						anchorField.multiple = true;
				}
				
				System.Object[] attrs = field.GetCustomAttributes(true);
				foreach (var attr in attrs)
				{
					InputAttribute			inputAttr = attr as InputAttribute;
					OutputAttribute			outputAttr = attr as OutputAttribute;
					ColorAttribute			colorAttr = attr as ColorAttribute;
					OffsetAttribute			offsetAttr = attr as OffsetAttribute;
					VisibilityAttribute		visibilityAttr = attr as VisibilityAttribute;
					NotRequiredAttribute	notRequiredAttr = attr as NotRequiredAttribute;

					if (inputAttr != null)
					{
						anchorField.anchorType = AnchorType.Input;
						if (inputAttr.name != null)
							anchorField.name = inputAttr.name;
					}
					if (outputAttr != null)
					{
						anchorField.anchorType = AnchorType.Output;
						if (outputAttr.name != null)
							anchorField.name = outputAttr.name;
					}
					if (colorAttr != null)
						anchorField.color = new SerializableColor(colorAttr.color);
					if (offsetAttr != null)
					{
						anchorField.offset = offsetAttr.offset;
						anchorField.padding = offsetAttr.padding;
					}
					if (notRequiredAttr != null)
						anchorField.required = false;
					if (visibilityAttr != null)
						anchorField.defaultVisibility = visibilityAttr.visibility;
				}
				if (anchorField.anchorType == AnchorType.None) //field does not have a PW attribute
					anchorFieldDictionary.Remove(field.Name);
				else
				{
					//create anchor in this anchorField if there is not existing one
					if (anchorField.anchors.Count == 0)
						anchorField.CreateNewAnchor();

					anchorField.colorSchemeName = ColorTheme.GetAnchorColorSchemeName(field.FieldType);
					anchorField.fieldName = field.Name;
					anchorField.fieldType = (SerializableType)field.FieldType;
					anchorField.fieldValue = field.GetValue(this);
					anchorField.nodeRef = this;
				}
			}

			//remove inhexistants field dictionary entries (for renamed variables):
			var toRemoveKeys = new List< string >();
			foreach (var kp in anchorFieldDictionary)
				if (!actualFields.Contains(kp.Key))
					toRemoveKeys.Add(kp.Key);
			
			foreach (var toRemoveKey in toRemoveKeys)
				anchorFieldDictionary.Remove(toRemoveKey);
		}

See More Examples