async private Task Using(Func <DbSet <TModel>, Task> func)
 {
     using (var context = _pool.Rent())
     {
         await func(context.Set <TModel>());
     }
 }
Example #2
0
 async private Task Using(Func <BlogDbContext, Task> func)
 {
     using (var ctx = _context.Rent())
     {
         await Task.Run(() => func(ctx));
     }
 }
Example #3
0
        private async Task Handler(ShowStart showMessage, string lockToken, CancellationToken ct)
        {
            if (!showMessage.IsValid())
            {
                _logger.LogError("Invalid ShowStart message received");
                await _client.CompleteAsync(lockToken).ConfigureAwait(false);

                return;
            }

            var show = new Show
            {
                Place             = showMessage.Place,
                Presenter         = showMessage.Presenter,
                Slug              = showMessage.Slug,
                HighestSlideShown = 0,
                Title             = showMessage.Title,
                Time              = showMessage.Time
            };

            using (var context = _contextPool.Rent())
            {
                if (!await context.Shows.AnyAsync(
                        s => s.Place == show.Place && s.Presenter == show.Presenter && s.Slug == show.Slug, ct))
                {
                    context.Shows.Add(show);
                    await context.SaveChangesAsync(ct).ConfigureAwait(false);
                }
            }

            await _client.CompleteAsync(lockToken).ConfigureAwait(false);
        }
Example #4
0
        private static void PerformanceCacheDbTest(SelectTestDefinition[] testDefinitions, int testCount)
        {
            var pool = new DbContextPool <OrderContext>(OrderContextOptions.Create(true, null));

            Db.OeEntitySetAdapterCollection entitySetAdapters = new OrderDbDataAdapter(false, false, null).EntitySetAdapters;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var stopWatch = new Stopwatch();

            stopWatch.Start();
            for (int i = 0; i < testCount; i++)
            {
                foreach (SelectTestDefinition testDefinition in testDefinitions)
                {
                    OrderContext dbContext = pool.Rent();
                    testDefinition.ExecutorDb(entitySetAdapters, dbContext);
                    pool.Return(dbContext);
                }
            }
            stopWatch.Stop();
            Console.WriteLine("Entity Framework " + stopWatch.Elapsed);
        }
Example #5
0
        public virtual async Task CreateAsync(User user, bool orUpdate = false, CancellationToken cancellationToken = default)
        {
            using var lease = DbContextPool.Rent();
            var dbContext    = lease.Subject;
            var existingUser = (User?)null;

            var supportTransactions = !dbContext.Database.IsInMemory();

            await using var tx = supportTransactions
                ? await dbContext.Database.BeginTransactionAsync(cancellationToken)
                : (IDbContextTransaction?)null;

            var userId = user.Id;

            if (orUpdate)
            {
                existingUser = await dbContext.Users.FindAsync(new [] { (object)userId }, cancellationToken);

                if (existingUser != null)
                {
                    dbContext.Users.Update(user);
                }
            }
            if (existingUser == null)
            {
                dbContext.Users.Add(user);
            }
            await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            await(tx?.CommitAsync(cancellationToken) ?? Task.CompletedTask);
            Invalidate(user, existingUser == null);
        }
Example #6
0
        public virtual async Task UpdateAsync(User user, CancellationToken cancellationToken = default)
        {
            await using var dbContext = DbContextPool.Rent();
            dbContext.Users.Update(user);
            await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            Invalidate(user, false);
        }
Example #7
0
        public virtual async Task <long> CountAsync(CancellationToken cancellationToken = default)
        {
            await Everything().ConfigureAwait(false);

            await using var dbContext = DbContextPool.Rent();
            var count = await dbContext.Users.LongCountAsync(cancellationToken).ConfigureAwait(false);

            // _log.LogDebug($"Users.Count query: {count}");
            return(count);
        }
Example #8
0
        public async Task <string> ToOsuString(DbContextPool <SoraDbContext> ctxPool)
        {
            var returnString = string.Empty;

            if (_bm == null)
            {
                Logger.Err("Failed to set Beatmap! Beatmap is null!");
                return($"{(int) RankedStatus.NeedUpdate}|false\n");
            }

            var count = 0;

            if (_ownScore != null)
            {
                var ctx = ctxPool.Rent();
                try
                {
                    returnString += $"{_ownScore?.ToOsuString(ctx)}\n";
                }
                finally
                {
                    ctxPool.Return(ctx);
                }
            }

            await foreach (var score in _scores)
            {
                count++;
                var ctx = ctxPool.Rent();
                try
                {
                    returnString += $"{score.ToOsuString(ctx)}\n";
                }
                finally
                {
                    ctxPool.Return(ctx);
                }
            }

            return(ScoreboardHeader(count) + returnString);
        }
Example #9
0
        public virtual async Task <User?> TryGetAsync(long userId, CancellationToken cancellationToken = default)
        {
            // Debug.WriteLine($"TryGetAsync {userId}");
            await Everything().ConfigureAwait(false);

            await using var dbContext = DbContextPool.Rent();
            var user = await dbContext.Users
                       .FindAsync(new[] { (object)userId }, cancellationToken)
                       .ConfigureAwait(false);

            return(user);
        }
Example #10
0
        public override IEnumerable <DynamicPropertyInfo> GetStructuralProperties(String tableName)
        {
            SchemaContext schemaContext = _dbContextPool.Rent();

            foreach (DbColumn column in schemaContext.GetColumns(tableName))
            {
                DatabaseGeneratedOption databaseGenerated;
                if (column.IsIdentity.GetValueOrDefault())
                {
                    databaseGenerated = DatabaseGeneratedOption.Identity;
                }
                else if (column.IsExpression.GetValueOrDefault())
                {
                    databaseGenerated = DatabaseGeneratedOption.Computed;
                }
                else
                {
                    databaseGenerated = DatabaseGeneratedOption.None;
                }
                yield return(new DynamicPropertyInfo(column.ColumnName, column.DataType, databaseGenerated));
            }
            _dbContextPool.Return(schemaContext);
        }
Example #11
0
        public virtual async Task <bool> DeleteAsync(User user, CancellationToken cancellationToken = default)
        {
            Computed.GetCurrent().Should().BeNull();
            await using var dbContext = DbContextPool.Rent();
            dbContext.Users.Remove(user);
            try {
                await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

                Invalidate(user);
                return(true);
            }
            catch (DbUpdateConcurrencyException) {
                return(false);
            }
        }
Example #12
0
        protected override async Task <ILookup <int, Tag> > LoadGroupedBatchAsync(
            IReadOnlyList <int> keys, CancellationToken cancellationToken)
        {
            AppDbContext db = _dbPool.Rent();

            try
            {
                List <CardTag> tags = await db.Cards
                                      .Where(card => keys.Contains(card.Id))
                                      .Include(card => card.CardTags)
                                      .SelectMany(card => card.CardTags)
                                      .Include(cardTag => cardTag.Tag)
                                      .ToListAsync();

                return(tags.Where(t => t.Tag is {}).ToLookup(t => t.CardId, t => t.Tag !));
            }
Example #13
0
        protected override async Task <ILookup <int, Attendee> > LoadGroupedBatchAsync(
            IReadOnlyList <int> keys,
            CancellationToken cancellationToken)
        {
            ApplicationDbContext dbContext = _dbContextPool.Rent();

            try
            {
                List <SessionAttendee> speakers = await dbContext.Sessions
                                                  .Where(session => keys.Contains(session.Id))
                                                  .Include(session => session.SessionAttendees)
                                                  .SelectMany(session => session.SessionAttendees)
                                                  .ToListAsync();

                return(speakers.Where(t => t.Attendee is { }).ToLookup(t => t.SessionId, t => t.Attendee !));
            }
Example #14
0
        protected override async Task <IReadOnlyDictionary <int, Speaker> > LoadBatchAsync(
            IReadOnlyList <int> keys,
            CancellationToken cancellationToken)
        {
            ApplicationDbContext dbContext = _dbContextPool.Rent();

            try
            {
                return(await dbContext.Speakers
                       .Where(s => keys.Contains(s.Id))
                       .ToDictionaryAsync(t => t.Id, cancellationToken));
            }
            finally
            {
                _dbContextPool.Return(dbContext);
            }
        }
Example #15
0
        public override Object CreateDataContext()
        {
            T dbContext;

            if (_dbContextPool == null)
            {
                dbContext = Db.FastActivator.CreateInstance <T>();
            }
            else
            {
                dbContext = _dbContextPool.Rent();
            }

            dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
            dbContext.ChangeTracker.QueryTrackingBehavior    = QueryTrackingBehavior.NoTracking;
            return(dbContext);
        }
Example #16
0
        protected override async Task <ILookup <int, Session> > LoadGroupedBatchAsync(
            IReadOnlyList <int> keys,
            CancellationToken cancellationToken)
        {
            ApplicationDbContext dbContext = _dbContextPool.Rent();

            try
            {
                var sessions = await dbContext.Tracks
                               .Where(track => keys.Contains(track.Id))
                               .Include(track => track.Sessions)
                               .SelectMany(track => track.Sessions)
                               .ToListAsync();

                return(sessions.ToLookup(t => t.TrackId !.Value));
            }
            finally
            {
                _dbContextPool.Return(dbContext);
            }
        }
Example #17
0
        private async Task Handler(ShowSlide slide, string lockToken, CancellationToken ct)
        {
            if (!slide.IsValid())
            {
                _logger.LogError("Invalid ShowSlide message received");
                await _queueClient.CompleteAsync(lockToken).ConfigureAwait(false);
            }

            try
            {
                using (var context = _contextPool.Rent())
                {
                    await context.UpdateHighestShown(slide.Place, slide.Presenter, slide.Slug, slide.Number);
                }

                await _queueClient.CompleteAsync(lockToken).ConfigureAwait(false);

                _redis.PublishSlideAvailable(slide.Place, slide.Presenter, slide.Slug, slide.Number);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error updating database: {ex.Message}");
            }
        }
Example #18
0
        protected override void ThreadWorker()
        {
            while (!CancellationToken.IsCancellationRequested)
            {
                var dbContext = _dbContextPool.Rent();
                try
                {
                    var beatmaps = dbContext.BeatmapSet
                                   .Where(x => !x.Disabled)
                                   .AsEnumerable()
                                   .Where(x => x.LastChecked != null)
                                   .Where(
                        x => (
                            (
                                (
                                    x.RankedStatus == BeatmapSetOnlineStatus.None ||
                                    x.RankedStatus == BeatmapSetOnlineStatus.Loved
                                ) &&
                                (x.LastChecked.Value + TimeSpan.FromDays(90)).Subtract(DateTime.Now).TotalMilliseconds < 0
                            ) ||
                            (
                                (
                                    x.RankedStatus == BeatmapSetOnlineStatus.Pending ||
                                    x.RankedStatus == BeatmapSetOnlineStatus.Qualified ||
                                    x.RankedStatus == BeatmapSetOnlineStatus.WIP
                                ) &&
                                (x.LastChecked.Value + TimeSpan.FromDays(30)).Subtract(DateTime.Now).TotalMilliseconds < 0
                            ) ||
                            (
                                (
                                    x.RankedStatus == BeatmapSetOnlineStatus.Graveyard ||
                                    x.RankedStatus == BeatmapSetOnlineStatus.Ranked ||
                                    x.RankedStatus == BeatmapSetOnlineStatus.Approved
                                ) &&
                                (x.LastChecked.Value + TimeSpan.FromDays(365)).Subtract(DateTime.Now).TotalMilliseconds < 0
                            )
                            )

                        && !x.Disabled
                        );

                    foreach (var beatmap in beatmaps)
                    {
                        if (Tasks.Count > 128)
                        {
                            Task.WaitAll(Tasks.ToArray(), CancellationToken); // wait for all tasks
                            Tasks.Clear();                                    // Remove all previous tasks.
                        }

                        _requestLimiter.Limit();

                        Tasks.Add(Crawl(beatmap.SetId));
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e, "an Unknown error occured during HouseKeeping", LoggingTarget.Database);
                    SentrySdk.CaptureException(e);
                } finally {
                    _dbContextPool.Return(dbContext);
                }

                Thread.Sleep(TimeSpan.FromHours(8)); // Update every 8 hours...
            }
        }