Example #1
0
 public async Task <IEnumerable <NicoVideoCacheInfo> > EnumerateCacheVideosAsync()
 {
     using (var releaser = await _CacheRequestProcessingLock.LockAsync())
     {
         return(_CacheVideos.SelectMany(x => x.Value).ToArray());
     }
 }
Example #2
0
        public Task <Result <IEnumerable <DomainEventWrapper> > > LoadEvents(long lastOverallVersion = 0)
        {
            var domainEvents        = _domainEvents.SelectMany(e => e.Value);
            var domainEventWrappers = domainEvents
                                      .Where(e => e.OverallVersion > lastOverallVersion)
                                      .OrderBy(e => e.OverallVersion);

            return(Task.FromResult(Result <IEnumerable <DomainEventWrapper> > .Ok(domainEventWrappers)));
        }
        public IEnumerable <Subscription> GetSubscriptionsBySubscriberStartsWith(string subscriberPrefix)
        {
            var empty = new List <Subscription>();

            if (subscriberPrefix.IsNullOrEmpty())
            {
                return(empty);
            }

            return(_resources.SelectMany(i => i.Value).Select(m => m.Value).Where(k => k.Subscriber.StartsWith(subscriberPrefix)).ToList());
        }
Example #4
0
        public ScanResult GetScanResult()
        {
            var flatResult = _graph.SelectMany(g => g.Value.Select(v => new Tuple <PackageReference, RepoInfo>(g.Key, v))).ToArray();
            var statString = $"Last update time {_lastUpDateTime}. NuGet packages found {_packagesFound}";

            return(new ScanResult(_status, statString, flatResult));
        }
Example #5
0
        private void LoadSettings()
        {
            OnlineLibrarySettings settings = ServiceRegistration.Get <ISettingsManager>().Load <OnlineLibrarySettings>();

            //Music matchers
            ConfigureMatchers(AUDIO_MATCHERS.SelectMany(m => m.Value), settings.MusicMatchers, settings.MusicLanguageCulture, settings.UseMusicAudioLanguageIfUnmatched);

            //Movie matchers
            ConfigureMatchers(MOVIE_MATCHERS.SelectMany(m => m.Value), settings.MovieMatchers, settings.MovieLanguageCulture, settings.UseMovieAudioLanguageIfUnmatched);

            //Series matchers
            ConfigureMatchers(SERIES_MATCHERS.SelectMany(m => m.Value), settings.SeriesMatchers, settings.SeriesLanguageCulture, settings.UseSeriesAudioLanguageIfUnmatched);

            //Subtitle matchers
            ConfigureMatchers(SUBTITLE_MATCHERS.SelectMany(m => m.Value), settings.SubtitleMatchers, settings.SubtitleLanguageCulture, false);
        }
Example #6
0
        /// <inheritdoc cref="IConsumer{TKey,TValue}.Commit()" />
        public List <TopicPartitionOffset> Commit()
        {
            var topicPartitionOffsets = _storedOffsets.SelectMany(
                topicPair => topicPair.Value.Select(
                    partitionPair => new TopicPartitionOffset(
                        topicPair.Key,
                        partitionPair.Key,
                        partitionPair.Value))).ToList();

            var topicPartitionOffsetsByTopic = topicPartitionOffsets.GroupBy(tpo => tpo.Topic);

            var actualCommittedOffsets = new List <TopicPartitionOffset>();

            foreach (var group in topicPartitionOffsetsByTopic)
            {
                actualCommittedOffsets.AddRange(_topics[group.Key].Commit(GroupId, group));
            }

            if (actualCommittedOffsets.Count > 0)
            {
                OffsetsCommittedHandler?.Invoke(
                    this,
                    new CommittedOffsets(
                        actualCommittedOffsets
                        .Select(
                            topicPartitionOffset =>
                            new TopicPartitionOffsetError(topicPartitionOffset, null)).ToList(),
                        null));
            }

            return(actualCommittedOffsets);
        }
Example #7
0
 /// <summary>
 /// Flushes changes since last sink for each metric.
 /// Called when Driver is sinking metrics.
 /// </summary>
 /// <returns>Key value pairs of metric name and record that was flushed.</returns>
 public IEnumerable <KeyValuePair <string, MetricTracker.MetricRecord> > FlushMetricRecords()
 {
     // for each metric, flush the records and create key value pairs
     return(_metricsMap.SelectMany(
                kv => kv.Value.FlushRecordsCache().Select(
                    r => new KeyValuePair <string, MetricTracker.MetricRecord>(kv.Key, r))));
 }
Example #8
0
        public void Run(int queries, int threads, int prepared)
        {
            Console.WriteLine("Preparing...");
            _queries   = queries;
            _manager   = new CartManager();
            _times     = new ConcurrentDictionary <string, LinkedList <long> >();
            _stopwatch = new Stopwatch();
            _count     = 0;
            _groups    = Enumerable.Range(0, 9).Select(n => "group_" + n).ToArray();


            //pregenerate carts
            _manager.PrepareDbAsync().Wait();
            var cartTasks = new Task <Cart> [prepared];
            int groupId   = 0;

            for (int i = 0; i < prepared; i++)
            {
                cartTasks[i] = _manager.AddCartAsync(_groups[groupId]);
                groupId      = (groupId + 1) % _groups.Length;
            }

            Task.WaitAll(cartTasks);
            var carts = cartTasks.Select(t => t.Result).ToArray();

            Console.WriteLine("Executing...");

            //execute!
            _stopwatch.Start();
            var doTasks = new LinkedList <Task>();

            for (int i = 0; i < threads; i++)
            {
                doTasks.AddLast(DoAddCarts());
                doTasks.AddLast(DoAddItems(carts));
                //doTasks.AddLast(DoFindByGroupId());
                doTasks.AddLast(DoGetItems(carts));
                doTasks.AddLast(DoUpdateCarts(carts));
            }

            Task.WaitAll(doTasks.ToArray());

            _stopwatch.Stop();

            //print results
            Console.WriteLine("Total tasks run: {0} in {1} ({2} req/s)", _count, _stopwatch.Elapsed,
                              DoubleString((double)queries / _stopwatch.ElapsedMilliseconds * 1000));

#if debug
            Console.WriteLine(MemoryPool.Instance);
#endif
            Console.WriteLine();
            WriteRow("", "Calls", "Avg", "Median", "Min", "Max");
            WriteStatistics("Total", _times.SelectMany(vls => vls.Value));
            Console.WriteLine(new string('-', 60));
            foreach (var call in _times)
            {
                WriteStatistics(call.Key, call.Value);
            }
        }
Example #9
0
        internal RootManager(WorkspaceSuperviser superviser, IStateDispatcherConfigurator stateDispatcher, IEnumerable <StateBuilderBase> states,
                             IEnumerable <IEffect?> effects, IEnumerable <IMiddleware?> middlewares, bool sendBackSetting, Maybe <IComponentContext> componentContext)
        {
            _sendBackSetting = sendBackSetting;
            _engine          = MutatingEngine.Create(superviser, stateDispatcher.Configurate);
            _effects         = effects.Where(e => e != null).ToArray() !;
            _middlewares     = middlewares.Where(m => m != null).ToArray() !;

            foreach (var stateBuilder in states)
            {
                var(container, key) = stateBuilder.Materialize(_engine, componentContext);

                _stateContainers.GetOrAdd(key.OrElse(string.Empty), _ => new ConcurrentBag <StateContainer>()).Add(container);
            }

            _states = _stateContainers.SelectMany(b => b.Value).ToArray();

            foreach (var middleware in _middlewares)
            {
                middleware.Initialize(this);
            }

            foreach (var middleware in _middlewares)
            {
                middleware.AfterInitializeAllMiddlewares();
            }
        }
        private static void CheckForCaches(string collectioName = "", Culture culture = null, MessageType msgMode = MessageType.General)
        {
            DateTime dt = DateTime.Now;

            if (culture != null)
            {
                DictionaryAccessTime dic;
                if (Dic[collectioName][culture].TryGetValue(msgMode, out dic))
                {
                    dic.Value = dt;
                }
            }
            if (_shouldberemoved && (dt - _lastCleanUp).TotalSeconds > MinSeconds)
            {
                _lastCleanUp = dt;
                foreach (var kpp in Dic.SelectMany(kp => kp.Value))
                {
                    foreach (MessageType messageType in kpp.Value.Keys)
                    {
                        if (((dt - kpp.Value[messageType].Value).TotalSeconds > MinSeconds))
                        {
                            DictionaryAccessTime obj;
                            kpp.Value.TryRemove(messageType, out obj);
                        }
                    }
                }
            }
        }
        public ScanResult GetScanResult()
        {
            var flatResult = _graph.SelectMany(g => g.Value.Select(v => new Tuple <PackageReference, RepoInfo>(g.Key, v))).ToArray();
            var statString = $"Last update time {_lastUpDateTime}. Found {_foundReposCount} repositories, scanned {_scannedProjectFilesCount} projects.";

            return(new ScanResult(_status, statString, flatResult));
        }
Example #12
0
        public override Task OnDisconnected()
        {
            Log.DebugFormat("Disconnect from client='{0}'", Context.ConnectionId);
            int ignored;

            ConnectedClients.TryRemove(Context.ConnectionId, out ignored);

            try
            {
                foreach (var player in DraftManagers.SelectMany(x => x.Value.Players))
                {
                    player.ClientIds.Remove(Context.ConnectionId);
                }
            }
            catch
            {
            }

            /*foreach (var player in ConnectedPlayers.Where(c => c.ConnectedClients.Contains(Context.ConnectionId)))
             * {
             *  player.ConnectedClients.Remove(Context.ConnectionId);
             *
             *  if (player.ConnectedClients.Count == 0)
             *      ConnectedPlayers.Remove(player);
             * }*/

            return(base.OnDisconnected());
        }
Example #13
0
        /// <summary>
        /// Get last 30 seconds samples data from memory of selected samples types.
        /// Default is all types retrieved
        /// </summary>
        /// <param name="sampleTypeIds">id of sample type (ram, memory)</param>
        /// <returns></returns>
        public List <SampleDataModel> GetLastThirtySeconds(params int[] sampleTypeIds)
        {
            var result = new List <SampleDataModel>();

            if (sampleTypeIds != null)
            {
                if (sampleTypeIds.Count() > 0)
                {
                    foreach (var sampleTypeId in sampleTypeIds)
                    {
                        List <SampleDataModel> list;
                        _samplesCache.TryGetValue(sampleTypeId, out list);

                        if (list != null)
                        {
                            result.AddRange(list);
                        }
                    }
                }
                else
                {
                    result = _samplesCache.SelectMany(x => x.Value).ToList();
                }
            }

            var now = DateTime.UtcNow;
            var lastThirySecondsList = result.Where(x => (now - x.TimeStamp).TotalSeconds <= 30).ToList();

            return(lastThirySecondsList);
        }
Example #14
0
 /// <summary>
 /// Updates the cached ranges.
 /// </summary>
 private void UpdateCachedRanges()
 {
     _cachedRanges =
         _cache.SelectMany(x => x.Value.AddressRanges)
         .OrderBy(x => x.Address)
         .Aggregate(new List <AddressRange>(), AddAddressRange);
 }
Example #15
0
        public static async Task <ImmutableDictionary <Document, ImmutableArray <Diagnostic> > > GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext)
        {
            var allDiagnostics = ImmutableArray <Diagnostic> .Empty;
            var projectsToFix  = ImmutableArray <Project> .Empty;

            var document = fixAllContext.Document;
            var project  = fixAllContext.Project;

            switch (fixAllContext.Scope)
            {
            case FixAllScope.Document:
                if (document != null)
                {
                    var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);

                    return(ImmutableDictionary <Document, ImmutableArray <Diagnostic> > .Empty.SetItem(document, documentDiagnostics));
                }

                break;

            case FixAllScope.Project:
                projectsToFix  = ImmutableArray.Create(project);
                allDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, project).ConfigureAwait(false);

                break;

            case FixAllScope.Solution:
                projectsToFix = project.Solution.Projects
                                .Where(p => p.Language == project.Language)
                                .ToImmutableArray();

                var diagnostics = new ConcurrentDictionary <ProjectId, ImmutableArray <Diagnostic> >();
                var tasks       = new Task[projectsToFix.Length];
                for (int i = 0; i < projectsToFix.Length; i++)
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    var projectToFix = projectsToFix[i];
                    tasks[i] = Task.Run(
                        async() =>
                    {
                        var projectDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, projectToFix).ConfigureAwait(false);
                        diagnostics.TryAdd(projectToFix.Id, projectDiagnostics);
                    },
                        fixAllContext.CancellationToken);
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);

                allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value.Where(x => fixAllContext.DiagnosticIds.Contains(x.Id))));
                break;
            }

            if (allDiagnostics.IsEmpty)
            {
                return(ImmutableDictionary <Document, ImmutableArray <Diagnostic> > .Empty);
            }

            return(await GetDocumentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false));
        }
Example #16
0
 public List <QueueItem> GetTimeoutedItems()
 {
     return(_queues
            .SelectMany(x => x.Value.Fetched)
            .Select(x => x.Value)
            .Where(i => DateTime.UtcNow > i.TimeoutAt)
            .ToList());
 }
Example #17
0
        /// <summary>
        /// 获取指定类型的上下文实例
        /// </summary>
        /// <param name="dbContextType">上下文类型</param>
        /// <returns></returns>
        public IDbContext GetDbContext(Type dbContextType)
        {
            //已存在上下文对象,直接返回
            DbContextBase dbContext = _contextDict.SelectMany(m => m.Value)
                                      .FirstOrDefault(m => m.GetType() == dbContextType);

            if (dbContext != null)
            {
                _logger.LogDebug($"获取到已存在的上下文 {dbContext.GetType()} 实例,上下文标识:{dbContext.GetHashCode()}");
                return(dbContext);
            }

            dbContext = (DbContextBase)GetDbContextInternal(dbContextType);
            _logger.LogDebug($"创建新的上下文 {dbContext.GetType()} 实例,上下文标识:{dbContext.GetHashCode()}");

            return(dbContext);
        }
Example #18
0
 public Task <IEnumerable <JiraIssueModel> > GetBulkIssues(IEnumerable <string> issueKeys)
 {
     return(Task.FromResult <IEnumerable <JiraIssueModel> >(
                jiraIssueStore.SelectMany(x => x.Value)
                .Where(x => issueKeys.Contains(x.Key))
                .GroupBy(x => x.Key)
                .Select(group => group.First())));
 }
Example #19
0
 /// <summary>
 /// Use it for statistics if you want
 /// </summary>
 public static int GetMessageDataCount(Type type)
 {
     if (type == null)
     {
         return(MessageDataDictionary.SelectMany(v => v.Value).Count());
     }
     return(MessageDataDictionary.TryGetValue(type.Name, out var list) ? list.Count : 0);
 }
        public async Task <IEnumerable <Game> > GetGamesForTeam(string team, CancellationToken cancellationToken)
        {
            if (!_cacheInitialized)
            {
                await InitializeCache(cancellationToken);
            }

            return(_gamesPerSeasonCache.SelectMany(x => x.Value.Where(g => g.HomeTeam == team || g.AwayTeam == team)));
        }
Example #21
0
 /// <summary>
 /// Updates the fill forward resolution by checking all existing subscriptions and
 /// selecting the smallest resoluton not equal to tick
 /// </summary>
 private void UpdateFillForwardResolution()
 {
     _fillForwardResolution.Value = _subscriptions
                                    .SelectMany(x => x.Value)
                                    .Where(x => !x.Configuration.IsInternalFeed)
                                    .Select(x => x.Configuration.Resolution)
                                    .Where(x => x != Resolution.Tick)
                                    .DefaultIfEmpty(Resolution.Minute)
                                    .Min().ToTimeSpan();
 }
Example #22
0
        public static void __check(this object obj)
        {
            IEnumerable <IDisposable> x = tracker.SelectMany(cd => cd.Value);
            int i;

            if ((i = x.Count()) > 0)
            {
                throw new InvalidOperationException(i.ToString());
            }
        }
        void PossiblyTrimCache()
        {
            var numberOfEntriesCurrentlyInTheCache = Interlocked.Read(ref _currentNumberOfCacheEntries);

            if (numberOfEntriesCurrentlyInTheCache <= _approximateMaxNumberOfCacheEntries)
            {
                return;
            }

            var removalsToPerform = Math.Max(10, _approximateMaxNumberOfCacheEntries / 10);

            _logger.Debug("Performing cache trimming - cache currently holds {0} entries divided among {1} aggregate roots - will attempt to perform {2} removals",
                          numberOfEntriesCurrentlyInTheCache, _cacheEntries.Count, removalsToPerform);

            var entriesOrderedByValue = _cacheEntries
                                        .SelectMany(kvp => kvp.Value)
                                        .Select(kvp => kvp.Value)
                                        .Select(entry => new
            {
                Entry = entry,
                Value = entry.ComputeValue()
            })
                                        .OrderBy(a => a.Value)
                                        .ToArray();

            var index = 0;

            while (index < entriesOrderedByValue.Length && removalsToPerform > 0)
            {
                ConcurrentDictionary <long, CacheEntry> entriesForThisRoot;

                var entryToRemove = entriesOrderedByValue[index++];

                if (!_cacheEntries.TryGetValue(entryToRemove.Entry.AggregateRootId, out entriesForThisRoot))
                {
                    continue;
                }

                CacheEntry removedEntry;

                var entrySuccessfullyRemoved = entriesForThisRoot.TryRemove(entryToRemove.Entry.GlobalSequenceNumber, out removedEntry);

                if (entrySuccessfullyRemoved)
                {
                    removalsToPerform--;

                    Interlocked.Decrement(ref _currentNumberOfCacheEntries);
                }
            }

            if (removalsToPerform > 0)
            {
                _logger.Debug("Cache trimming could not remove {0} cache entries (no worries, they have probably been removed by another thread)", removalsToPerform);
            }
        }
        public static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext)
        {
            var allDiagnostics = ImmutableArray<Diagnostic>.Empty;
            var projectsToFix = ImmutableArray<Project>.Empty;

            var document = fixAllContext.Document;
            var project = fixAllContext.Project;

            switch (fixAllContext.Scope)
            {
            case FixAllScope.Document:
                if (document != null)
                {
                    var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
                    return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty.SetItem(document, documentDiagnostics);
                }

                break;

            case FixAllScope.Project:
                projectsToFix = ImmutableArray.Create(project);
                allDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, project).ConfigureAwait(false);
                break;

            case FixAllScope.Solution:
                projectsToFix = project.Solution.Projects
                    .Where(p => p.Language == project.Language)
                    .ToImmutableArray();

                var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>();
                var tasks = new Task[projectsToFix.Length];
                for (int i = 0; i < projectsToFix.Length; i++)
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    var projectToFix = projectsToFix[i];
                    tasks[i] = Task.Run(
                        async () =>
                        {
                            var projectDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, projectToFix).ConfigureAwait(false);
                            diagnostics.TryAdd(projectToFix.Id, projectDiagnostics);
                        }, fixAllContext.CancellationToken);
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);
                allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value.Where(x => fixAllContext.DiagnosticIds.Contains(x.Id))));
                break;
            }

            if (allDiagnostics.IsEmpty)
            {
                return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
            }

            return await GetDocumentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false);
        }
Example #25
0
        public void Render(int centerTileX, int centerTileY, int renderRange)
        {
            // todo implement global model
            if (!_isTiled)
            {
                return;
            }

            var wmoProgram      = ShaderProgramCache.Instance.Get("wmo");
            var view            = Matrix4.Mult(Game.Camera.View, Game.Camera.Projection);
            var cameraDirection = Game.Camera.Forward;

            wmoProgram.Use();
            wmoProgram.UniformMatrix("projection_view", false, ref view);
            wmoProgram.UniformVector("camera_direction", ref cameraDirection);
            wmoProgram.UniformVector("object_color", ref WMO_COLOR);

            foreach (var kv in _grids)
            {
                var xInRange = Math.Abs(kv.Value.X - centerTileX) <= renderRange;
                var yInRange = Math.Abs(kv.Value.Y - centerTileY) <= renderRange;

                if (!xInRange || !yInRange)
                {
                    kv.Value.RemoveInstances();
                }
            }

            for (var i = centerTileY - renderRange; i <= centerTileY + renderRange; ++i)
            {
                for (var j = centerTileX - renderRange; j <= centerTileX + renderRange; ++j)
                {
                    if (!_grids.TryGetValue(PackTile(j, i), out var gridRenderer))
                    {
                        LoadGrid(j, i);
                    }
                    else
                    {
                        gridRenderer.AddInstances();
                    }
                }
            }

            // Now that all instances are added, render everything in one single pass
            foreach (var kv in _grids.SelectMany(grid => grid.Value.Models).Distinct())
            {
                var worldModel = WorldModelCache.OpenInstance(_directory, kv);
                if (worldModel == null)
                {
                    continue;
                }

                worldModel.Render();
            }
        }
 public IEnumerable <StoredObjectDto> ListObjects()
 {
     lock (stores) {
         return(stores.SelectMany(pair => {
             return pair.Value.ListObjects().Select(objectDto => {
                 objectDto.PartitionId = pair.Key;
                 return objectDto;
             });
         }));
     }
 }
Example #27
0
        public Automaton(params State[] states)
        {
            foreach (var state in states)
            {
                SetState(state);
            }

            var letters = states.SelectMany(x => x.GetPossibleLetters()).Distinct().ToArray();

            Letters = letters;
        }
Example #28
0
        public JsonStringLocalizer()
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Resources/Resource.json");

            using (StreamReader reader = File.OpenText(path))
            {
                var jObject = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
                _resource  = JsonConvert.DeserializeObject <ConcurrentDictionary <string, ConcurrentDictionary <string, string> > >(jObject.ToString());
                _languages = new HashSet <string>(_resource.SelectMany(r => r.Value).Select(r => r.Key).Distinct());
            }
        }
Example #29
0
        public IList <IRelation> GetReversedRelationships(Type entityType)
        {
            Type[] typeList = ReflectionUtils.GetSuperTypesWithInterfacesImplemented(entityType,
                                                                                     new Type[]
                                                                                     { typeof(IReadOnlyEntity) });

            return(Cache.SelectMany(c => c.Value.Relations)
                   .Where(r => !r.ReverseRelationship &&
                          !r.NonIdentifyingRelation &&
                          typeList.Contains(r.RelatedObjectType))
                   .Select(r => r).ToList());
        }
Example #30
0
 /// WARNING: if partitionKey is null, this API is slow as it loads all tokens, not just from 1 partition.
 /// It should only support external token caching, in the hope that the external token cache is partitioned.
 public virtual List <MsalAccountCacheItem> GetAllAccounts(string partitionKey = null, ICoreLogger requestlogger = null)
 {
     if (string.IsNullOrEmpty(partitionKey))
     {
         return(AccountCacheDictionary.SelectMany(dict => dict.Value).Select(kv => kv.Value).ToList());
     }
     else
     {
         AccountCacheDictionary.TryGetValue(partitionKey, out ConcurrentDictionary <string, MsalAccountCacheItem> partition);
         return(partition?.Select(kv => kv.Value)?.ToList() ?? CollectionHelpers.GetEmptyList <MsalAccountCacheItem>());
     }
 }
Example #31
0
        public void Dispose()
        {
            var allSingletons = singletons.SelectMany(x => x.Value.Cast <object>()).Select(x => x as IDisposable)
                                .Where(x => x != null)
                                .Concat(singletonsDisposableInstancesRegistered)
                                .Distinct(new ReferenceEqualityComparar());

            foreach (var disposableSingleton in allSingletons)
            {
                disposableSingleton.Dispose();
            }
            singletonsDisposableInstancesRegistered.Clear();
            singletons.Clear();
        }
        public IActionResult Index(string repoSet)
        {
            var gitHubAccessToken = Context.Session.GetString("GitHubAccessToken");
            var gitHubName = Context.Session.GetString("GitHubName");

            // If session state didn't have our data, either there's no one logged in, or they just logged in
            // but the claims haven't yet been read.
            if (string.IsNullOrEmpty(gitHubAccessToken))
            {
                if (!User.Identity.IsAuthenticated)
                {
                    // Not authenticated at all? Go to GitHub to authorize the app
                    return new ChallengeResult("GitHub", new AuthenticationProperties { RedirectUri = "/" + repoSet });
                }

                // Authenticated but haven't read the claims? Process the claims
                gitHubAccessToken = Context.User.FindFirst("access_token")?.Value;
                gitHubName = Context.User.Identity.Name;
                Context.Session.SetString("GitHubAccessToken", gitHubAccessToken);
                Context.Session.SetString("GitHubName", gitHubName);
            }

            // Authenticated and all claims have been read

            var repos =
                RepoSets.HasRepoSet(repoSet ?? string.Empty)
                ? RepoSets.GetRepoSet(repoSet)
                : RepoSets.GetAllRepos();

            var allIssuesByRepo = new ConcurrentDictionary<string, Task<IReadOnlyList<Issue>>>();
            var allPullRequestsByRepo = new ConcurrentDictionary<string, Task<IReadOnlyList<PullRequest>>>();

            Parallel.ForEach(repos, repo => allIssuesByRepo[repo] = GetIssuesForRepo(repo, GetGitHubClient(gitHubAccessToken)));
            Parallel.ForEach(repos, repo => allPullRequestsByRepo[repo] = GetPullRequestsForRepo(repo, GetGitHubClient(gitHubAccessToken)));

            Task.WaitAll(allIssuesByRepo.Select(x => x.Value).ToArray());
            Task.WaitAll(allPullRequestsByRepo.Select(x => x.Value).ToArray());

            var allIssues = allIssuesByRepo.SelectMany(
                issueList => issueList.Value.Result.Select(
                    issue => new IssueWithRepo
                    {
                        Issue = issue,
                        RepoName = issueList.Key,
                    })).ToList();

            var allPullRequests = allPullRequestsByRepo.SelectMany(
                pullRequestList => pullRequestList.Value.Result.Select(
                    pullRequest => new PullRequestWithRepo
                    {
                        PullRequest = pullRequest,
                        RepoName = pullRequestList.Key,
                    }))
                    .OrderBy(pullRequestWithRepo => pullRequestWithRepo.PullRequest.CreatedAt)
                    .ToList();

            return View(new HomeViewModel
            {
                TotalIssues = allIssues.Count,

                Name = gitHubName,

                GroupByAssignee = new GroupByAssigneeViewModel
                {
                    Assignees =
                        allIssues
                            .GroupBy(issue => issue.Issue.Assignee?.Login)
                            .Select(group =>
                                new GroupByAssigneeAssignee
                                {
                                    Assignee = group.Key,
                                    Issues = group.ToList().AsReadOnly(),
                                })
                            .OrderBy(group => group.Assignee, StringComparer.OrdinalIgnoreCase)
                            .ToList()
                            .AsReadOnly()
                },

                GroupByMilestone = new GroupByMilestoneViewModel
                {
                    Milestones =
                        allIssues
                            .GroupBy(issue => issue.Issue.Milestone?.Title)
                            .Select(group =>
                                new GroupByMilestoneMilestone
                                {
                                    Milestone = group.Key,
                                    Issues = group.ToList().AsReadOnly(),
                                })
                            .OrderBy(group => group.Milestone, StringComparer.OrdinalIgnoreCase)
                            .ToList()
                            .AsReadOnly()
                },

                GroupByRepo = new GroupByRepoViewModel
                {
                    Repos =
                        allIssues
                            .GroupBy(issue => issue.RepoName)
                            .Select(group =>
                                new GroupByRepoRepo
                                {
                                    RepoName = group.Key,
                                    Issues = group.ToList().AsReadOnly(),
                                })
                            .OrderByDescending(group => group.Issues.Count)
                            .ToList()
                            .AsReadOnly()
                },

                PullRequests = allPullRequests,
            });
        }
Example #33
0
        public void Run(int queries, int threads, int prepared)
        {
            Console.WriteLine("Preparing...");
            _queries = queries;
            _manager = new CartManager();
            _times = new ConcurrentDictionary<string, LinkedList<long>>();
            _stopwatch = new Stopwatch();
            _count = 0;
            _groups = Enumerable.Range(0, 9).Select(n => "group_" + n).ToArray();


            //pregenerate carts
            _manager.PrepareDbAsync().Wait();
            var cartTasks = new Task<Cart>[prepared];
            int groupId = 0;
            for (int i = 0; i < prepared; i++)
            {
                cartTasks[i] = _manager.AddCartAsync(_groups[groupId]);
                groupId = (groupId + 1) % _groups.Length;
            }

            Task.WaitAll(cartTasks);
            var carts = cartTasks.Select(t => t.Result).ToArray();

            Console.WriteLine("Executing...");

            //execute!
            _stopwatch.Start();
            var doTasks = new LinkedList<Task>();

            for (int i = 0; i < threads; i++)
            {
                doTasks.AddLast(DoAddCarts());
                doTasks.AddLast(DoAddItems(carts));
                //doTasks.AddLast(DoFindByGroupId());
                doTasks.AddLast(DoGetItems(carts));
                doTasks.AddLast(DoUpdateCarts(carts));
            }

            Task.WaitAll(doTasks.ToArray());

            _stopwatch.Stop();

            //print results
            Console.WriteLine("Total tasks run: {0} in {1} ({2} req/s)", _count, _stopwatch.Elapsed,
                              DoubleString((double)queries / _stopwatch.ElapsedMilliseconds * 1000));

#if debug
            Console.WriteLine(MemoryPool.Instance);
#endif
            Console.WriteLine();
            WriteRow("", "Calls", "Avg", "Median", "Min", "Max");
            WriteStatistics("Total", _times.SelectMany(vls => vls.Value));
            Console.WriteLine(new string('-', 60));
            foreach (var call in _times)
            {
                WriteStatistics(call.Key, call.Value);
            }
        }