示例#1
0
        public async Task <IEnumerable <object> > DoctorScheduleList(decimal doctorId, bool showRecent, DateTime?start,
                                                                     DateTime?end, int?limit, int?skip)
        {
            var query = _context.Reservation
                        .Where(d => d.DoctorId == doctorId)
                        .Where(x => x.Starttime.Date >= start.Value.Date && x.Endtime.Date <= end.Value.Date);

            query = showRecent
                ? query.Where(x => x.Visit != null && x.Canceled == false).Where(x => x.Starttime.AddMinutes(-30) < DateTime.Now)
                : query.Where(x => x.Visit == null).Where(x => x.Starttime.AddMinutes(30) >= DateTime.Now);

            var anonymousQuery = query.Select(s => new
            {
                reservationId        = s.Id,
                reservationStartTime = s.Starttime,
                reservationEndTime   = s.Endtime,
                isCanceled           = s.Canceled,
                localName            = s.Room.Local.Name,
                roomNumber           = s.Room.Number,
                patientId            = s.Patient.Id,
                patientName          = s.Patient.IdNavigation.Name,
                patientLastname      = s.Patient.IdNavigation.Lastname,
                visit = _context.Visit.FirstOrDefault(y => y.ReservationId == s.Id)
            });

            IOrderedQueryable <object> orderedQuery = showRecent
                ? anonymousQuery.OrderByDescending(x => x.reservationStartTime)
                : anonymousQuery.OrderBy(x => x.reservationStartTime);

            var trimmedQuery = PaginationService <object> .SplitAndLimitQueryable(skip, limit, orderedQuery);

            return(await trimmedQuery.ToListAsync());
        }
示例#2
0
        public void Refresh(CriteriaType criteriaType, TCriteria criteria)
        {
            Busy = true;
            Guid refreshGuid = Guid.NewGuid();

            _refreshGuid = refreshGuid;
            PaginationService.GetItems(criteriaType, PageSize, criteria, items => {
                if (_refreshGuid != refreshGuid)
                {
                    return;
                }
                _dispatcher.Invoke(() => {
                    CriteriaType = criteriaType;
                    if (criteriaType == CriteriaType.DownFromInfinity && items.Any())
                    {
                        Criteria = _getCriteriaFunc(items.First());
                    }
                    else if (criteriaType == CriteriaType.UpFromInfinity && items.Any())
                    {
                        Criteria = _getCriteriaFunc(items.Last());
                    }
                    else
                    {
                        Criteria = criteria;
                    }
                    UpdateItems(items);
                    Busy = false;
                });
            });
        }
示例#3
0
        public void PaginationGettingTotalPagesWorks()
        {
            List <Article> data = new List <Article>
            {
                new Article {
                    Id = 0, Title = "T0"
                },
                new Article {
                    Id = 1, Title = "T1"
                },
                new Article {
                    Id = 2, Title = "T2"
                },
                new Article {
                    Id = 3, Title = "T3"
                },
                new Article {
                    Id = 4, Title = "T4"
                },
            };
            int pageSize = 2;

            int totalPages = PaginationService.GetTotalPages(data, pageSize);

            Assert.IsTrue(totalPages == 3);
        }
示例#4
0
        public async Task <Pagination <ProductListResponseModel> > GetAllProducts(ProductListRequestModel requestModel)
        {
            var parameters = new DynamicParameters();

            parameters.Add("@PageSize", requestModel.PageSize);
            parameters.Add("@Offset", requestModel.Page);

            await using var connection = _dbConnection.CreateDbConnection();
            var products = await connection.QueryMultipleAsync(ProductQuery(requestModel), parameters);

            var productListResponseModel = new ProductListResponseModel();

            var productResult = products.Read <ProductServiceResponseModel, CategoryServiceResponseModel, ProductListResponseModel>
                                    ((product, category) => {
                product.CategoryServiceResponseModel = category;
                productListResponseModel.ProductServiceResponseModel = product;

                return(productListResponseModel);
            }
                                    , splitOn: "CategoryId");

            var totalItemCount = products.Read <int>().FirstOrDefault();

            var productResponse = PaginationService.GetPagination(
                productResult.AsQueryable(),
                requestModel.Page.Value,
                string.Empty,
                true,
                requestModel.PageSize.Value);

            return(productResponse);
        }
示例#5
0
        public void PaginationWorks()
        {
            List <Article> data = new List <Article>
            {
                new Article {
                    Id = 0, Title = "T0"
                },
                new Article {
                    Id = 1, Title = "T1"
                },
                new Article {
                    Id = 2, Title = "T2"
                },
                new Article {
                    Id = 3, Title = "T3"
                },
                new Article {
                    Id = 4, Title = "T4"
                },
            };
            int pageSize = 2;

            var res0 = PaginationService.Paginate(data, 2, pageSize).ToList();
            var res1 = PaginationService.Paginate(data, 3, pageSize).ToList();
            var res2 = PaginationService.Paginate(data, 4, pageSize).ToList();

            Assert.IsTrue(res0.Count() == 2);
            Assert.IsTrue(res1.Count() == 1);
            Assert.IsTrue(res2.Count() == 0);
            Assert.IsTrue(res0[0].Title == "T2");
            Assert.IsTrue(res1[0].Title == "T4");
        }
示例#6
0
        public async Task <IEnumerable <object> > GetAllWithRoles(int?limit, int?skip)
        {
            var query = _context.Person
                        .Select(x => new
            {
                id        = x.Id,
                name      = x.Name,
                lastname  = x.Lastname,
                email     = x.Email,
                gender    = x.Gender,
                birthdate = x.Birthdate,
                pesel     = x.Pesel,
                userroles = _context.Userroles
                            .Where(u => u.PersonId == x.Id)
                            .Select(u => new
                {
                    roleId      = u.RoleId,
                    dateofissue = u.Dateofissue,
                    personId    = u.PersonId,
                    roleName    = u.Role.Name
                })
            })
                        .OrderBy(x => x.lastname)
                        .ThenBy(x => x.name);

            var trimmed = PaginationService <object> .SplitAndLimitQueryable(skip, limit, query);

            return(await trimmed.ToListAsync());
        }
        private static PaginationModel <ImageLikesModel> BuildEditPaginationModel <TFinder>
            (PaginationService <Picture, TFinder> pagination,
            int pageNumber, int userId)
            where TFinder : PaginationFinder <Picture>
        {
            var pictures = pagination.GetPageObjects(pageNumber);

            var models = new List <ImageLikesModel>(12);

            var dao = new VoteFindDao();

            var ownerDao = new VoteOwnerDao();

            models.AddRange(pictures.Select(picture => new ImageLikesModel
            {
                VotesModel = new VotesModel
                {
                    Dislikes = dao.GetDislikesVoteCount(picture.PictureId),
                    Likes    = dao.GetLikesVoteCount(picture.PictureId),
                    IsOwner  = ownerDao.CheckOwner(userId, picture.PictureId)
                },
                ImageModel = new ImageEditModel
                {
                    PictureUrl = picture.PictureUrl, PictureId = picture.PictureId
                }
            }));


            return(new PaginationModel <ImageLikesModel>
            {
                ObjectsList = models,
                PagesCount = pagination.GetPagesCount(),
                PageNumber = pageNumber
            });
        }
        public BaseServiceTest()
        {
            // Настройка тестовых строк подключения.
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

            AppConfiguration    = builder.Build();
            MsSqlConfigString   = AppConfiguration["ConnectionStrings:TestMsSqlConnection"];
            PostgreConfigString = AppConfiguration["ConnectionStrings:TestNpgSqlConnection"];

            // Настройка тестовых контекстов.
            var optionsMsSqlBuilder = new DbContextOptionsBuilder <ApplicationDbContext>();

            optionsMsSqlBuilder.UseSqlServer(MsSqlConfigString);
            ApplicationDbContext = new ApplicationDbContext(optionsMsSqlBuilder.Options);

            var optionsBuilder = new DbContextOptionsBuilder <PostgreDbContext>();

            optionsBuilder.UseNpgsql(PostgreConfigString);
            PostgreContext = new PostgreDbContext(optionsBuilder.Options);

            // Настройка экземпляров сервисов для тестов.
            UserService       = new UserService(null, PostgreContext, null, null);
            ExecutorService   = new ExecutorService(null, PostgreContext, UserService);
            PaginationService = new PaginationService(PostgreContext, UserService);
        }
示例#9
0
        public async Task <PagedResultBase <DigitalAccountTransactionModel> > GetFilterAsync(DateTime startDate, DateTime endDate, int page, int pageSize)
        {
            var query = _appDbContext.DigitalAccountTransactions.Where(c => c.CreatedDate.Date >= startDate.Date &&
                                                                       c.CreatedDate.Date <= endDate.Date);

            return(await PaginationService.GetPagination(query, page, pageSize));
        }
示例#10
0
        public void PageCount(int pageSize, int totalEntries, int expectedPages)
        {
            var range  = Enumerable.Range(1, totalEntries).AsQueryable();
            var result = PaginationService.Paginate(range, 1, pageSize);

            Assert.Equal(expectedPages, result.PageCount);
        }
示例#11
0
        private async Task OnReactionAddedAsync(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            InternalStatistics.IncrementEvent("ReactionAdded");

            using var scope = Provider.CreateScope();
            await scope.ServiceProvider.GetService <EmoteStats>().IncrementFromReactionAsync(reaction);

            if (reaction.User.IsSpecified && reaction.User.Value.IsUser())
            {
                await PaginationService.HandleReactionAsync(reaction);

                await scope.ServiceProvider.GetService <UserReactionsService>().IncrementReactionStatsAsync(reaction);

                await scope.ServiceProvider.GetService <ReminderService>().HandleRemindCopyAsync(reaction);

                if (channel is SocketTextChannel textChannel)
                {
                    await scope.ServiceProvider.GetService <PointsService>().IncrementPointsAsync(textChannel.Guild, reaction);
                }

                if (message.HasValue)
                {
                    await scope.ServiceProvider.GetService <ReminderService>().PostponeReminderAsync(message.Value, reaction);
                }
            }
        }
示例#12
0
        public LaunchesListCommands(OddityCore oddity, PaginationService paginationService, CacheService cacheService, LaunchesListTableGenerator launchesListTableGenerator)
        {
            _oddity                     = oddity;
            _paginationService          = paginationService;
            _cacheService               = cacheService;
            _launchesListTableGenerator = launchesListTableGenerator;

            _allowedPaginationTypes = new List <CacheContentType>
            {
                CacheContentType.UpcomingLaunches,
                CacheContentType.PastLaunches,
                CacheContentType.AllLaunches,
                CacheContentType.FailedStarts,
                CacheContentType.FailedLandings,
                CacheContentType.LaunchesWithOrbit
            };

            Bot.Client.MessageReactionAdded += Client_MessageReactionAddedAsync;

            _cacheService.RegisterDataProvider(CacheContentType.UpcomingLaunches, async p => await _oddity.LaunchesEndpoint.GetUpcoming().ExecuteAsync());
            _cacheService.RegisterDataProvider(CacheContentType.PastLaunches, async p => await _oddity.LaunchesEndpoint.GetPast().ExecuteAsync());
            _cacheService.RegisterDataProvider(CacheContentType.AllLaunches, async p => await _oddity.LaunchesEndpoint.GetAll().ExecuteAsync());
            _cacheService.RegisterDataProvider(CacheContentType.FailedStarts, async p =>
            {
                var result = await _oddity.LaunchesEndpoint.Query()
                             .WithFieldEqual(q => q.Success, false)
                             .WithLimit(1000)
                             .ExecuteAsync();

                return(result.Data);
            });
        }
示例#13
0
        public async Task Call_TotalPages_should_invoke_TotalNumberOfRecords()
        {
            paginationService = new PaginationService <WeatherHistory>(pagination.Object, pageLinkFactory.Object);
            await paginationService.TotalPages();

            pagination.Verify(x => x.TotalNumberOfRecords(), Times.Once);
        }
        public async Task <IEnumerable <Oldmedicinehistory> > GetAll(int?limit, int?skip)
        {
            var query   = _context.Oldmedicinehistory.OrderByDescending(x => x.Date);
            var trimmed = (IOrderedQueryable <Oldmedicinehistory>) PaginationService <Oldmedicinehistory> .SplitAndLimitQueryable(skip, limit, query);

            return(await trimmed.ToListAsync());
        }
        private async Task OnMessageDeletedAsync(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel)
        {
            InternalStatistics.IncrementEvent("MessageDeleted");
            if (channel is IPrivateChannel || (message.HasValue && !message.Value.Author.IsUser()))
            {
                return;
            }

            SocketGuildUser user = null;

            if (message.HasValue && message.Value.Author is SocketGuildUser guildUser)
            {
                user = guildUser;
            }
            else if (MessageCache.Exists(message.Id))
            {
                var author = MessageCache.Get(message.Id).Author;
                user = author is SocketGuildUser socketGuildUser ? socketGuildUser : null;
            }

            using var scope = Provider.CreateScope();

            if (user != null)
            {
                await scope.ServiceProvider.GetService <UserMessagesService>().DecrementMessageStats(user.Guild, user, channel);
            }

            await Logger.OnMessageDelete(message, channel).ConfigureAwait(false);

            PaginationService.DeleteEmbed(message.Id);
        }
        public void Test_GetPage(int page, int expected)
        {
            var cut = new PaginationService(100, 10);

            var actual = cut.GetPage(page);

            Assert.Equal(expected, actual);
        }
示例#17
0
        public async Task <IEnumerable <object> > GetAllByName(string name, int?limit, int?skip)
        {
            var query = _table.Where(x => name == null || x.Name.ToLower().Contains(name.ToLower())).OrderBy(x => x.Name);

            var orderedQuery = PaginationService <T> .SplitAndLimitQueryable(skip, limit, query);

            return(await orderedQuery.ToListAsync());
        }
示例#18
0
        public void CustomCountPageCount(int pageSize, int expectedPages)
        {
            var range = Enumerable.Range(1, 10).AsQueryable();

            var result = PaginationService.Paginate(range, 1, pageSize, (x) => 400);

            Assert.Equal(expectedPages, result.PageCount);
        }
示例#19
0
 public ReactionAddedHandler(DiscordSocketClient client, InternalStatistics internalStatistics, PaginationService paginationService,
                             IServiceProvider provider)
 {
     Client             = client;
     InternalStatistics = internalStatistics;
     PaginationService  = paginationService;
     Provider           = provider;
 }
示例#20
0
 public GCSearchController(IScopeProvider scopeProvider)
 {
     QueriesRepository  = new QueriesRepository();
     SettingsRepository = new SettingsRepository();
     PaginationService  = new PaginationService();
     NodeService        = new NodeService();
     _scopeProvider     = scopeProvider;
 }
示例#21
0
        public async Task CustomAsyncCountPageCount(int pageSize, int expectedPages)
        {
            var range = Enumerable.Range(1, 10).AsQueryable();

            var result = await PaginationService.PaginateAsync(range, 1, pageSize, (x) => Task.FromResult(400));

            Assert.Equal(expectedPages, result.PageCount);
        }
示例#22
0
 public MessageUpdatedHandler(DiscordShardedClient s, DatabaseService d, PaginationService p)
 {
     this.database              = d;
     this.shard                 = s;
     this.paginationService     = p;
     this.shard.MessageUpdated += ShardOnMessageUpdated;
     this.logger.Information("Registered");
 }
        public void Test_PageRange(int records, int recordsPerPage, int expected)
        {
            var cut = new PaginationService(records, recordsPerPage);

            var actual = cut.PageRange.Max;

            Assert.Equal(expected, actual);
            Assert.Equal(1, cut.PageRange.Min);
        }
示例#24
0
        protected async Task SendPaginatedEmbedAsync(PaginatedEmbed embed)
        {
            if (PaginationService == null)
            {
                throw new InvalidOperationException("Paginated embed requires PaginationService");
            }

            await PaginationService.SendPaginatedMessage(embed, async embed => await ReplyAsync(embed: embed));
        }
示例#25
0
        public TrueShipCommonService(TrueShipConfiguration config, IWebRequestServices webRequestServices)
        {
            Condition.Requires(config, "config").IsNotNull();
            Condition.Requires(webRequestServices, "webRequestServices").IsNotNull();

            this._webRequestServices = webRequestServices;
            this._requestService     = new RequestCreatorService(config.Credentials.AccessToken);
            this._paginationService  = new PaginationService(this._webRequestServices);
        }
示例#26
0
        private async Task OnReactionAddedAsync(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            InternalStatistics.IncrementEvent("ReactionAdded");

            EmoteStats.IncrementFromReaction(reaction);
            await PaginationService.HandleReactionAsync(reaction);

            UserService.IncrementReaction(reaction);
        }
示例#27
0
 public ReactionAddedHandler(DiscordSocketClient client, EmoteStats emoteStats, InternalStatistics internalStatistics,
                             PaginationService paginationService, UserService userService)
 {
     Client             = client;
     EmoteStats         = emoteStats;
     InternalStatistics = internalStatistics;
     PaginationService  = paginationService;
     UserService        = userService;
 }
示例#28
0
 public MessageDeletedHandler(DiscordSocketClient client, InternalStatistics internalStatistics,
                              PaginationService paginationService, IMessageCache messageCache, IServiceProvider provider)
 {
     Client             = client;
     InternalStatistics = internalStatistics;
     PaginationService  = paginationService;
     MessageCache       = messageCache;
     Provider           = provider;
 }
示例#29
0
        public async Task StartAsync(bool sleep = true)
        {
            var config = Configuration.Config;

            _client = new DiscordShardedClient(new DiscordSocketConfig
            {
                AlwaysDownloadUsers = true,
                LogLevel            = Discord.LogSeverity.Info,
                MessageCacheSize    = 1000
            });



            _services = new ServiceCollection()
                        .AddSingleton(_client)
                        .AddSingleton(Audio.AudioService.Instance)
                        .BuildServiceProvider();

            _commands = new CommandHandler(_client,
                                           new CommandService(new CommandServiceConfig
            {
                LogLevel       = LogSeverity.Info,
                DefaultRunMode = RunMode.Async
            }),
                                           _services);

            new Logger(new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/Logs", add: true);

            _client.ShardReady += ShardReady;
            _client.Log        += Log;

            Databases.Users = await DataBase <long, UserData> .Async(new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/Databases/Users.db", x =>
            {
                UserData retVal = new UserData
                {
                    Key             = x,
                    Prefix          = ".f",
                    SendCompMessage = true
                };
                return(retVal);
            });

            paginationService = new PaginationService <DiscordShardedClient>(_client);

            await _commands.InitializeAsync();

            _ = Commands;
            await _client.LoginAsync(TokenType.Bot, config.Token);

            await _client.StartAsync();

            if (sleep)
            {
                await Task.Delay(-1);
            }
        }
示例#30
0
        public async Task InitMyCustomerPaginationTestAsync()
        {
            var mock = new Mock <IPaginationService>();

            mock.Setup(a => a.InitMyCustomerPaginationAsync(1, "petya")).Returns(Task.FromResult(new IndexOutput()));
            var component = new PaginationService(PostgreContext, UserService);
            var result    = await component.InitMyCustomerPaginationAsync(3, "petya");

            Assert.IsNotNull(result);
        }