public void TestDuplicateRemove()
        {
            var dict = new ConcurrentDictionary<int, string>();

            dict.Add(3, string.Empty);

            dict.Remove(3);
            dict.Remove(3);
        }
        public void TestLockFreeDictionary()
        {
            IDictionary<int, Guid> dict = new ConcurrentDictionary<int, Guid>();

            KeyValuePair<int, Guid> test = new KeyValuePair<int, Guid>(-64, Guid.NewGuid());

            dict.Add(42, Guid.NewGuid());
            dict.Add(22, Guid.NewGuid());
            dict.Add(test);
            dict.Add(55, Guid.NewGuid());

            Assert.IsTrue(dict.ContainsKey(-64));
            Assert.IsTrue(dict.Contains(test));
            Assert.IsFalse(dict.Contains(new KeyValuePair<int, Guid>(-64, new Guid())));

            dict[-64] = Guid.NewGuid();
            Assert.IsFalse(dict.Contains(test));

            Guid newID = Guid.NewGuid();
            dict[12] = newID;
            Guid id = dict[12];

            Assert.IsTrue(newID == id);

            Assert.IsTrue(dict.Count == 5);

            dict.Remove(-64);
            Assert.IsTrue(dict.Count == 4);

        }
        public void Remove_ThrowsNotImplementedException()
        {
            // Arrange
            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();

            // Act/Assert
            Assert.Throws<NotImplementedException>(() => dictionary.Remove(0));
        }
Example #4
0
 public void Dispose() => All.Remove(this, out var _);
Example #5
0
        public async Task <ConcurrentDictionary <long, Dictionary <string, string> > > ReadWIs()
        {
            Console.WriteLine($"Reading WIs for org {_org}");
            var allIDs         = new ConcurrentDictionary <long, Dictionary <string, string> >();
            var childParentIDs = new Dictionary <long, long?>();
            var queryContent   = new StringContent($"{{\"query\": \"{_query}\"}}", Encoding.UTF8, "application/json");
            var wiqlResult     = await _httpClient.PostAsync($"/{_org}/_apis/wit/wiql?api-version=5.1", queryContent);

            wiqlResult.EnsureSuccessStatusCode();
            var wiqlResultContent = await wiqlResult.Content.ReadAsStringAsync();

            var wiqlResponse = JsonConvert.DeserializeObject <QueryResponse>(wiqlResultContent);

            if (wiqlResponse.QueryResultType == "workItem")
            {
                // flat list
                Console.WriteLine($"Found {wiqlResponse.WorkItems.Count()} WorkItems in org {_org}");
                foreach (var wi in wiqlResponse.WorkItems)
                {
                    allIDs[wi.Id]         = null;
                    childParentIDs[wi.Id] = null;
                }
            }
            else if (wiqlResponse.QueryResultType == "workItemLink")
            {
                // tree list
                Console.WriteLine($"Found {wiqlResponse.WorkItemRelations.Count()} WorkItemRelations in org {_org}");
                var parentChilds = wiqlResponse.WorkItemRelations.Where(w => w.Rel == _linkType);
                foreach (var parentChild in parentChilds)
                {
                    allIDs[parentChild.Target.Id]         = null;
                    childParentIDs[parentChild.Target.Id] = parentChild.Source.Id;
                    if (!allIDs.ContainsKey(parentChild.Source.Id))
                    {
                        allIDs[parentChild.Source.Id] = null;
                    }
                }

                var childsOnly = wiqlResponse.WorkItemRelations.Where(w => w.Rel == null);
                foreach (var child in childsOnly)
                {
                    if (!allIDs.ContainsKey(child.Target.Id))
                    {
                        allIDs[child.Target.Id] = null;
                    }
                    if (!childParentIDs.ContainsKey(child.Target.Id))
                    {
                        childParentIDs[child.Target.Id] = null;
                    }
                }
            }
            else
            {
                // unknown
            }

            var sliceSize = 200;
            var keyArray  = allIDs.Keys.ToArray();
            var tasks     = new List <Task <Dictionary <long, Dictionary <string, object> > > >();

            for (int start = 0; start < keyArray.Length; start += sliceSize)
            {
                int end = start + sliceSize;
                if (end > (keyArray.Length))
                {
                    end = keyArray.Length;
                }
                Range r            = start..end;
                var   requestedIDs = keyArray[r];
                tasks.Add(GetWIDetails(requestedIDs));
            }

            var allWIs = await Task.WhenAll(tasks);

            foreach (var wiDicts in allWIs)
            {
                foreach (var wiDict in wiDicts)
                {
                    var fieldDict = new Dictionary <string, string>();
                    foreach (var kvp in wiDict.Value)
                    {
                        if (kvp.Key == "System.AssignedTo")
                        {
                            var valueObject = kvp.Value as JObject;
                            fieldDict["System.AssignedTo.DisplayName"] = valueObject.GetValue("displayName").ToString();
                            fieldDict["System.AssignedTo.UniqueName"]  = valueObject.GetValue("uniqueName").ToString();
                        }
                        else
                        {
                            fieldDict[kvp.Key] = kvp.Value.ToString();
                        }
                    }
                    allIDs[wiDict.Key] = fieldDict;
                }
            }

            foreach (var parentId in childParentIDs.Values)
            {
                if (parentId.HasValue && allIDs.ContainsKey(parentId.Value))
                {
                    foreach (var childId in childParentIDs.Where(e => e.Value == parentId))
                    {
                        allIDs[childId.Key]["ParentTitle"] = allIDs[parentId.Value]["System.Title"];
                        allIDs[childId.Key]["ParentURL"]   = $"https://dev.azure.com/{_org}/_workitems/edit/{parentId.Value}";
                    }
                    Dictionary <string, string> outDict;
                    allIDs.Remove(parentId.Value, out outDict);
                }
            }
            return(allIDs);
        }
Example #6
0
 public bool RemovePlayer(int objectId)
 {
     return(Players.Remove(objectId, out _));
 }
Example #7
0
        /// <inheritdoc cref="IConsumer.ClearFailedAttempts" />
        // TODO: Call it!
        public void ClearFailedAttempts(IRawInboundEnvelope envelope)
        {
            Check.NotNull(envelope, nameof(envelope));

            _failedAttemptsDictionary.Remove(envelope.Offset, out _);
        }
 public void TestRemove()
 {
     _dictionary.TryAdd(1, 1);
     _dictionary.Remove(1);
     _dictionary.Count.ShouldBe(0);
 }
Example #9
0
        private async Task <TelegramChat> GetChat(long chatId, TdApi.Chat chat = null)
        {
            if (_chats.TryGetValue(chatId, out var tg))
            {
                return(tg);
            }

            AutoResetEvent wait;

            if (_loadingChats.TryGetValue(chatId, out wait))
            {
                wait.WaitOne();
                return(_chats[chatId]);
            }

            wait = new AutoResetEvent(false);
            if (!_loadingChats.TryAdd(chatId, wait))
            {
                wait.WaitOne();
                return(_chats[chatId]);
            }

            int tryIndex = 0;

            while (tryIndex < 5)
            {
                tryIndex++;
                const string tdLibThrottlePrefix = "Too Many Requests: retry after";

                try
                {
                    if (chat == null)
                    {
                        chat = await _client.ExecuteAsync(new TdApi.GetChat {
                            ChatId = chatId
                        });
                    }

                    switch (chat.Type)
                    {
                    case TdApi.ChatType.ChatTypeBasicGroup existingBasicGroup:
                    {
                        if (chat.LastReadInboxMessageId != 0)
                        {
                            _logger.LogInformation("Known last read for chat {chat} {messageId}", chat.Id, chat.LastReadInboxMessageId);
                        }

                        tg = new TelegramChat()
                        {
                            ChatId       = chatId,
                            BasicGroupId = existingBasicGroup.BasicGroupId,
                            Title        = chat.Title
                        };
                        var basicGroupFullInfo = await _client.ExecuteAsync(new TdApi.GetBasicGroupFullInfo()
                            {
                                BasicGroupId = existingBasicGroup.BasicGroupId
                            });

                        var users   = basicGroupFullInfo.Members.Where(m => m.UserId != _serviceUserId).Select(m => m.UserId);
                        var members = new List <TelegramContact>();
                        foreach (var user in users)
                        {
                            var contact = await GetTelegramContact(user);

                            members.Add(contact);
                        }

                        tg.Members = members.ToArray();

                        break;
                    }

                    case TdApi.ChatType.ChatTypePrivate privateChat:
                    {
                        tg = new TelegramChat()
                        {
                            ChatId = chatId,
                            Title  = chat.Title
                        };
                        var members = new List <TelegramContact>();
                        var contact = await GetTelegramContact(privateChat.UserId);

                        members.Add(contact);

                        tg.Members = members.ToArray();

                        break;
                    }

                    case TdApi.ChatType.ChatTypeSupergroup superGroup:
                    {
                        tg = new TelegramChat()
                        {
                            ChatId = chatId,
                            Title  = chat.Title
                        };
                        var group = await _client.ExecuteAsync(new TdApi.GetSupergroup()
                            {
                                SupergroupId = superGroup.SupergroupId
                            });

                        try
                        {
                            var groupMember = await _client.ExecuteAsync(new TdApi.GetSupergroupMembers()
                                {
                                    SupergroupId = superGroup.SupergroupId, Limit = 1000, Offset = 0
                                });

                            var users   = groupMember.Members.Where(m => m.UserId != _serviceUserId).Select(m => m.UserId);
                            var members = new List <TelegramContact>();
                            foreach (var user in users)
                            {
                                var contact = await GetTelegramContact(user);

                                members.Add(contact);
                            }

                            tg.Members = members.ToArray();
                        }
                        catch (Exception ex)
                        {
                            _logger.LogInformation("Error loading supergroup members {group}, {message}", tg.Title, ex.Message);
                        }

                        break;
                    }

                    default:
                    {
                        tg = new TelegramChat()
                        {
                            ChatId       = chatId,
                            BasicGroupId = 0,
                            Title        = chat.Title,
                        };
                        break;
                    }
                    }

                    _chats.TryAdd(tg.ChatId, tg);
                    _loadingChats.Remove(chatId, out wait);
                    break;
                }
                catch (Exception ex) when(ex.Message.StartsWith(tdLibThrottlePrefix))
                {
                    var howLong = int.Parse(ex.Message.Substring(tdLibThrottlePrefix.Length));

                    _logger.LogWarning("TDLib throttling in progress waiting {howLong} seconds", howLong);
                    Thread.Sleep((howLong + 5) * 1000);
                }
            }
            wait.Set();
            _chatFeed.OnNext(tg);
            return(tg);
        }
Example #10
0
 public bool Remove(string nameSpace) => _namespace.Remove(nameSpace, out DataLakeNamespace? _);
Example #11
0
        public override void OnKeyUp(KeyEventArgs e)
        {
            base.OnKeyUp(e);

            _keysDown.Remove(e.Key, out _);
        }
Example #12
0
        public override async Task EventStream(IAsyncStreamReader <Event> requestStream,
                                               IServerStreamWriter <Event> responseStream, ServerCallContext context)
        {
            try
            {
                while (await requestStream.MoveNext())
                {
                    var currentEvent = requestStream.Current;
                    Console.WriteLine(currentEvent.ToString());
                    var userInfoRequest = new GetUserInfoRequest
                    {
                        Userid = currentEvent.SenderInfo.Userid
                    };
                    var senderInfo = _userClient.GetUserInfo(userInfoRequest);
                    // check if this is an initial message that is sent on the first connection'
                    //currentEvent.SenderInfo
                    if (currentEvent.SenderInfo.IsInit)
                    {
                        ActiveRequests.TryAdd(currentEvent.SenderInfo.Userid, responseStream);
                    }
                    else if (currentEvent.Message != null)
                    {
                        Console.WriteLine(currentEvent.Message.Id);
                        var message =
                            Message.CreateMessageFromRequest(currentEvent.Message, currentEvent.SenderInfo.Userid, _db);
                        // if the group is not null, add many fields for user read
                        if (message.GroupRef != null)
                        {
                            foreach (var member in message.GroupRefNavigation.GroupMembers)
                            {
                                await _db.UsersReads.AddAsync(new UsersRead
                                {
                                    MessageRefNavigation = message,
                                    MessageStatus        = 0,
                                    UserId = member.Userid
                                });

                                // change the notification templates depending on group or no group
                                // send user a notification when they are offline, otherwise send them the event
                                ActiveRequests.TryGetValue(currentEvent.Message.ReceiverUserId,
                                                           out var receiver);
                                if (receiver != null)
                                {
                                    try
                                    {
                                        await _notificationClient.SendNotificationByUserIdAsync(
                                            new UserIdNotificationRequest
                                        {
                                            Message = $"New Message: {currentEvent.Message.Message_}",
                                            Title   = $"{senderInfo.UserName}",
                                            Userid  = member.Userid
                                        });
                                    }
                                    catch (Exception)
                                    {
                                        // don't do anything, sometimes unregistered tokens don't get notified.
                                    }
                                }
                            }
                        }
                        // if group is null, this is a peer to peer message, only add one read.
                        else
                        {
                            await _db.UsersReads.AddAsync(new UsersRead
                            {
                                MessageRefNavigation = message,
                                MessageStatus        = 0,
                                UserId = requestStream.Current.Message.ReceiverUserId
                            });
                        }
                        await _db.Messages.AddAsync(message);

                        // get the active request if the user is currently subscribed
                        ActiveRequests.TryGetValue(currentEvent.Message.ReceiverUserId,
                                                   out var receiverResponse);
                        // user is currently online!
                        if (receiverResponse != null)
                        {
                            // just send the entire event over
                            await receiverResponse.WriteAsync(currentEvent);
                        }
                        else
                        {
                            // send user a notification when they are offline
                            await _notificationClient.SendNotificationByUserIdAsync(new UserIdNotificationRequest
                            {
                                Message = $"New Message: {currentEvent.Message.Message_}",
                                Title   = $"{senderInfo.UserName}",
                                Userid  = currentEvent.Message.ReceiverUserId
                            });
                        }

                        await _db.SaveChangesAsync();
                    }
                    else if (currentEvent.GroupCreated != null)
                    {
                        //var groupMembers = currentEvent.GroupCreated.
                        var group = new Group
                        {
                            // empty message list
                            Messages = { },
                            Title    = currentEvent.GroupCreated.Title,
                            Uuid     = Guid.NewGuid(),
                        };
                        await _db.Groups.AddAsync(group);

                        var groupMembers = currentEvent.GroupCreated.GroupMemberIds.Select(x => new GroupMember
                        {
                            Userid             = x,
                            GroupRefNavigation = group,
                            // everyone is not admin by default
                            IsAdmin = false,
                        });
                        await _db.GroupMembers.AddRangeAsync(groupMembers);

                        var creatorMember = new GroupMember
                        {
                            Userid             = currentEvent.GroupCreated.GroupCreator,
                            IsAdmin            = true,
                            GroupRefNavigation = group
                        };
                        foreach (var memberIds in currentEvent.GroupCreated.GroupMemberIds)
                        {
                            // get the active request if the user is currently subscribed
                            ActiveRequests.TryGetValue(memberIds,
                                                       out var receiverResponse);
                            if (receiverResponse != null)
                            {
                                // just send the entire event over
                                await receiverResponse.WriteAsync(currentEvent);
                            }
                            else
                            {
                                // send user a notification when they are offline
                                await _notificationClient.SendNotificationByUserIdAsync(new UserIdNotificationRequest
                                {
                                    Message = $"{currentEvent.GroupCreated.Title}",
                                    Title   = $"You have been added to a group!",
                                    Userid  = memberIds
                                });
                            }
                        }
                        await _db.SaveChangesAsync();
                    }
                    else if (currentEvent.MessageRead != null)
                    {
                        Console.WriteLine("message read");
                        _db.UsersReads.First(x => x.MessageRefNavigation.Uuid == Guid.Parse(currentEvent.MessageRead.MessageId)).MessageStatus = (int)currentEvent.MessageRead.MessageStatus;
                        // get the active request if the user is currently subscribed
                        var message = _db.Messages.First(x =>
                                                         x.Uuid == Guid.Parse(currentEvent.MessageRead.MessageId));
                        ActiveRequests.TryGetValue(message.AuthorId,
                                                   out var receiverResponse);
                        // user is currently online!
                        if (receiverResponse != null)
                        {
                            // just send the entire event over
                            await receiverResponse.WriteAsync(currentEvent);
                        }
                        // no need to send notification for read receipts


                        await _db.SaveChangesAsync();
                    }
                }
                // unfortunately, by this stage we might not have the key (userid) so we have to take the inefficient route and find it using linq
                // then remove it using the key, which searches for it again. Mitigate this by running it in an asynchronous task
                // so we can let this run while we remove the active user.
                await Task.Run(() =>
                {
                    // remove the request as an active request before it ends
                    var activeRequest = ActiveRequests.FirstOrDefault(x => x.Value == responseStream);
                    ActiveRequests.Remove(activeRequest.Key, out var request);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                // same thing here
                await Task.Run(() =>
                {
                    // remove any references to the current request on error
                    var activeRequest = ActiveRequests.FirstOrDefault(x => x.Value == responseStream);
                    ActiveRequests.Remove(activeRequest.Key, out var request);
                });
            }
        }
 private bool RemoveFromRunningProductions(ProductionInProgress productionInProgress)
 {
     return(_productionsInProgress.Remove(productionInProgress.ID));
 }
Example #14
0
        public static void IDictionary_Remove_NullKeyInKeyValuePair_ThrowsArgumentNullException()
        {
            IDictionary <string, int> dictionary = new ConcurrentDictionary <string, int>();

            Assert.Throws <ArgumentNullException>(() => dictionary.Remove(new KeyValuePair <string, int>(null, 0)));
        }
Example #15
0
        private static async Task <bool> Run(int blockchainID, string webSocketsUrl, string rpcUrl, BlockchainType blockchainType,
                                             BlockchainNetwork blockchainNetwork)
        {
            bool hasFailed = false;

            using (var client = new StreamingWebSocketClient(webSocketsUrl))
            {
                EthLogsObservableSubscription logsSubscription = new EthLogsObservableSubscription(client);

                Web3 cl = new Web3(rpcUrl);

                RequestInterceptor r = new RPCInterceptor(blockchainType);
                cl.Client.OverridingRequestInterceptor = r;
                EthApiService eth = new EthApiService(cl.Client);

                logsSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(async filterLog =>
                {
                    FilterLog transaction = filterLog;

                    if (transaction.Removed)
                    {
                        return;
                    }

                    if (SmartContractManager.TryGetAddress(blockchainID, filterLog.Address, out ContractTypeEnum type))
                    {
                        await ProcessSmartContractEvent(blockchainID, blockchainType, blockchainNetwork, type, eth, filterLog,
                                                        transaction, cl);
                    }
                });

                _dictionary[blockchainID] = new Subscription(client, logsSubscription);

                await client.StartAsync();

                client.Error += Client_Error;

                while (!client.IsStarted)
                {
                    await Task.Delay(1000);
                }

                await logsSubscription.SubscribeAsync();

                while (!hasFailed)
                {
                    try
                    {
                        var handler = new EthBlockNumberObservableHandler(client);
                        handler.GetResponseAsObservable().Subscribe(integer => { });
                        await handler.SendRequestAsync();

                        SystemStatus status = new SystemStatus(TaskNames.WebSockets, blockchainID);
                        await using (var connection = new MySqlConnection(OTHubSettings.Instance.MariaDB.ConnectionString))
                        {
                            await status.InsertOrUpdate(connection, true, null, false, "Blockchain Sync");
                        }
                    }

                    catch (Exception ex) when(errorCounter <= 100)
                    {
                        hasFailed = true;
                        _dictionary.Remove(blockchainID, out _);
                        client.Dispose();
                        //try
                        //{
                        //    await client.StopAsync();
                        //    await client.StartAsync();
                        //}
                        //catch (Exception)
                        //{
                        //    Logger.WriteLine(Source.BlockchainSync, ex.ToString());
                        //}
                    }

                    await Task.Delay(120000);
                }
            }

            return(!hasFailed);
        }
Example #16
0
 public void CloseTrack(int trackId)
 {
     m_TrackIds.Enqueue(trackId);
     m_ReleaseCallbacks.Remove(trackId, out _);
 }
Example #17
0
 public void Remove(string commandId)
 {
     _handledCommandDict.Remove(commandId);
 }
 public void Remove(string id)
 {
     _tasks.Remove(id, out Models.Task task);
 }
Example #19
0
        void Flush()
        {
            if (WrappedTarget == null)
            {
                InternalLogger.Error("BufferingWrapper(Name={0}): WrappedTarget is NULL", Name);
                return;
            }

            lock (_lockObject)
            {
#if USECONCURRENT
                ICollection <AsyncLogEventInfo> keys = _entriesCounts.Keys;
#else
                ICollection <AsyncLogEventInfo> keys = _entriesCounts.Keys.ToList();
#endif
                foreach (AsyncLogEventInfo initialLog in keys)
                {
                    Tuple <int, StringBuilder, AsyncLogEventInfo> count;
#if USECONCURRENT
                    if (_entriesCounts.TryRemove(initialLog, out count) && count.Item1 > 0)
#else
                    count = _entriesCounts[initialLog];
                    if (_entriesCounts.Remove(initialLog))
#endif
                    {
                        AsyncLogEventInfo lastLog = count.Item3;

                        // do not remove if count > 0 (insert it back) - on aggressive logs we should not send an extra log
#if USECONCURRENT
                        _entriesCounts.AddOrUpdate(initialLog,
                                                   new Tuple <int, StringBuilder, AsyncLogEventInfo>(0, NeedsStringBuilder(initialLog.LogEvent) ? new StringBuilder() : null, default(AsyncLogEventInfo)),
                                                   (k, v) => v /*do not change it if it is already there - situation is aggressive and first log is already sent*/);
#else
                        lock (_lockObject)
                        {
                            if (!_entriesCounts.ContainsKey(initialLog))
                            {
                                _entriesCounts[initialLog] =
                                    new Tuple <int, StringBuilder, AsyncLogEventInfo>(0,
                                                                                      NeedsStringBuilder(initialLog.LogEvent)
                                            ? new StringBuilder()
                                            : null, default(AsyncLogEventInfo));
                            }
                        }
#endif


                        if (count.Item1 > 1)
                        {
                            string sbString = null;

                            if (NeedsStringBuilder(lastLog.LogEvent))
                            {
                                lastLog.LogEvent.Properties["AccumulatedMessages"] =
                                    sbString = count.Item2.ToString();
                            }

                            if (CorrectMessageForGroup && !string.IsNullOrEmpty(CountAppendFormat))
                            {
                                if (sbString != null)
                                {
                                    lastLog.LogEvent.Message
                                        = /*messages differ so log all of them*/
                                          Escape(lastLog.LogEvent.Message) +
                                          string.Format(CountAppendFormat, count.Item1) +
                                          (this.GroupByTemplateSeparator == Environment.NewLine
                                            ? Environment.NewLine
                                            : "") +
                                          sbString;
                                }
                                else
                                {
                                    lastLog.LogEvent.Message
                                        += /*all messages are the same, so just append count*/
                                           string.Format(CountAppendFormat, count.Item1);
                                }
                            }
                        }

                        lastLog.LogEvent.Properties["AccumulatedCount"] = count.Item1;
                        lastLog.LogEvent.Properties["IsFirst"]          = "false";
                        WrappedTarget.WriteAsyncLogEvents(lastLog);
                    }
                }
            }
        }
Example #20
0
 public void Delete(int id)
 {
     data.Remove(id, out var value);
 }
Example #21
0
 public Task DeleteContext(Identity identity)
 {
     _data.Remove(GetKey(identity), out _);
     return(Task.CompletedTask);
 }
Example #22
0
        public static async Task UploadBlobsAsync
            (CloudBlobClient blobClient,
            CloudBlobContainer container,
            string blobPrefix,
            ulong blobSizeInBytes,
            int levelOfConcurrency,
            CancellationToken cancellationToken)
        {
            // Create a buffer with the given size.
            byte[] buffer = new byte[blobSizeInBytes];
            Random rand   = new Random();

            rand.NextBytes(buffer);


            // Create a task to periodically report metrics until cancellation.
            Task metricReportingTask = new Task(async() =>
            {
                TimeSpan reportPeriod = TimeSpan.FromSeconds(5);
                ulong nPreviouslyScheduledOperations = nScheduledOperations;
                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Delay(reportPeriod);

                    ulong nCurrentlyScheduledOperations = nScheduledOperations;
                    ulong deltaOperations = nCurrentlyScheduledOperations - nPreviouslyScheduledOperations;
                    double tps            = deltaOperations / reportPeriod.TotalSeconds;
                    Console.WriteLine($"\t{deltaOperations} PutBlob operations issued in {reportPeriod.TotalSeconds} seconds ({tps} TPS).");
                    nPreviouslyScheduledOperations = nCurrentlyScheduledOperations;
                }
            });

            try
            {
                ConcurrentDictionary <string, Task> tasks = new ConcurrentDictionary <string, Task>();
                SemaphoreSlim semaphore = new SemaphoreSlim(levelOfConcurrency, levelOfConcurrency);

                metricReportingTask.Start();

                for (; !cancellationToken.IsCancellationRequested; ++nScheduledOperations)
                {
                    string blobName = blobPrefix + nScheduledOperations;

                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

                    await semaphore.WaitAsync();

                    tasks[blobName] = Task.Run(async() =>
                    {
                        try
                        {
                            await blockBlob.UploadFromByteArrayAsync(buffer, 0, buffer.Length, AccessCondition.GenerateEmptyCondition(), new BlobRequestOptions(), new OperationContext(), cancellationToken);
                            ++nCompleteOperations;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            tasks.Remove(blobName, out Task val);
                            semaphore.Release();
                        }
                    }, cancellationToken);
                }

                ICollection <Task> remainingTasks = tasks.Values;
                Console.WriteLine($"Cancellation received. Waiting for the remaining {remainingTasks.Count()} operations to complete.");
                remainingTasks.Append(metricReportingTask);
                await Task.WhenAll(remainingTasks);
            }
            finally
            {
                Console.WriteLine($"Issued {nScheduledOperations} operations. Successfully completed {nCompleteOperations} operations.");
            }
        }
Example #23
0
File: Cache.cs Project: ted9/cqrs
        public void Evict(string region)
        {
            GetCacheByRegion(region).Clear();

            _caches.Remove(region);
        }
Example #24
0
 public void UnregisterWindow(uint windowId)
 {
     _registeredWindowHandlers.Remove(windowId, out _);
 }
Example #25
0
        public async Task <JsonResult> StartWatering(int activityToDo, string plantNumber, Dictionary <string, double> plantDict, int waterLevel = 0)
        {
            //check in dict if plantActiveDict contains task and activityTodo is start or stop
            //if task exists and is new process then create new task with new cancellation token and add into concurrentBag
            //if task exists and is not new process then cancel task
            double waterlevel = 0;

            //if (plantDict.ContainsKey(plantNumber))
            //{
            if (plantsActivityDict == null)
            {
                plantsActivityDict = new ConcurrentDictionary <string, WaterDTO>();
            }
            if (activityToDo == 1 && !plantsActivityDict.ContainsKey(plantNumber))
            {
                var tokenSource = new CancellationTokenSource();
                var token       = tokenSource.Token;
                //start water=1 && stop Water=2
                WaterDTO waterDTO = new WaterDTO();
                // ViewData["planActivitySession"] = plantsActivityDict;
                waterDTO.tokenSource = tokenSource;
                plantsActivityDict.TryAdd(plantNumber, waterDTO);


                Task t;
                var  tasks = new ConcurrentBag <Task>();

                t = Task.Run(() => DoRunTask(activityToDo, plantNumber, plantDict, waterDTO, token, waterLevel), token);
                tasks.Add(t);
            }
            //  }
            else if (activityToDo == 2)
            {
                // WaterDTO waterDTO = new WaterDTO();
                //waterDTO.stopwatch.Stop();
                //waterlevel = waterDTO.stopwatch.Elapsed.TotalSeconds;
                //if(waterlevel>10)
                var waterObj = plantsActivityDict[plantNumber];
                waterObj.tokenSource.Cancel();
                waterObj.stopwatch.Stop();
                var timeElapsed = waterObj.stopwatch.Elapsed;
                waterlevel = timeElapsed.TotalSeconds;
                plantsActivityDict.Remove(plantNumber, out waterObj);
                ViewData["planActivitySession"] = plantsActivityDict;
            }



            // plantDict.TryGetValue(plantNumber, out waterlevel);

            //Stopwatch stopwatch = new Stopwatch();


            //if (plantDict.ContainsKey(plantNumber))
            //{
            //    if (activityToDo == 1 && !plantsActivityDict.ContainsKey(plantNumber))
            //    {

            //        plantsActivityDict.TryAdd(plantNumber, waterDTO);


            //        // Begin timing
            //        waterDTO.stopwatch = new Stopwatch();
            //        waterDTO.stopwatch.Start();
            //        //  var timer = new System.Timers.Timer(10);
            //        // timer.Elapsed+=new ElapsedEventHandler()


            //        while (waterDTO.stopwatch.Elapsed < TimeSpan.FromSeconds(100))
            //        {
            //            if (!plantsActivityDict.ContainsKey(plantNumber))
            //            {
            //                var waterObj = plantsActivityDict[plantNumber];
            //                waterObj.tokenSource.Cancel();
            //                waterDTO.stopwatch.Stop();
            //            }
            //        }

            //        // Stop.s
            //        waterDTO.stopwatch.Stop();
            //        waterlevel = waterDTO.stopwatch.Elapsed.TotalSeconds;

            //    }
            //else if (activityToDo == 2)
            //{
            //    //waterDTO.stopwatch.Stop();
            //    //waterlevel = waterDTO.stopwatch.Elapsed.TotalSeconds;
            //    //if(waterlevel>10)
            //    var waterObj = plantsActivityDict[plantNumber];
            //    waterObj.tokenSource.Cancel();
            //    plantsActivityDict.TryRemove(plantNumber, out waterDTO);
            //    ViewData["planActivitySession"] = plantsActivityDict;


            //}
            // waterDTO.WaterLevel = waterDTO.stopwatch.Elapsed.TotalSeconds;


            plantDict[plantNumber] = waterlevel;

            var jsonResult = Json(plantDict);

            return(jsonResult);
        }
Example #26
0
        /**
         * Check the congestion after receiving the given sequence number that was acknowledged
         * We also switch send rates in this method if the average RTT is consistently high/low
         */
        private void CheckCongestion(ushort sequence)
        {
            if (!_sentQueue.TryGetValue(sequence, out var sentPacket))
            {
                return;
            }

            var stopwatch = sentPacket.Stopwatch;

            var rtt        = stopwatch.ElapsedMilliseconds;
            var difference = rtt - _averageRtt;

            // Adjust average with 1/10th of difference
            _averageRtt += difference * 0.1f;

            _sentQueue.Remove(sequence);

            if (_isChannelCongested)
            {
                // If the stopwatch for checking packets below the threshold was already running
                if (_belowThresholdStopwatch.IsRunning)
                {
                    // If our average is above the threshold again, we reset the stopwatch
                    if (_averageRtt > CongestionThreshold)
                    {
                        _belowThresholdStopwatch.Reset();
                    }
                }
                else
                {
                    // If the stopwatch wasn't running, and we are below the threshold
                    // we can start the stopwatch again
                    if (_averageRtt < CongestionThreshold)
                    {
                        _belowThresholdStopwatch.Start();
                    }
                }

                // If the average RTT was below the threshold for a certain amount of time,
                // we can go back to high send rates
                if (_belowThresholdStopwatch.IsRunning &&
                    _belowThresholdStopwatch.ElapsedMilliseconds > _currentSwitchTimeThreshold)
                {
                    Logger.Info(this, "Switched to non-congested send rates");

                    _isChannelCongested = false;

                    _udpUpdateManager.CurrentSendRate = HighSendRate;

                    // Reset whether we have spent the threshold in non-congested mode
                    _spentTimeThreshold = false;

                    // Since we switched send rates, we restart the stopwatch again
                    _currentCongestionStopwatch.Reset();
                    _currentCongestionStopwatch.Start();
                }
            }
            else
            {
                // If the channel is not congested, we check whether we have spent a certain
                // amount of time in this mode, and decrease the switch threshold
                if (_currentCongestionStopwatch.ElapsedMilliseconds > TimeSpentCongestionThreshold)
                {
                    // We spent at least the threshold in non-congestion mode
                    _spentTimeThreshold = true;

                    _currentCongestionStopwatch.Reset();
                    _currentCongestionStopwatch.Start();

                    // Also cap it at a minimum
                    _currentSwitchTimeThreshold = Math.Max(_currentSwitchTimeThreshold / 2, MinimumSwitchThreshold);

                    Logger.Info(this, $"Proper time spent in non-congested mode, halved switch threshold to: {_currentSwitchTimeThreshold}");

                    // After we reach the minimum threshold, there's no reason to keep the stopwatch going
                    if (_currentSwitchTimeThreshold == MinimumSwitchThreshold)
                    {
                        _currentCongestionStopwatch.Reset();
                    }
                }

                // If the channel was not previously congested, but our average round trip time
                // exceeds the threshold, we switch to congestion values
                if (_averageRtt > CongestionThreshold)
                {
                    Logger.Info(this, "Switched to congested send rates");

                    _isChannelCongested = true;

                    _udpUpdateManager.CurrentSendRate = LowSendRate;

                    // If we were a few seconds in the High send rates before switching again, we
                    // double the threshold for switching
                    if (!_spentTimeThreshold)
                    {
                        // Also cap it at a maximum
                        _currentSwitchTimeThreshold = Math.Min(_currentSwitchTimeThreshold * 2, MaximumSwitchThreshold);

                        Logger.Info(this, $"Too little time spent in non-congested mode, doubled switch threshold to: {_currentSwitchTimeThreshold}");
                    }

                    // Since we switched send rates, we restart the stopwatch again
                    _currentCongestionStopwatch.Reset();
                    _currentCongestionStopwatch.Start();
                }
            }
        }
Example #27
0
        async void HandleClient(TcpClient client)
        {
            var clientAddress = client.Client.RemoteEndPoint.ToString();

            Console.WriteLine($"Serving new console client: {clientAddress}");

            connectedClients[clientAddress] = client;

            // Apparently client.Close() disposes of these...?
            var reader = new StreamReader(client.GetStream(), Encoding.UTF8);
            var writer = new StreamWriter(client.GetStream(), Encoding.UTF8);

            writer.AutoFlush = true;

            bool servingClient = true;

            while (servingClient)
            {
                string line;
                try
                {
                    writer.WriteLine();
                    writer.Write("> ");
                    line = await reader.ReadLineAsync();
                }
                catch
                {
                    Console.WriteLine($"Lost console client: {clientAddress}");
                    servingClient = false;
                    continue;
                }

                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                var toks = Regex.Split(line, @"\s+").Where(s => s != string.Empty).ToArray();
                if (toks.Length == 0 || string.IsNullOrEmpty(toks[0]))
                {
                    continue;
                }

                switch (toks[0])
                {
                case "quit":
                case "exit":
                case "disconnect":
                case "bye":
                    client.Close();
                    servingClient = false;
                    break;

                case "shutdown":
                case "kill":
                    bot.ForceStop();
                    client.Close();
                    servingClient = false;
                    listener.Stop();
                    break;

                case "say":
                    if (toks.Length < 3)
                    {
                        break;
                    }

                    string to        = toks[1];
                    string something = String.Join(" ", toks.Skip(2).Take(toks.Length - 2).ToArray());
                    bot.Say(something, to);
                    break;

                default:
                    Console.WriteLine($"Unknown command: '{toks[0]}'");
                    break;
                }
            }

            if (connectedClients.ContainsKey(clientAddress))
            {
                connectedClients.Remove(clientAddress, out _);
            }

            Console.WriteLine($"No longer serving console client: {clientAddress}");
        }
Example #28
0
 /// <summary>
 /// Deletes the data in specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 public static bool Delete(string path)
 {
     return(_memory.Remove(path));
 }
Example #29
0
 public bool RemoveNpc(int objectId)
 {
     return(npcs.Remove(objectId, out _));
 }
Example #30
0
 public bool RemovePortal(int objectId)
 {
     return(portals.Remove(objectId, out _));
 }
Example #31
0
 public void Handle(PeerStopped message)
 {
     _peers.Remove(message.PeerId);
 }
        public void Remove_WithKeyValuePairThrowsNotImplementedException()
        {
            // Arrange
            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();

            // Act/Assert
            Assert.Throws<NotImplementedException>(() => dictionary.Remove(new KeyValuePair<int, int>(0, 0)));
        }
Example #33
0
        public void Leave(Player plr, RoomLeaveReason roomLeaveReason = RoomLeaveReason.Left)
        {
            using (_playerSync.Lock())
            {
                if (plr.Room != this)
                {
                    return;
                }
                try
                {
                    if (plr.RelaySession?.HostId != null)
                    {
                        Group?.Leave(plr.RelaySession.HostId);
                    }

                    Broadcast(new RoomLeavePlayerAckMessage(plr.Account.Id, plr.Account.Nickname, roomLeaveReason));

                    if (roomLeaveReason == RoomLeaveReason.Kicked ||
                        roomLeaveReason == RoomLeaveReason.ModeratorKick ||
                        roomLeaveReason == RoomLeaveReason.VoteKick)
                    {
                        _kickedPlayers.TryAdd(plr.Account.Id, null);
                    }

                    plr.LocationInfo.Invisible = false;
                    var curchannelid = (uint)(plr.Channel?.Id ?? 0);
                    plr.Channel?.Leave(plr, true);
                    GameServer.Instance.ChannelManager[curchannelid].Join(plr);

                    plr.RoomInfo.PeerId = 0;
                    plr.RoomInfo.Team?.Leave(plr);
                    _players?.Remove(plr.Account.Id);
                    plr.Room = null;
                    plr.Session?.SendAsync(new RoomLeavePlayerInfoAckMessage(plr.Account.Id));
                    plr.Session?.SendAsync(
                        new ItemClearInvalidEquipItemAckMessage {
                        Items = new InvalidateItemInfoDto[] { }
                    });
                    plr.Session?.SendAsync(new ItemClearEsperChipAckMessage {
                        Unk = new ClearEsperChipDto[] { }
                    });

                    if (GameState == GameState.Playing)
                    {
                        plr.stats.Loss++;
                    }

                    if (TeamManager.Players.Any())
                    {
                        ChangeMasterIfNeeded(GetPlayerWithLowestPing());
                        ChangeHostIfNeeded(GetPlayerWithLowestPing());
                        OnPlayerLeft(new RoomPlayerEventArgs(plr));
                    }
                    else
                    {
                        RoomManager.Remove(this);
                    }
                }
                catch (Exception ex)
                {
                    Broadcast(new RoomLeavePlayerAckMessage(plr.Account.Id, plr.Account.Nickname, roomLeaveReason));
                    Broadcast(new RoomLeavePlayerInfoAckMessage(plr.Account.Id));

                    _players?.Remove(plr.Account.Id);
                    Logger.Error(ex.ToString());
                }
            }
        }
Example #34
0
        public void Leave(Player plr, RoomLeaveReason roomLeaveReason = RoomLeaveReason.Left)
        {
            if (plr.Room != this)
            {
                return;
            }
            try
            {
                if (plr.RelaySession?.HostId != null)
                {
                    Group?.Leave(plr.RelaySession.HostId);
                }

                Broadcast(new RoomLeavePlayerAckMessage(plr.Account.Id, plr.Account.Nickname, roomLeaveReason));
                Broadcast(new RoomLeavePlayerInfoAckMessage(plr.Account.Id));

                if (roomLeaveReason == RoomLeaveReason.Kicked ||
                    roomLeaveReason == RoomLeaveReason.ModeratorKick ||
                    roomLeaveReason == RoomLeaveReason.VoteKick)
                {
                    _kickedPlayers.TryAdd(plr.Account.Id, null);
                }

                plr.LocationInfo.Invisible = false;
                var curchannelid = (uint)plr.Channel.Id;
                plr.Channel.Leave(plr, true);
                GameServer.Instance.ChannelManager[curchannelid].Join(plr);

                plr.RoomInfo.PeerId = 0;
                plr.RoomInfo?.Team?.Leave(plr);
                _players?.Remove(plr.Account.Id);
                plr.Room = null;

                if (_players != null && _players.Count > 0)
                {
                    if (Master == plr)
                    {
                        ChangeMasterIfNeeded(GetPlayerWithLowestPing(), true);
                    }

                    if (Host == plr)
                    {
                        ChangeHostIfNeeded(GetPlayerWithLowestPing(), true);
                    }

                    OnPlayerLeft(new RoomPlayerEventArgs(plr));
                }
                else
                {
                    RoomManager.Remove(this);
                }
            }
            catch (Exception ex)
            {
                Broadcast(new RoomLeavePlayerAckMessage(plr.Account.Id, plr.Account.Nickname, roomLeaveReason));
                Broadcast(new RoomLeavePlayerInfoAckMessage(plr.Account.Id));

                if (_players.Count == 1)
                {
                    plr?.Channel?.RoomManager?.Remove(this);
                }

                _players?.Remove(plr.Account.Id);
                Logger.Error(ex.ToString());
            }
        }
Example #35
0
 private void LoadChannels(ConcurrentDictionary<ulong, UserEventCallback> dict)
 {
     foreach (var pair in dict)
     {
         try
         {
             pair.Value.Channel = _client.GetServer(pair.Key).GetChannel(pair.Value.ChannelId);
         }
         catch (NullReferenceException)
         {
             Logger.FormattedWrite("AnnounceLoad",
                 $"Failed loading channel {pair.Value.ChannelId} for server {pair.Key}. Removing",
                 ConsoleColor.Yellow);
             dict.Remove(pair.Key);
         }
     }
 }